-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwiki-as-git.ts
More file actions
executable file
·189 lines (165 loc) · 5.04 KB
/
wiki-as-git.ts
File metadata and controls
executable file
·189 lines (165 loc) · 5.04 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
import { Mwn, ApiRevision } from "mwn";
import { join, resolve } from "path";
import * as fs from "fs";
import git from "isomorphic-git";
import { ArgumentParser } from "argparse";
import dayjs from "dayjs";
import { fetchFromApi } from "./api-fetch";
import { processXmlDump } from "./xml-dump";
const { name } = JSON.parse(fs.readFileSync("./package.json").toString());
export const defaults = {
commitMessageLength: 100,
};
export const sanitizeArticleName = (articleName: string) =>
articleName.replace(/[<>:"/\\|?*]/g, "_");
export interface XmlRevision {
id: string;
parentid?: string;
timestamp: string;
contributor?: {
username?: string;
id?: string;
};
comment?: string;
text?: { "#text"?: string };
sha1?: string;
}
export const isXmlRevision = (
revision: ApiRevision | XmlRevision,
): revision is XmlRevision => "text" in revision;
export interface RevisionWithArticle {
revision: ApiRevision | XmlRevision;
articleName: string;
isXml: boolean;
}
export const createCommitForRevision = async (
revisionData: RevisionWithArticle,
dir: string,
language: string,
vvv?: boolean,
) => {
const { revision, articleName } = revisionData;
const sanitizedName = sanitizeArticleName(articleName);
const fileName = `${sanitizedName}.wiki`;
let fileContent: string | undefined;
let username: string;
const timestamp = revision.timestamp;
const rawMessage = revision.comment || "";
if (isXmlRevision(revision)) {
fileContent = revision.text?.["#text"] || "";
username = revision.contributor?.username || "[Deleted user]";
} else {
fileContent = revision.slots!.main.content || "";
username = revision.user || "[Deleted user]";
}
if (!timestamp) {
if (vvv) {
console.debug("No date for this revision, skipping");
}
return;
}
if (!fileContent || typeof fileContent !== "string") {
if (vvv) {
console.debug("No valid content for this revision, skipping");
}
return;
}
const message = rawMessage.substring(0, defaults.commitMessageLength) || "\n";
if (vvv) {
console.debug(`Creating commit for ${articleName} from ${timestamp}`);
}
fs.writeFileSync(join(dir, fileName), fileContent);
await git.add({ fs, dir, filepath: fileName });
const committer = {
name: username,
email: `${username}@${language}.wikipedia.org`,
timestamp: dayjs(timestamp).unix(),
};
const author = committer;
await git.commit({ fs, dir, message, committer, author });
};
export const getRepoDir = (language: string) =>
resolve(__dirname, "articles", `${language}.wikipedia.org`);
export const ensureRepoInitialized = async (dir: string) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
await git.init({ fs, dir });
console.debug(`Initialized repository at ${dir}`);
} else if (!fs.existsSync(join(dir, ".git"))) {
await git.init({ fs, dir });
console.debug(`Initialized repository at ${dir}`);
}
};
let settings: Record<string, string>;
try {
settings = JSON.parse(fs.readFileSync("./settings.json").toString());
} catch (error) {
settings = {};
}
const argparser = new ArgumentParser({
description: name,
});
argparser.add_argument("--language", {
nargs: 1,
default: "en",
help: "The Wikipedia language version to use (ex: en, fr, etc.)",
});
argparser.add_argument("--xml-dump", {
nargs: 1,
help: "Path to XML dump file to process",
});
argparser.add_argument("-vvv", { help: "Verbose log", action: "store_true" });
argparser.add_argument("articleName", {
type: "str",
nargs: "?",
help: "The name of the article to retrieve (required when not using --xml-dump)",
});
const args = argparser.parse_args() as {
language: string;
xml_dump: string;
articleName: string;
vvv: boolean;
};
if (args.xml_dump) {
const xmlPath = Array.isArray(args.xml_dump)
? args.xml_dump[0]
: args.xml_dump;
await processXmlDump(xmlPath);
} else {
if (!args.articleName) {
console.error("Error: articleName is required when not using --xml-dump");
process.exit(1);
}
const articleName = Array.isArray(args.articleName)
? args.articleName[0]
: args.articleName;
const language = Array.isArray(args.language)
? args.language[0]
: args.language || "en";
const mwn = new Mwn({
apiUrl: `https://${language}.wikipedia.org/w/api.php`,
});
await mwn.getSiteInfo();
if (!(settings.username && settings.password)) {
console.info(
`If you have a bot account on ${mwn.options.apiUrl}, specify its credentials in settings.json to wiki-as-git faster!`,
);
await fetchFromApi(articleName, language);
} else {
try {
await mwn.login({
username: settings.username,
password: settings.password,
});
console.info(
"Login successful. Note that logging in only allows to make wiki-as-git faster if bot credentials are used",
);
} catch (e) {
console.error(
"Login failed. Log in with a bot account to make wiki-as-git faster!",
);
} finally {
await fetchFromApi(articleName, language, undefined, args.vvv);
}
}
}