-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpaligo.js
More file actions
255 lines (215 loc) · 8.38 KB
/
Copy pathpaligo.js
File metadata and controls
255 lines (215 loc) · 8.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* @description This script provides functions to interact with the Paligo API for publishing and managing documentation.
* It includes functions to list publish settings, create productions, download outputs, and extract files.
* It also provides middleware functions to update HTML content with custom scripts and styles.
*
* @see https://api.paligo.net/en/index-en.html
*/
const fs = require('fs');
const path = require('path');
const unzipper = require('unzipper');
const getPaligoApiKey = () => {
const { PALIGO_API_KEY } = process.env;
if (!PALIGO_API_KEY) {
throw new Error('PALIGO_API_KEY environment variable is not set.');
}
return PALIGO_API_KEY;
};
const LATEST_PALIGO_FILE = '.paligo.zip';
const listPublishSettings = async () => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Basic ${getPaligoApiKey()}`,
};
const response = await fetch('https://bitrise.paligoapp.com/api/v2/publishsettings/', {
method: 'GET',
headers,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
return response.json();
};
const listProductions = async () => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Basic ${getPaligoApiKey()}`,
};
const response = await fetch('https://bitrise.paligoapp.com/api/v2/productions/', {
method: 'GET',
headers,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
return response.json();
};
const createProduction = async (publishsetting) => {
const inputBody = JSON.stringify({ publishsetting });
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Basic ${getPaligoApiKey()}`,
};
const response = await fetch('https://bitrise.paligoapp.com/api/v2/productions/', {
method: 'POST',
body: inputBody,
headers,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
return response.json();
};
const showProduction = async (productionId) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Basic ${getPaligoApiKey()}`,
};
const response = await fetch(`https://bitrise.paligoapp.com/api/v2/productions/${productionId}`, {
method: 'GET',
headers,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
return response.json();
};
const pollProductionStatus = async (productionId, handleResponse) => {
const response = await showProduction(productionId);
if (handleResponse) handleResponse(response);
if (response.status !== 'done') {
return new Promise((resolve) => {
setTimeout(() => {
resolve(pollProductionStatus(productionId, handleResponse));
}, 5000); // Poll every 5 seconds
});
}
return response;
};
const getOutput = async (outputUrl, outputPath) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Basic ${getPaligoApiKey()}`,
};
const response = await fetch(outputUrl, {
method: 'GET',
headers,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await fs.promises.writeFile(outputPath, buffer);
return outputPath;
};
const getLastestOutput = async (latestOutputUrl, outputPath) => {
const response = await fetch(latestOutputUrl);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await fs.promises.writeFile(outputPath, buffer);
return outputPath;
};
const extractOutputFile = async (outputPath, extractPath) => {
await fs.promises.mkdir(extractPath, { recursive: true });
await fs
.createReadStream(outputPath)
.pipe(unzipper.Extract({ path: extractPath }))
.promise();
return extractPath;
};
const listFolders = async (dirPath) => {
const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
};
const pathExists = async (filePath) => {
return await fs.promises.access(filePath).then(() => true).catch(() => false);
};
const publish = async (publishsetting, outputPath, useLatest) => {
const tempPath = path.join(__dirname, 'temp');
if (!(await pathExists(tempPath))) {
await fs.promises.mkdir(tempPath, { recursive: true });
}
let outputFile;
if (useLatest) {
try {
const latestOutputUrl = `https://docs.bitrise.io/${LATEST_PALIGO_FILE}`;
process.stdout.write(`Downloading latest output file: ${latestOutputUrl}...\n`);
outputFile = await getLastestOutput(latestOutputUrl, path.join(tempPath, LATEST_PALIGO_FILE));
} catch (error) {
process.stderr.write(`Error downloading latest output file: ${error.message}\n`);
}
}
if (!outputFile) {
process.stdout.write('Creating a new production...\n');
const createProductionResponse = await createProduction(publishsetting);
process.stdout.write(`Production created: ${createProductionResponse.id}\n`);
productionId = createProductionResponse.id;
process.stdout.write('Building production...\n');
const productionStatus = await pollProductionStatus(productionId, (statusResponse) => {
process.stdout.write(` [${statusResponse.status}]`);
if (statusResponse.steps) process.stdout.write(` ${statusResponse.steps.count}/${statusResponse.steps.total}`);
if (statusResponse.message) process.stdout.write(`: ${statusResponse.message}`);
process.stdout.write('\n');
});
process.stdout.write(`Downloading output file: ${productionStatus.url}...\n`);
outputFile = await getOutput(productionStatus.url, path.join(tempPath, `${productionStatus.id}.zip`));
}
process.stdout.write(`Output file downloaded: ${outputFile}\nExtracting output file...\n`);
const extractPath = await extractOutputFile(outputFile, outputFile.replace('.zip', '/'));
process.stdout.write(`Output file extracted: ${extractPath}\nDeploying output...\n`);
if (await (pathExists(outputPath))) {
await fs.promises.rm(outputPath, { recursive: true, force: true });
}
const folders = await listFolders(extractPath);
await fs.promises.rename(path.join(extractPath, folders[0], 'out'), outputPath);
await fs.promises.rename(outputFile, path.join(outputPath, LATEST_PALIGO_FILE));
await fs.promises.rm(extractPath, { recursive: true, force: true });
process.stdout.write('Output deployed.\n\n');
};
if (process.argv[1] === __filename) {
const cli = async () => {
if (process.argv[2] === 'list') {
const settings = await listPublishSettings();
process.stdout.write('Available publish settings:\n');
console.log(settings);
settings.publishsettings?.forEach((setting) => {
process.stdout.write(`- ID: ${setting.id}, Name: ${setting.name}\n`);
});
} else if (process.argv[2] === 'publish' || process.argv[2] === 'download_latest') {
if (process.argv.length < 5) {
process.stderr.write(`Usage: node publish.js ${process.argv[2]} <publishsetting> <outputPath>\n`);
process.exit(1);
}
const publishsetting = process.argv[3];
const outputPath = process.argv[4];
await publish(publishsetting, outputPath, process.argv[2] === 'download_latest');
} else {
process.stderr.write(`
Usage: node publish.js <list|publish>
- list: List available publish settings
- publish <publishsetting> <outputPath>: Publish using the specified publish setting and output path
- download_latest <publishsetting> <outputPath>: Download the latest production for the specified publish setting and output path`);
process.exit(1);
}
process.exit(0);
};
cli().catch((error) => {
throw error;
});
}
module.exports = { pathExists, publish };