Skip to content

Commit 030c208

Browse files
committed
Add support for updating content in text files
Relates to #7
1 parent bc9c44d commit 030c208

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

bin/github-default-branch

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
const getBranchSha = require("../src/get-branch-sha");
3838
const createBranch = require("../src/create-branch");
3939
const removeBranch = require("../src/remove-branch");
40+
const updateContent = require("../src/update-content");
4041

4142
const octokit = new Octokit({
4243
auth: argv.pat || process.env.GITHUB_TOKEN,
@@ -149,6 +150,17 @@
149150
}
150151
}
151152

153+
// Update all content on the branch
154+
await updateContent(
155+
owner,
156+
repo,
157+
old,
158+
target,
159+
octokit,
160+
argv.verbose,
161+
isDryRun
162+
);
163+
152164
// Add an empty new line to break up the output for each repo
153165
if (argv.verbose) {
154166
console.log("");

src/update-content.js

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
module.exports = async function (
2+
owner,
3+
repo,
4+
old,
5+
target,
6+
octokit,
7+
isVerbose,
8+
isDryRun
9+
) {
10+
const replacements = {
11+
"README.md": [
12+
{
13+
from: `@${old}`,
14+
to: `@${target}`,
15+
},
16+
{
17+
from: `${owner}/${repo}.svg?branch=${old}`,
18+
to: `${owner}/${repo}.svg?branch=${target}`,
19+
},
20+
],
21+
};
22+
23+
for (let path in replacements) {
24+
try {
25+
let file = await loadFile(owner, repo, path, octokit);
26+
27+
let content = file.content;
28+
for (let r of replacements[path]) {
29+
var re = new RegExp(r.from, "g");
30+
content = content.replace(re, r.to);
31+
}
32+
33+
if (content !== file.content) {
34+
if (isVerbose) {
35+
console.log(`✏️ Updating [${path}]`);
36+
}
37+
if (!isDryRun) {
38+
const r = await writeFile(
39+
owner,
40+
repo,
41+
path,
42+
content,
43+
file.sha,
44+
octokit
45+
);
46+
}
47+
} else {
48+
if (isVerbose) {
49+
console.log(`✏️ No changes detected in [${path}]`);
50+
}
51+
}
52+
} catch (e) {
53+
console.log(e);
54+
}
55+
}
56+
};
57+
58+
async function loadFile(owner, repo, path, octokit) {
59+
const {
60+
data: { sha, content },
61+
} = await octokit.repos.getContent({
62+
owner,
63+
repo,
64+
path,
65+
});
66+
67+
return {
68+
sha,
69+
content: Buffer.from(content, "base64").toString(),
70+
};
71+
}
72+
73+
async function writeFile(owner, repo, path, content, sha, octokit) {
74+
const { data: file } = await octokit.repos.createOrUpdateFileContents({
75+
owner,
76+
repo,
77+
path,
78+
message: `github-default-branch: Update ${path}`,
79+
content: Buffer.from(content).toString("base64"),
80+
sha,
81+
});
82+
83+
return file;
84+
}

0 commit comments

Comments
 (0)