-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
110 lines (97 loc) · 2.84 KB
/
script.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
import { protectionResponseDataToUpdateParameters } from "./utils.js";
let templateBranchProtectionSettings;
/**
* Updates branch protection based on a settings from a template repository
*
* @param {import('@octoherd/cli').Octokit} octokit
* @param {import('@octoherd/cli').Repository} repository
* @param { {template: string} } options Custom user options passed to the CLI
*/
export async function script(octokit, repository, options) {
if (!options.template) {
throw new Error(`--template is required`);
}
try {
if (!templateBranchProtectionSettings) {
octokit.log.debug(
"Load branch protection settings from template repository %s",
options.template
);
const [templateOwner, templateRepo] = options.template.split("/");
try {
const {
data: { default_branch },
} = await octokit.request("GET /repos/{owner}/{repo}", {
owner: templateOwner,
repo: templateRepo,
});
const { data } = await octokit.request(
"GET /repos/{owner}/{repo}/branches/{branch}/protection",
{
owner: templateOwner,
repo: templateRepo,
branch: default_branch,
}
);
templateBranchProtectionSettings = protectionResponseDataToUpdateParameters(
data
);
} catch (error) {
if (error.status === 404) {
throw new Error(`No branch protection in template repository: %s`);
}
throw error;
}
octokit.log.info(
templateBranchProtectionSettings,
"branch protection settings loaded from %s",
options.template
);
}
const urlParameters = {
owner: repository.owner.login,
repo: repository.name,
branch: repository.default_branch,
};
try {
const { data } = await octokit.request(
"GET /repos/{owner}/{repo}/branches/{branch}/protection",
urlParameters
);
const branchProtectionParameters = protectionResponseDataToUpdateParameters(
data
);
octokit.log.debug(
branchProtectionParameters,
"Current branch protection settings for %s",
repository.full_name
);
} catch (error) {
if (error.status === 404) {
octokit.log.debug(
"No branch protection settings on %s",
repository.full_name
);
} else {
throw error;
}
}
await octokit.request(
"PUT /repos/{owner}/{repo}/branches/{branch}/protection",
{
...urlParameters,
...templateBranchProtectionSettings,
}
);
} catch (error) {
if (error.status === 404) {
octokit.log.info(
"No branch protection on %s's default branch (%s)",
repository.full_name,
repository.default_branch
);
return;
}
throw error;
}
}