-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.js
94 lines (83 loc) · 1.99 KB
/
github.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
const {octo} = require('./config');
const owner = process.env['GITHUB_USER_NAME'];
const repo = process.env['GITHUB_REPO_NAME'];
const branch = process.env['GITHUB_BRANCH_NAME']
async function uploadToRepo(files, filePaths) {
const currentCommit = await getCurrentCommit();
const filesBlobs = await Promise.all(files.map(createBlobForFile));
const newTree = await createNewTree(
filesBlobs,
filePaths,
currentCommit.treeSha,
);
const commitMessage = `added posts`
const newCommit = await createNewCommit(
commitMessage, newTree.sha, currentCommit.commitSha
)
if(newCommit.tree.sha === currentCommit.treeSha)
throw new Error('No changes made');
await setBranchToCommit(newCommit.sha)
}
async function getCurrentCommit() {
const { data: refData } = await octo.git.getRef({
owner,
repo,
ref: `heads/${branch}`,
});
const commitSha = refData.object.sha
const {data: commitData} = await octo.git.getCommit({
owner,
repo,
commit_sha: commitSha
});
return {
commitSha,
treeSha: commitData.tree.sha
}
}
async function createBlobForFile(content) {
const blobData = await octo.git.createBlob({
owner,
repo,
content,
encoding: 'utf-8'
});
return blobData.data;
}
async function createNewTree(blobs, paths, parentTreeSha) {
const tree = blobs.map(({ sha }, index) => ({
path: paths[index],
mode: `100644`,
type: `blob`,
sha,
}));
const { data } = await octo.git.createTree({
owner,
repo,
tree,
base_tree: parentTreeSha
});
console.log("tree data",data);
return data;
}
async function createNewCommit(message, currentTreeSha, currentCommitSha) {
const result = await octo.git.createCommit({
owner,
repo,
message,
tree: currentTreeSha,
parents: [currentCommitSha],
});
return result.data;
}
function setBranchToCommit(commitSha) {
return octo.git.updateRef({
owner,
repo,
ref: `heads/${branch}`,
sha: commitSha
});
}
module.exports= {
uploadToRepo
}