This repository was archived by the owner on Mar 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit.js
More file actions
105 lines (91 loc) · 2.27 KB
/
commit.js
File metadata and controls
105 lines (91 loc) · 2.27 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
const gh = require('gh-got')
const Mutex = require('await-lock')
const ghToken = process.env.GITHUB_TOKEN
const ghRepo = 'extplug/faerss'
function createBlob (path, content) {
return gh(`repos/${ghRepo}/git/blobs`, {
token: ghToken,
method: 'post',
body: { path, content, encoding: 'utf-8' }
}).then((res) => ({
path,
mode: '100644',
type: 'blob',
sha: res.body.sha
}))
}
function getLatestCommit () {
return gh(`repos/${ghRepo}/git/refs/heads/master`, { token: ghToken })
.then((res) => res.body.object)
}
function getTree (commit) {
return gh(`repos/${ghRepo}/git/commits/${commit.sha}`, { token: ghToken })
.then((res) => res.body.tree)
}
async function getBaseTree () {
const commit = await getLatestCommit()
return {
commit,
tree: await getTree(commit)
}
}
function createTree (baseTree, updates) {
return gh(`repos/${ghRepo}/git/trees`, {
token: ghToken,
method: 'post',
body: {
base_tree: baseTree.sha,
tree: updates
}
}).then((res) => res.body)
}
function createCommit (parent, newTree, message, author) {
return gh(`repos/${ghRepo}/git/commits`, {
token: ghToken,
method: 'post',
body: {
message,
tree: newTree.sha,
parents: [
parent.sha
],
committer: {
name: 'ExtPlug Bot',
email: 'd@extplug.com'
},
author
}
}).then((res) => res.body)
}
function updateRef (ref, commit) {
return gh(`repos/${ghRepo}/git/refs/${ref}`, {
token: ghToken,
method: 'patch',
body: {
sha: commit.sha
}
}).then((res) => res.body)
}
const lock = new Mutex()
module.exports = async function commit (user, message, files) {
await lock.acquireAsync()
try {
const [ updates, base ] = await Promise.all([
Promise.all(
files.map((file) => createBlob(file.path, file.content))),
getBaseTree()
])
const newTree = await createTree(base.tree, updates)
const newCommit = await createCommit(base.commit, newTree, message, {
name: user.username,
email: `user.${user.id}@extplug.com`
})
await updateRef('heads/master', newCommit)
return newCommit
} catch (err) {
if (err.response) console.error(err.response.body)
throw err
} finally {
lock.release()
}
}