-
Notifications
You must be signed in to change notification settings - Fork 2
/
replace.js
executable file
·218 lines (203 loc) · 5.67 KB
/
replace.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
#!/usr/bin/env node
import fetch from "node-fetch";
import dotenv from "dotenv";
import { Buffer } from "node:buffer";
import { Command, Option } from "commander";
import log4js from "log4js";
import { diffWordsWithSpace } from "diff";
import colors from "colors";
const logger = log4js.getLogger();
dotenv.config();
const options = new Command()
.name("replace.js")
.description("CLI to replace strings in Confluence Pages")
.version("0.0.1")
.requiredOption(
"-q, --query <query>",
"CQL query used to search pages, eg: text~gitlab"
)
.requiredOption("-s, --search <string>", "string to replace eg: gitlab")
.requiredOption(
"-r, --replace <string>",
"replacement string eg: gitlab -> github"
)
.addOption(
new Option("-u, --user <user>", "user eg: your_email@domain.com").env(
"CONFLUENCE_USER"
)
)
.addOption(
new Option(
"-t, --token <token>",
"your_user_api_token with scope read:content-details:confluence,write:content:confluence"
).env("CONFLUENCE_TOKEN")
)
.addOption(
new Option(
"-d, --domain <domainurl>",
"eg: https://<domain_name>.atlassian.net"
).env("CONFLUENCE_DOMAIN")
)
.addOption(
new Option(
"-l, --loglevel <loglevel>",
"loglevel, eg: debug, info, warn, error, fatal"
).env("LOGLEVEL")
)
.option(
"-c, --convertbburl",
"convert bitbucket url format to github url format"
)
.option("--dryrun", "dry run only")
.parse()
.opts();
let user;
let token;
let query;
let domain;
let search;
let replacestr = "";
replacestr = options.replace;
query = options.query;
search = options.search;
user = options.user;
token = options.token;
domain = options.domain;
logger.level = options.loglevel ?? process.env.LOGLEVEL ?? "info";
logger.debug(options);
const searchQuery = domain + "/wiki/rest/api/content/search?cql=" + query;
const header = {
"Content-Type": "application/json",
Authorization: "Basic " + Buffer.from(user + ":" + token).toString("base64"),
};
logger.debug({ "searchQuery: ": searchQuery });
logger.debug(header);
fetch(searchQuery, {
method: "GET",
headers: header,
})
.then((res) => res.json())
.then((json) => {
logger.debug({ "Content IDs: ": json.results.map((result) => result.id) });
json.size
? console.table({ "Total Pages: ": json.size })
: console.table({ "No results matching query": query });
json.results.forEach((result) => {
getContent(result.id);
});
})
.catch((err) => {
console.error(err);
});
function getPageQuery(pageId) {
return (
domain + "/wiki/rest/api/content/" + pageId + "?expand=body.storage,version"
);
}
function getPageUpdateQuery(pageId) {
return domain + "/wiki/rest/api/content/" + pageId;
}
function convertBBurl2GH(content) {
const re = /projects\/([^\/]*)\/repos\/([^\/]*)\/browse/gim;
const subst = "$2";
return content.replace(re, subst);
}
function replaceStr(content) {
const replacedContent = content.replace(new RegExp(search, "ig"), replacestr);
const replacedContent2 = options.convertbburl
? convertBBurl2GH(replacedContent)
: replacedContent;
return replacedContent2;
}
function showdiff(content, replacedContent) {
if (content != replacedContent) {
const dff = diffWordsWithSpace(content, replacedContent, {
ignoreCase: true,
ignoreWhitespace: true,
});
let diffstr = "";
dff.forEach((part) => {
const color = part.added ? "green" : part.removed ? "red" : "grey";
// console.log(colors[color](part?.value));
diffstr += colors[color](part?.value);
// process.stdout.write(colors[color](part?.value ?? ""));
});
console.log("");
return diffstr;
} else {
return "no changes";
}
}
function getContent(id) {
fetch(getPageQuery(id), {
method: "GET",
headers: header,
})
.then((res) => res.json())
.then((json) => {
const content = json.body.storage.value;
const title = json.title;
const type = json.type;
const replacedContent = replaceStr(content);
const titleReplaced = replaceStr(title);
logger.info({ "Page ID: ": id, "Title: ": title, "Type: ": type });
const difftitle = showdiff(title, titleReplaced);
const diffstr = showdiff(content, replacedContent);
process.stdout.write(diffstr) && console.log("");
options.dryrun
? logger.debug({
title,
...(title == titleReplaced && { "No changes to title": "" }),
...(content != replacedContent && {
content,
replacedContent,
}),
...(content == replacedContent && { "No changes to content": "" }),
})
: updateContent(
id,
json.version.number + 1,
type,
titleReplaced,
JSON.stringify(replacedContent)
);
})
.catch((err) => {
console.error(err);
});
}
function updateContent(id, version, type, title, content) {
const bodyData = `{
"version": {
"number": ${version}
},
"type": "${type}",
"title": "${title}",
"body": {
"storage": {
"value": ${content},
"representation": "storage"
}
}
}`;
logger.debug(bodyData.toString());
fetch(getPageUpdateQuery(id), {
method: "PUT",
headers: header,
body: bodyData,
})
.then((res) => res.json())
.then((json) => {
json.data
? console.log(json.data.errors)
: console.table({
id: json.id,
type: json.type,
version: json.version.number,
title: json.title,
});
})
.catch((err) => {
console.error(err);
});
}