-
Notifications
You must be signed in to change notification settings - Fork 11
/
sync.js
386 lines (359 loc) · 11.8 KB
/
sync.js
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import fs from "fs";
import path from "path";
import { globby } from "globby";
import yaml from "js-yaml";
import axios from "axios";
import matter from "gray-matter";
import ejs from "ejs";
const yamlPatterns = ["**/*.yaml"];
const reThreeNumber = new RegExp("^v\\d+\\.\\d+.\\d+$");
const reFourNumber = new RegExp("^v\\d+.\\d+.\\d+.\\d+$");
const GITHUB_HTTP_BASE = "https://api.github.com";
const CONTENT_PREFIX = "https://raw.githubusercontent.com";
function getLink(organization, repository, rest) {
return (
GITHUB_HTTP_BASE +
"/repos/" +
organization +
"/" +
repository +
(rest ? "/" + rest : "")
);
}
function getDocLink(organization, repository, version, fileName) {
return (
CONTENT_PREFIX +
"/" +
organization +
"/" +
repository +
"/" +
version +
"/" +
fileName
);
}
async function getTagsToSync(organization, repository, maxVersions) {
const tagsLink = getLink(organization, repository, "git/refs/tags");
try {
const { data } = await axios.get(tagsLink, {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
});
const tags = data.map((tag) => {
const name = tag.ref.split("/")[2];
return {
name,
tarball_url: tag.url.replace("/git/", "/tarball/"),
};
});
// 1. we need to create an object to store the maximum version for each group
let maxTagInGroup = {};
tags.forEach(tag => {
// Check if the version format is valid
const isValidFormat = reThreeNumber.test(tag.name) || reFourNumber.test(tag.name);
if (!isValidFormat) {
return;
}
// Extract the first two digits of the version number as the group name
const group = tag.name.split('.').slice(0, 2).join('.');
// If this group in maxTagInGroup does not have a version yet, or if this version is greater than the version in maxTagInGroup, then update maxTagInGroup
if (!maxTagInGroup[group] || compareVersions(tag.name, maxTagInGroup[group].name) > 0) {
maxTagInGroup[group] = tag;
}
});
// 2. we convert maxTagInGroup to an array and filter out the versions that need to be synchronized
return Object.values(maxTagInGroup).filter(tag => {
// Extract the first two digits of the version number as the group name
const group = tag.name.split('.').slice(0, 2).join('.');
// If there is no local version for this group, or if this version is greater than the maximum local version, then synchronize this version
return !maxVersions[group] || compareVersions(tag.name, maxVersions[group]) > 0;
});
} catch(error) {
console.log(
"no tag list for repo",
repository,
`maybe it's archived, so skip this repo`,
'Error:', error
);
return [];
}
}
async function getDoc(organization, repository, version, name) {
try {
const docLink = getDocLink(
organization,
repository,
version,
"/docs/" + name
);
let res = await axios.get(docLink, {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
});
if (!res || !res.data) {
const readmeLink = getDocLink(
organization,
repository,
version,
"README.md"
);
res = await axios.get(readmeLink, {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
});
}
return res.data;
} catch (error) {
return null;
}
}
async function getRepository(organization, repository) {
const { data } = await axios.get(
getLink(organization, repository), {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
}
);
return data;
}
async function getContributors(organization, repository) {
const { data } = await axios.get(
getLink(organization, repository, "contributors"), {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
}
);
return data;
}
async function getLicenses(organization, repository) {
try {
const { data } = await axios.get(
getLink(organization, repository, "license"), {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
}
);
return data;
} catch (error) {
console.error(`Not Found License ${organization}:${repository}`);
return {
license: {
name: "Not Found License",
},
html_url: "",
};
}
}
async function getLanguages(organization, repository) {
const { data } = await axios.get(
getLink(organization, repository, "languages"), {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
}
);
return data;
}
async function getTopics(organization, repository) {
const { data } = await axios.get(
getLink(organization, repository, "topics"), {
headers: {
Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
},
}
);
return data;
}
function compareVersions(v1, v2) {
const parts1 = v1.slice(1).split('.').map(Number);
const parts2 = v2.slice(1).split('.').map(Number);
for (let i = 0; i < parts1.length; i++) {
if (parts1[i] > parts2[i]) {
return 1;
} else if (parts1[i] < parts2[i]) {
return -1;
}
}
return 0;
}
function getLocalMaxVersion(dir) {
const versions = fs.readdirSync(dir).filter(file => file.startsWith('v'));
const maxVersions = {};
versions.forEach(version => {
const group = version.split('.').slice(0, 2).join('.');
if (!maxVersions[group] || compareVersions(version, maxVersions[group]) > 0) {
maxVersions[group] = version;
}
});
return maxVersions;
}
async function syncDoc(tag, pathPrefix, fileName, organization, repository, project) {
const version = tag.name;
const download = tag.tarball_url;
const _dir = pathPrefix + "/" + version;
const _file_path = _dir + "/" + fileName + ".md";
if (!fs.existsSync(_dir)) {
fs.mkdirSync(_dir);
}
if (!fs.existsSync(_file_path)) {
const repo = await getRepository(organization, repository);
const description = repo["description"];
const ownerName = repo["owner"]["login"];
const support = repo["owner"]["login"];
const ownerImg = repo["owner"]["avatar_url"];
const icon = project.icon || ownerImg
const name = repo["name"];
const source = repo["html_url"];
let license;
let licenseLink;
if (!project.private_source) {
const licenses = await getLicenses(organization, repository);
license = licenses["license"]["name"];
licenseLink = licenses["html_url"];
}
const languages = await getLanguages(organization, repository);
const languageKeys = Object.keys(languages);
const language = languageKeys.slice(0, 4);
const topics = await getTopics(organization, repository);
const contributors = await getContributors(organization, repository);
const contributorList = [];
for (let m = 0; m < contributors.length; m++) {
contributorList.push(contributors[m]["login"]);
}
const doc = await getDoc(
organization,
repository,
version,
fileName + ".md"
);
if (!doc) {
console.log(`not found doc ${fileName} version: ${version}`);
return;
}
const md = matter(doc);
const dockerfile = md.data.dockerfile;
const alias = md.data.alias || name;
let content = "";
md.content.split("\n").forEach(function (line) {
if (line.indexOf("![](/docs") >= 0) {
line = line.replace(
"/docs",
"https://raw.githubusercontent.com/" +
organization +
"/" +
name +
"/" +
tag.name +
"/docs"
);
}
if (line.indexOf("![](docs") >= 0) {
line = line.replace(
"docs",
"https://raw.githubusercontent.com/" +
organization +
"/" +
name +
"/" +
tag.name +
"/docs"
);
}
content += line + "\n";
});
const result = {
description: project.description || description,
authors: project.authors || contributorList.slice(0, 4),
contributors: project.contributors || contributorList.slice(0, 4),
languages: project.language || language,
document: "",
source: project.private_source ? "Private source" : (project.source || source),
license: project.private_source ? "StreamNative, Inc.. All Rights Reserved" : (project.license || license),
licenseLink: project.private_source ? "" : (project.license_link || licenseLink),
tags: project.tags || topics["names"],
alias: project.alias || alias,
features: project.description || description,
icon: project.icon || icon,
download: project.private_source ? "" : (project.download || download),
support: project.private_source ? "streamnative" : (project.support || support),
supportLink: project.private_source ? "https://streamnative.io" : (project.support_link || source),
supportImg: project.support_img || ownerImg,
ownerName: project.owner_name || ownerName,
ownerImg: project.owner_img || ownerImg,
dockerfile: project.private_source ? "" : (project.dockerfile || dockerfile),
snAvailable: project.sn_available || md.data.sn_available,
id: fileName,
content: content,
};
ejs.renderFile("hub.template", result, (err, str) => {
if (err) {
return console.error(err);
}
fs.writeFileSync(_file_path, str);
console.log("successed sync doc:", _file_path);
});
}
}
function cleanupDirectories(baseDir) {
// Get all directories within the base directory
const dirents = fs.readdirSync(baseDir, { withFileTypes: true });
const directories = dirents
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
// Group the directories based on the first two digits of the version
let groups = {};
directories.forEach(dir => {
const group = dir.split('.').slice(0, 2).join('.');
if (!groups[group]) {
groups[group] = [];
}
groups[group].push(dir);
});
// For each group, delete all directories except for the maximum version
for (let group in groups) {
let versions = groups[group];
versions.sort(compareVersions);
let maxVersion = versions.pop(); // Keep the maximum version
// Delete the other versions
for (let version of versions) {
let directoryPath = path.join(baseDir, version);
fs.rmSync(directoryPath, { recursive: true, force: true });
}
}
}
async function fetchDocs() {
const yamlFiles = await globby(yamlPatterns);
for (let yamlFile of yamlFiles) {
const filePath = yamlFile.split("/");
const fileName = path.basename(yamlFile, ".yaml");
const pathPrefix = filePath.slice(0, 2).join("/");
const project = yaml.load(fs.readFileSync(yamlFile, "utf8"));
if (!project.repository) {
continue;
}
const host = project.repository.split("://")[1];
const orgRepository = host.split("/");
const organization = orgRepository[1];
const repository = orgRepository[2];
console.log(`Initiating synchronization for ${repository} documents...`);
// 1. Get the maximum versions locally.
const maxVersions = getLocalMaxVersion(path.dirname(yamlFile));
// 2. Get the tags (versions) that need to be synchronized.
const tags = await getTagsToSync(organization, repository, maxVersions);
// 3. Synchronize the documentation.
for (let tag of tags) {
await syncDoc(tag, pathPrefix, fileName, organization, repository, project);
}
// 4. Clean up the directories right after the synchronization.
cleanupDirectories(path.dirname(yamlFile));
console.log(`Synchronization completed for ${repository} documents.`);
}
}
await fetchDocs();