-
Notifications
You must be signed in to change notification settings - Fork 0
/
createBranches.js
99 lines (89 loc) · 2.65 KB
/
createBranches.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
/* Importing the required modules. */
const request = require('request-promise')
const fs = require('fs-extra')
const glob = require('glob')
/* Importing the sleep function from the utils file and the config file. */
const { sleep } = require('./utils')
const config = require('./config')
const api = `${config.target.baseUrl}/${config.target.org}/${config.target.repo}`
/* Creating a header object that will be used in the request. */
const headers = {
'Accept': 'application/vnd.github+json',
'User-Agent': 'node.js'
}
if (config.target.token) {
headers['Authorization'] = `token ${config.target.token}`
}
/**
* It creates a branch on the repository
* @param issue - the issue object
* @param which - This is the branch name.
*/
const createBranch = async (issue, which, which_str) => {
const ref = `refs/heads/pr${issue.number}${which_str}`
console.log(which.sha);
await request({
method: 'POST',
headers,
url: `${api}/git/refs`,
body: {
ref,
sha: which.sha,
},
json: true,
}).catch(err => {
console.log(`Unable to create ref: ${ref}`)
console.log(err.message)
})
}
/**
* It checks if a branch exists for a given issue
* @param issue - the issue object from the GitHub API
* @returns A boolean value
*/
const isBranchMade = async (issue, which_str) => {
const url = `${api}/branches/pr${issue.number}${which_str}`
let exists = true
try {
await request({
method: 'GET',
headers,
url,
json: true,
})
} catch (error) {
exists = false
}
return exists
}
/**
* It takes all the issues in the `issues` folder, sorts them by number, and then creates a branch for
* each issue
*/
const main = async () => {
const issues = glob.sync(`${config.source.repo}/issues/issue-+([0-9]).json`)
.map(file => JSON.parse(fs.readFileSync(file)))
.sort((a, b) => a.number - b.number)
for (let issue of issues) {
/* Checking if the issue has a base. If it does, it will create a branch for the issue. */
if (issue.base) {
console.log(`Creating branch for PR-${issue.number}`)
await createBranch(issue, issue.base, 'base')
while (!(isBranchMade(issue, 'base'))) {
console.log(`Waiting for branch pr${issue.number}base to exist`)
await sleep(1000)
}
await sleep(1000)
}
/* Creating a branch for the head of the issue. */
else if (issue.head) {
console.log(`Creating branch for PR-${issue.number}`)
await createBranch(issue,issue.head, 'head')
while (!(await isBranchMade(issue, 'head'))) {
console.log(`Waiting for branch pr${issue.number}head to exist`)
await sleep(1000)
}
}
}
}
main()