github-settings-as-code 3.0.2 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +54 -34
  2. package/dist/cmd/repo-settings.mjs +13 -0
  3. package/dist/cmd/repo-settings.mjs.map +1 -1
  4. package/dist/github/actions-settings/api/get-actions-settings.d.mts +1 -1
  5. package/dist/github/actions-settings/api/get-actions-settings.d.mts.map +1 -1
  6. package/dist/github/actions-settings/api/get-actions-settings.mjs +4 -0
  7. package/dist/github/actions-settings/api/get-actions-settings.mjs.map +1 -1
  8. package/dist/github/actions-settings/api/set-actions-settings.d.mts.map +1 -1
  9. package/dist/github/actions-settings/api/set-actions-settings.mjs +8 -0
  10. package/dist/github/actions-settings/api/set-actions-settings.mjs.map +1 -1
  11. package/dist/github/actions-settings/constants.d.mts +67 -0
  12. package/dist/github/actions-settings/constants.d.mts.map +1 -1
  13. package/dist/github/actions-settings/constants.mjs +22 -0
  14. package/dist/github/actions-settings/constants.mjs.map +1 -1
  15. package/dist/github/constants.d.mts +2 -0
  16. package/dist/github/constants.d.mts.map +1 -1
  17. package/dist/github/constants.mjs +2 -0
  18. package/dist/github/constants.mjs.map +1 -1
  19. package/dist/github/environments/api/get-environments.d.mts +16 -0
  20. package/dist/github/environments/api/get-environments.d.mts.map +1 -0
  21. package/dist/github/environments/api/get-environments.mjs +98 -0
  22. package/dist/github/environments/api/get-environments.mjs.map +1 -0
  23. package/dist/github/environments/api/index.d.mts +3 -0
  24. package/dist/github/environments/api/index.d.mts.map +1 -0
  25. package/dist/github/environments/api/index.mjs +3 -0
  26. package/dist/github/environments/api/index.mjs.map +1 -0
  27. package/dist/github/environments/api/set-environment.d.mts +10 -0
  28. package/dist/github/environments/api/set-environment.d.mts.map +1 -0
  29. package/dist/github/environments/api/set-environment.mjs +73 -0
  30. package/dist/github/environments/api/set-environment.mjs.map +1 -0
  31. package/dist/github/environments/apply.d.mts +11 -0
  32. package/dist/github/environments/apply.d.mts.map +1 -0
  33. package/dist/github/environments/apply.mjs +67 -0
  34. package/dist/github/environments/apply.mjs.map +1 -0
  35. package/dist/github/environments/backup.d.mts +5 -0
  36. package/dist/github/environments/backup.d.mts.map +1 -0
  37. package/dist/github/environments/backup.mjs +24 -0
  38. package/dist/github/environments/backup.mjs.map +1 -0
  39. package/dist/github/environments/constants.d.mts +354 -0
  40. package/dist/github/environments/constants.d.mts.map +1 -0
  41. package/dist/github/environments/constants.mjs +62 -0
  42. package/dist/github/environments/constants.mjs.map +1 -0
  43. package/dist/github/environments/index.d.mts +6 -0
  44. package/dist/github/environments/index.d.mts.map +1 -0
  45. package/dist/github/environments/index.mjs +6 -0
  46. package/dist/github/environments/index.mjs.map +1 -0
  47. package/dist/github/environments/read-environment-contents.d.mts +4 -0
  48. package/dist/github/environments/read-environment-contents.d.mts.map +1 -0
  49. package/dist/github/environments/read-environment-contents.mjs +32 -0
  50. package/dist/github/environments/read-environment-contents.mjs.map +1 -0
  51. package/dist/github/index.d.mts +2 -0
  52. package/dist/github/index.d.mts.map +1 -1
  53. package/dist/github/index.mjs +2 -0
  54. package/dist/github/index.mjs.map +1 -1
  55. package/dist/github/vulnerability-alerts/api/get-vulnerability-alerts.d.mts +10 -0
  56. package/dist/github/vulnerability-alerts/api/get-vulnerability-alerts.d.mts.map +1 -0
  57. package/dist/github/vulnerability-alerts/api/get-vulnerability-alerts.mjs +25 -0
  58. package/dist/github/vulnerability-alerts/api/get-vulnerability-alerts.mjs.map +1 -0
  59. package/dist/github/vulnerability-alerts/api/index.d.mts +3 -0
  60. package/dist/github/vulnerability-alerts/api/index.d.mts.map +1 -0
  61. package/dist/github/vulnerability-alerts/api/index.mjs +3 -0
  62. package/dist/github/vulnerability-alerts/api/index.mjs.map +1 -0
  63. package/dist/github/vulnerability-alerts/api/set-vulnerability-alerts.d.mts +10 -0
  64. package/dist/github/vulnerability-alerts/api/set-vulnerability-alerts.d.mts.map +1 -0
  65. package/dist/github/vulnerability-alerts/api/set-vulnerability-alerts.mjs +19 -0
  66. package/dist/github/vulnerability-alerts/api/set-vulnerability-alerts.mjs.map +1 -0
  67. package/dist/github/vulnerability-alerts/apply.d.mts +11 -0
  68. package/dist/github/vulnerability-alerts/apply.d.mts.map +1 -0
  69. package/dist/github/vulnerability-alerts/apply.mjs +47 -0
  70. package/dist/github/vulnerability-alerts/apply.mjs.map +1 -0
  71. package/dist/github/vulnerability-alerts/backup.d.mts +5 -0
  72. package/dist/github/vulnerability-alerts/backup.d.mts.map +1 -0
  73. package/dist/github/vulnerability-alerts/backup.mjs +22 -0
  74. package/dist/github/vulnerability-alerts/backup.mjs.map +1 -0
  75. package/dist/github/vulnerability-alerts/constants.d.mts +72 -0
  76. package/dist/github/vulnerability-alerts/constants.d.mts.map +1 -0
  77. package/dist/github/vulnerability-alerts/constants.mjs +21 -0
  78. package/dist/github/vulnerability-alerts/constants.mjs.map +1 -0
  79. package/dist/github/vulnerability-alerts/index.d.mts +5 -0
  80. package/dist/github/vulnerability-alerts/index.d.mts.map +1 -0
  81. package/dist/github/vulnerability-alerts/index.mjs +5 -0
  82. package/dist/github/vulnerability-alerts/index.mjs.map +1 -0
  83. package/package.json +15 -15
  84. package/src/cmd/repo-settings.mts +17 -0
  85. package/src/github/actions-settings/api/get-actions-settings.mts +11 -1
  86. package/src/github/actions-settings/api/set-actions-settings.mts +13 -0
  87. package/src/github/actions-settings/constants.mts +24 -0
  88. package/src/github/constants.mts +7 -0
  89. package/src/github/environments/api/get-environments.mts +155 -0
  90. package/src/github/environments/api/index.mts +2 -0
  91. package/src/github/environments/api/set-environment.mts +106 -0
  92. package/src/github/environments/apply.mts +87 -0
  93. package/src/github/environments/backup.mts +38 -0
  94. package/src/github/environments/constants.mts +78 -0
  95. package/src/github/environments/index.mts +5 -0
  96. package/src/github/environments/read-environment-contents.mts +53 -0
  97. package/src/github/index.mts +2 -0
  98. package/src/github/vulnerability-alerts/api/get-vulnerability-alerts.mts +31 -0
  99. package/src/github/vulnerability-alerts/api/index.mts +2 -0
  100. package/src/github/vulnerability-alerts/api/set-vulnerability-alerts.mts +31 -0
  101. package/src/github/vulnerability-alerts/apply.mts +77 -0
  102. package/src/github/vulnerability-alerts/backup.mts +36 -0
  103. package/src/github/vulnerability-alerts/constants.mts +25 -0
  104. package/src/github/vulnerability-alerts/index.mts +4 -0
@@ -25,6 +25,13 @@ export const actionsSettingsDir = path.resolve(
25
25
 
26
26
  export const pagesSettingsDir = path.resolve(settingsDir, './pages');
27
27
 
28
+ export const environmentsDir = path.resolve(settingsDir, './environments');
29
+
30
+ export const vulnerabilityAlertsDir = path.resolve(
31
+ settingsDir,
32
+ './vulnerability-alerts',
33
+ );
34
+
28
35
  export const rulesetsDir = path.resolve(settingsDir, './rulesets');
29
36
 
30
37
  export const octokitHeaders = {
@@ -0,0 +1,155 @@
1
+ import { type EndpointKeys } from 'octokit-safe-types';
2
+ import { Arr } from 'ts-data-forge';
3
+ import * as t from 'ts-fortress';
4
+ import { Result } from 'ts-repo-utils';
5
+ import { octokitHeaders, OWNER, REPO } from '../../constants.mjs';
6
+ import { octokit } from '../../octokit.mjs';
7
+ import { EnvironmentSettings } from '../constants.mjs';
8
+
9
+ /**
10
+ * Settings > Environments の現在値を、宣言ファイルと同じ形にして返す。
11
+ *
12
+ * 名前順に整える。 GitHub が返す順は作成順で、環境を 1 つ足しただけで
13
+ * `bk/` の中身が並び替わると差分が読めなくなるため。
14
+ */
15
+ export const getAllEnvironments = async (): Promise<
16
+ readonly EnvironmentSettings[]
17
+ > => {
18
+ // https://docs.github.com/rest/deployments/environments#list-environments
19
+ //
20
+ // per_page の上限。環境は数個しか無く、 2 ページ目が要る状況は
21
+ // 「 GUI で何かが大量に作られた」ときだけなので、ページングは張らない。
22
+ const response = await octokit.request(
23
+ 'GET /repos/{owner}/{repo}/environments' satisfies EndpointKeys,
24
+ { owner: OWNER, repo: REPO, headers: octokitHeaders, per_page: 100 },
25
+ );
26
+
27
+ const environments = response.data.environments ?? [];
28
+
29
+ const settings = await Promise.all(
30
+ environments.map(async (environment) => {
31
+ const policy = environment.deployment_branch_policy ?? undefined;
32
+
33
+ return EnvironmentSettings.fill({
34
+ name: environment.name,
35
+ ...parseProtectionRules(environment.protection_rules),
36
+ deployment_branch_policy:
37
+ policy === undefined
38
+ ? null
39
+ : {
40
+ protected_branches: policy.protected_branches,
41
+ custom_branch_policies: policy.custom_branch_policies,
42
+ },
43
+ deployment_branch_policies:
44
+ policy?.custom_branch_policies === true
45
+ ? await getDeploymentBranchPolicyNames(environment.name)
46
+ : [],
47
+ });
48
+ }),
49
+ );
50
+
51
+ return settings.toSorted((a, b) => a.name.localeCompare(b.name));
52
+ };
53
+
54
+ /** 宣言ファイルに載る形。 `id` は GitHub 側の都合なので落とす。 */
55
+ const getDeploymentBranchPolicyNames = async (
56
+ environmentName: string,
57
+ ): Promise<readonly Readonly<{ name: string; type: 'branch' | 'tag' }>[]> => {
58
+ const policies = await getDeploymentBranchPolicies(environmentName);
59
+
60
+ return policies.map(({ name, type }) => ({ name, type }));
61
+ };
62
+
63
+ /** 「 Selected branches and tags 」に登録されている pattern を列挙する。 */
64
+ export const getDeploymentBranchPolicies = async (
65
+ environmentName: string,
66
+ ): Promise<readonly DeploymentBranchPolicy[]> => {
67
+ // https://docs.github.com/rest/deployments/branch-policies#list-deployment-branch-policies
68
+ const response = await octokit.request(
69
+ 'GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies' satisfies EndpointKeys,
70
+ {
71
+ owner: OWNER,
72
+ repo: REPO,
73
+ environment_name: environmentName,
74
+ headers: octokitHeaders,
75
+ per_page: 100,
76
+ },
77
+ );
78
+
79
+ return response.data.branch_policies.map((policy) => ({
80
+ id: policy.id ?? 0,
81
+ name: policy.name ?? '',
82
+ type: policy.type === 'tag' ? 'tag' : 'branch',
83
+ }));
84
+ };
85
+
86
+ export type DeploymentBranchPolicy = Readonly<{
87
+ id: number;
88
+ name: string;
89
+ type: 'branch' | 'tag';
90
+ }>;
91
+
92
+ /**
93
+ * GET が返す `protection_rules` を PUT の body の形に戻す。
94
+ *
95
+ * GitHub は有効な保護ルールだけを配列で返し、その要素の `type` は openapi の
96
+ * 型定義では素の `string` — つまり判別可能 union になっていないので、絞り込みが
97
+ * 効かない。実データを ts-fortress で読み直すほうが、上流の型に合わせて
98
+ * キャストを書くより素直で、形が変わったときに黙って通り過ぎることもない。
99
+ */
100
+ const parseProtectionRules = (
101
+ protectionRules: unknown,
102
+ ): Readonly<{
103
+ wait_timer: number;
104
+ prevent_self_review: boolean;
105
+ reviewers: readonly Readonly<{ type: 'User' | 'Team'; id: number }>[];
106
+ }> => {
107
+ const validationResult = ProtectionRules.validate(protectionRules ?? []);
108
+
109
+ if (Result.isErr(validationResult)) {
110
+ throw new Error(
111
+ Arr.toUnshifted(
112
+ 'GitHub が返した environment の protection_rules を読めませんでした。',
113
+ )(t.validationErrorsToMessages(validationResult.value)).join('\n'),
114
+ );
115
+ }
116
+
117
+ const rules = validationResult.value;
118
+
119
+ const waitTimer = rules.find((rule) => rule.type === 'wait_timer');
120
+
121
+ const requiredReviewers = rules.find(
122
+ (rule) => rule.type === 'required_reviewers',
123
+ );
124
+
125
+ return {
126
+ wait_timer: waitTimer?.wait_timer ?? 0,
127
+ prevent_self_review: requiredReviewers?.prevent_self_review ?? false,
128
+ reviewers: (requiredReviewers?.reviewers ?? []).map((entry) => ({
129
+ type: entry.type,
130
+ id: entry.reviewer.id,
131
+ })),
132
+ };
133
+ };
134
+
135
+ const ProtectionRules = t.array(
136
+ t.record({
137
+ type: t.string(''),
138
+ wait_timer: t.optional(t.number(0)),
139
+ prevent_self_review: t.optional(t.boolean(false)),
140
+ reviewers: t.optional(
141
+ t.array(
142
+ t.record({
143
+ type: t.enumType(['User', 'Team'], {
144
+ typeName: 'EnvironmentReviewerType',
145
+ defaultValue: 'User',
146
+ }),
147
+ // `reviewer` は User / Team の完全な表現だが、書き戻しに要るのは id
148
+ // だけ。 record は既定で余剰キーを通すので、残りはそのまま無視される。
149
+ reviewer: t.record({ id: t.number(0) }),
150
+ }),
151
+ ),
152
+ ),
153
+ }),
154
+ { typeName: 'EnvironmentProtectionRules' },
155
+ );
@@ -0,0 +1,2 @@
1
+ export * from './get-environments.mjs';
2
+ export * from './set-environment.mjs';
@@ -0,0 +1,106 @@
1
+ import { type EndpointKeys } from 'octokit-safe-types';
2
+ import { octokitHeaders, OWNER, REPO } from '../../constants.mjs';
3
+ import { octokit } from '../../octokit.mjs';
4
+ import { type EnvironmentSettings } from '../constants.mjs';
5
+ import { getDeploymentBranchPolicies } from './get-environments.mjs';
6
+
7
+ /**
8
+ * 環境を JSON の内容に合わせる。無ければ作られる。
9
+ *
10
+ * `PUT` は保護ルールを丸ごと置き換えるので、省いたキーは「変更しない」ではなく
11
+ * 「無効にする」になる。宣言ファイルをそのまま渡しているのはそのため —
12
+ * 部分更新にすると、ファイルから消した設定が GitHub 側に残る。
13
+ */
14
+ export const setEnvironment = async (
15
+ settings: EnvironmentSettings,
16
+ ): Promise<void> => {
17
+ // https://docs.github.com/rest/deployments/environments#create-or-update-an-environment
18
+ await octokit.request(
19
+ 'PUT /repos/{owner}/{repo}/environments/{environment_name}' satisfies EndpointKeys,
20
+ {
21
+ owner: OWNER,
22
+ repo: REPO,
23
+ environment_name: settings.name,
24
+ headers: octokitHeaders,
25
+ wait_timer: settings.wait_timer,
26
+ prevent_self_review: settings.prevent_self_review,
27
+ reviewers: settings.reviewers.map((reviewer) => ({
28
+ type: reviewer.type,
29
+ id: reviewer.id,
30
+ })),
31
+ deployment_branch_policy:
32
+ settings.deployment_branch_policy === null
33
+ ? null
34
+ : {
35
+ protected_branches:
36
+ settings.deployment_branch_policy.protected_branches,
37
+ custom_branch_policies:
38
+ settings.deployment_branch_policy.custom_branch_policies,
39
+ },
40
+ },
41
+ );
42
+
43
+ await setDeploymentBranchPolicies(settings);
44
+ };
45
+
46
+ /**
47
+ * 「 Selected branches and tags 」の pattern を宣言に合わせる。
48
+ *
49
+ * 個別の追加・削除しか無いエンドポイントなので、現在値との差分を取って埋める。
50
+ * 名前と種別が一致するものは触らない — 消して作り直すと id が変わり、
51
+ * その間だけ deploy できない ref ができる。
52
+ */
53
+ const keyOf = (policy: Readonly<{ name: string; type: string }>): string =>
54
+ `${policy.type}:${policy.name}` as const;
55
+
56
+ const setDeploymentBranchPolicies = async (
57
+ settings: EnvironmentSettings,
58
+ ): Promise<void> => {
59
+ if (settings.deployment_branch_policy?.custom_branch_policies !== true) {
60
+ // 選択されていないなら pattern は存在し得ない。 PUT 側が既に消している。
61
+ return;
62
+ }
63
+
64
+ const current = await getDeploymentBranchPolicies(settings.name);
65
+
66
+ const desiredKeys: ReadonlySet<string> = new Set(
67
+ settings.deployment_branch_policies.map(keyOf),
68
+ );
69
+
70
+ const currentKeys: ReadonlySet<string> = new Set(current.map(keyOf));
71
+
72
+ const toDelete = current.filter((p) => !desiredKeys.has(keyOf(p)));
73
+
74
+ const toCreate = settings.deployment_branch_policies.filter(
75
+ (p) => !currentKeys.has(keyOf(p)),
76
+ );
77
+
78
+ for (const policy of toDelete) {
79
+ // https://docs.github.com/rest/deployments/branch-policies#delete-a-deployment-branch-policy
80
+ await octokit.request(
81
+ 'DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}' satisfies EndpointKeys,
82
+ {
83
+ owner: OWNER,
84
+ repo: REPO,
85
+ environment_name: settings.name,
86
+ branch_policy_id: policy.id,
87
+ headers: octokitHeaders,
88
+ },
89
+ );
90
+ }
91
+
92
+ for (const policy of toCreate) {
93
+ // https://docs.github.com/rest/deployments/branch-policies#create-a-deployment-branch-policy
94
+ await octokit.request(
95
+ 'POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies' satisfies EndpointKeys,
96
+ {
97
+ owner: OWNER,
98
+ repo: REPO,
99
+ environment_name: settings.name,
100
+ headers: octokitHeaders,
101
+ name: policy.name,
102
+ type: policy.type,
103
+ },
104
+ );
105
+ }
106
+ };
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ import 'dotenv/config';
3
+ import * as fs from 'node:fs/promises';
4
+ import * as path from 'node:path';
5
+ import { Arr } from 'ts-data-forge';
6
+ import { isDirectlyExecuted } from 'ts-repo-utils';
7
+ import { environmentsDir } from '../constants.mjs';
8
+ import { getAllEnvironments, setEnvironment } from './api/index.mjs';
9
+ import { backupEnvironments } from './backup.mjs';
10
+ import { type EnvironmentSettings } from './constants.mjs';
11
+ import { readEnvironmentFiles } from './read-environment-contents.mjs';
12
+
13
+ /**
14
+ * `repo-settings/environments/*.json` を Settings > Environments に反映する。
15
+ *
16
+ * ruleset と同じく、宣言に無い環境は消さない。 GUI で作られたものが `bk/` に
17
+ * 現れることが drift の見え方であって、 apply が黙って片付けてしまうと
18
+ * 「いつ誰が何を作ったか」を見る機会がなくなる。
19
+ */
20
+ export const applyEnvironments = async (): Promise<void> => {
21
+ await backupEnvironments(false);
22
+
23
+ const environments = await readEnvironmentFiles();
24
+
25
+ for (const environment of environments) {
26
+ assertConsistent(environment);
27
+ }
28
+
29
+ for (const environment of environments) {
30
+ await setEnvironment(environment);
31
+ }
32
+
33
+ // 反映後の実際の値でローカルのファイルを更新する
34
+ {
35
+ const applied = await getAllEnvironments();
36
+
37
+ for (const environment of applied) {
38
+ const str = JSON.stringify(environment, undefined, 2);
39
+
40
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
41
+ await fs.writeFile(
42
+ path.resolve(environmentsDir, `${environment.name}.json`),
43
+ str,
44
+ );
45
+ }
46
+
47
+ // `bk/` は backup 側が makeEmptyDir から作り直す。ここで書き足すのではなく
48
+ // 呼び直しているのは、消えた環境のファイルが残らないようにするため。
49
+ // 整形もそこでまとめて走る。
50
+ await backupEnvironments();
51
+ }
52
+ };
53
+
54
+ /**
55
+ * GitHub 側が黙って無視する組み合わせを、送る前に落とす。
56
+ *
57
+ * `custom_branch_policies` が立っていないのに pattern が書いてあるファイルは、
58
+ * 読む側には「この ref だけに制限されている」と読めて、実際には何の制限にも
59
+ * なっていない — 一番危ない種類の嘘なので、エラーにする。
60
+ */
61
+ const assertConsistent = (environment: EnvironmentSettings): void => {
62
+ const custom =
63
+ environment.deployment_branch_policy?.custom_branch_policies === true;
64
+
65
+ if (!custom && Arr.isNonEmpty(environment.deployment_branch_policies)) {
66
+ throw new Error(
67
+ [
68
+ `環境 "${environment.name}": deployment_branch_policies が書かれていますが、`,
69
+ 'deployment_branch_policy.custom_branch_policies が true ではありません。',
70
+ 'pattern は "Selected branches and tags" を選んだときにしか効きません。',
71
+ ].join('\n'),
72
+ );
73
+ }
74
+
75
+ // `custom` が立っている時点で TypeScript は `deployment_branch_policy` を
76
+ // record 側に絞り込んでいる。両方 true は JSON としては書けてしまうので、
77
+ // この組み合わせは送る前に落とす。
78
+ if (custom && environment.deployment_branch_policy.protected_branches) {
79
+ throw new Error(
80
+ `環境 "${environment.name}": protected_branches と custom_branch_policies は同時に true にできません。`,
81
+ );
82
+ }
83
+ };
84
+
85
+ if (isDirectlyExecuted(import.meta.url)) {
86
+ await applyEnvironments();
87
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import 'dotenv/config';
3
+ import * as fs from 'node:fs/promises';
4
+ import * as path from 'node:path';
5
+ import {
6
+ formatUncommittedFiles,
7
+ isDirectlyExecuted,
8
+ makeEmptyDir,
9
+ } from 'ts-repo-utils';
10
+ import { environmentsDir } from '../constants.mjs';
11
+ import { getAllEnvironments } from './api/index.mjs';
12
+
13
+ const backupDir = path.resolve(environmentsDir, './bk');
14
+
15
+ /** Settings > Environments の現在値を `bk/` に保存する。 */
16
+ export const backupEnvironments = async (
17
+ fmt: boolean = true,
18
+ ): Promise<void> => {
19
+ await makeEmptyDir(backupDir);
20
+
21
+ const environments = await getAllEnvironments();
22
+
23
+ for (const environment of environments) {
24
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
25
+ await fs.writeFile(
26
+ path.resolve(backupDir, `${environment.name}.json`),
27
+ JSON.stringify(environment, undefined, 2),
28
+ );
29
+ }
30
+
31
+ if (fmt) {
32
+ await formatUncommittedFiles();
33
+ }
34
+ };
35
+
36
+ if (isDirectlyExecuted(import.meta.url)) {
37
+ await backupEnvironments();
38
+ }
@@ -0,0 +1,78 @@
1
+ import * as t from 'ts-fortress';
2
+
3
+ /**
4
+ * `repo-settings/environments/*.json` の型。
5
+ *
6
+ * Settings > Environments の 1 件に対応する。ファイルは「その環境の望ましい
7
+ * 状態」を丸ごと表しており、 GitHub 側で 2 つに分かれている次の API をまとめて
8
+ * 1 ファイルで管理する:
9
+ *
10
+ * - `PUT /repos/{owner}/{repo}/environments/{environment_name}`
11
+ * - `GET|POST|DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies`
12
+ *
13
+ * GET が返す `protection_rules` は「有効な保護ルールだけが並ぶ配列」だが、この
14
+ * 型は書き込み側( PUT の body )に合わせた平らな形にしている。往復させる側の
15
+ * 形を正とするほうが、ファイルを読んで何が起きるか分かりやすいため。
16
+ */
17
+ export const EnvironmentSettings = t.record({
18
+ name: t.string(''),
19
+
20
+ /** 「 Wait timer 」。分。 0 なら待たない。 */
21
+ wait_timer: t.number(0),
22
+
23
+ /** 「 Prevent self-review 」。 */
24
+ prevent_self_review: t.boolean(false),
25
+
26
+ /** 「 Required reviewers 」。空配列なら承認は要らない。 */
27
+ reviewers: t.array(
28
+ t.record({
29
+ type: t.enumType(['User', 'Team'], {
30
+ typeName: 'EnvironmentReviewerType',
31
+ defaultValue: 'User',
32
+ }),
33
+ id: t.number(0),
34
+ }),
35
+ { typeName: 'EnvironmentReviewers' },
36
+ ),
37
+
38
+ /**
39
+ * 「 Deployment branches and tags 」の選択。
40
+ *
41
+ * - `null` … 「 No restriction 」( どの ref からでも deploy できる )
42
+ * - `protected_branches: true` … 「 Protected branches only 」
43
+ * - `custom_branch_policies: true` … 「 Selected branches and tags 」。
44
+ * 具体的な pattern は下の `deployment_branch_policies` 。
45
+ *
46
+ * 2 つを同時に `true` にはできない。
47
+ */
48
+ deployment_branch_policy: t.union(
49
+ [
50
+ t.record({
51
+ protected_branches: t.boolean(false),
52
+ custom_branch_policies: t.boolean(true),
53
+ }),
54
+ t.nullType,
55
+ ],
56
+ { typeName: 'DeploymentBranchPolicySelection' },
57
+ ),
58
+
59
+ /**
60
+ * `custom_branch_policies` が `true` のときの pattern 一覧。
61
+ *
62
+ * それ以外のときは空配列でなければならない ( `applyEnvironments` が拒否する )。
63
+ * GitHub 側は別エンドポイントだが、「どの ref から deploy できるか」を
64
+ * 決めているのは選択と pattern の組で、片方だけ見ても意味を成さない。
65
+ */
66
+ deployment_branch_policies: t.array(
67
+ t.record({
68
+ name: t.string(''),
69
+ type: t.enumType(['branch', 'tag'], {
70
+ typeName: 'DeploymentBranchPolicyType',
71
+ defaultValue: 'branch',
72
+ }),
73
+ }),
74
+ { typeName: 'DeploymentBranchPolicies' },
75
+ ),
76
+ });
77
+
78
+ export type EnvironmentSettings = t.TypeOf<typeof EnvironmentSettings>;
@@ -0,0 +1,5 @@
1
+ export * from './api/index.mjs';
2
+ export * from './apply.mjs';
3
+ export * from './backup.mjs';
4
+ export * from './constants.mjs';
5
+ export * from './read-environment-contents.mjs';
@@ -0,0 +1,53 @@
1
+ import { type Dirent } from 'node:fs';
2
+ import * as fs from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import * as t from 'ts-fortress';
5
+ import { isDirectlyExecuted, Result } from 'ts-repo-utils';
6
+ import { environmentsDir } from '../constants.mjs';
7
+ import { EnvironmentSettings } from './constants.mjs';
8
+
9
+ export const readEnvironmentFiles = async (): Promise<
10
+ readonly EnvironmentSettings[]
11
+ > => readFilesIn(environmentsDir);
12
+
13
+ export const readEnvironmentBackupFiles = async (): Promise<
14
+ readonly EnvironmentSettings[]
15
+ > => readFilesIn(path.resolve(environmentsDir, './bk'));
16
+
17
+ const readFilesIn = async (
18
+ dir: string,
19
+ ): Promise<readonly EnvironmentSettings[]> => {
20
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
21
+ const files: readonly Dirent<string>[] = await fs.readdir(dir, {
22
+ withFileTypes: true,
23
+ });
24
+
25
+ const fileContents: readonly string[] = await Promise.all(
26
+ files
27
+ .filter((d) => d.isFile())
28
+ .map((d) =>
29
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
30
+ fs.readFile(path.resolve(dir, d.name), { encoding: 'utf8' }),
31
+ ),
32
+ );
33
+
34
+ const validationResults = fileContents.map((content) =>
35
+ EnvironmentSettings.validate(JSON.parse(content)),
36
+ );
37
+
38
+ const mut_values: EnvironmentSettings[] = [];
39
+
40
+ for (const r of validationResults) {
41
+ if (Result.isErr(r)) {
42
+ throw new Error(t.validationErrorsToMessages(r.value).join('\n'));
43
+ }
44
+
45
+ mut_values.push(r.value);
46
+ }
47
+
48
+ return mut_values;
49
+ };
50
+
51
+ if (isDirectlyExecuted(import.meta.url)) {
52
+ await readEnvironmentFiles();
53
+ }
@@ -1,7 +1,9 @@
1
1
  export * from './actions-settings/index.mjs';
2
2
  export * from './constants.mjs';
3
+ export * from './environments/index.mjs';
3
4
  export * from './pages/index.mjs';
4
5
  export * from './repository/index.mjs';
5
6
  export * from './resolve-target-repo.mjs';
6
7
  export * from './ruleset/index.mjs';
7
8
  export * from './variables/index.mjs';
9
+ export * from './vulnerability-alerts/index.mjs';
@@ -0,0 +1,31 @@
1
+ import { type EndpointKeys } from 'octokit-safe-types';
2
+ import { hasKey, isRecord } from 'ts-data-forge';
3
+ import { octokitHeaders, OWNER, REPO } from '../../constants.mjs';
4
+ import { octokit } from '../../octokit.mjs';
5
+ import { VulnerabilityAlertsSettings } from '../constants.mjs';
6
+
7
+ /**
8
+ * Dependabot alerts が有効かどうかを取得する。
9
+ *
10
+ * このエンドポイントは body を返さない: 有効なら 204、無効なら 404。
11
+ * octokit は 404 を例外にするので、それを `enabled: false` として扱う。
12
+ * 「無効」と「読めなかった」は区別する必要があるため、 404 以外は投げ直す。
13
+ */
14
+ export const getVulnerabilityAlerts =
15
+ async (): Promise<VulnerabilityAlertsSettings> => {
16
+ try {
17
+ // https://docs.github.com/rest/repos/repos#check-if-vulnerability-alerts-are-enabled-for-a-repository
18
+ await octokit.request(
19
+ 'GET /repos/{owner}/{repo}/vulnerability-alerts' satisfies EndpointKeys,
20
+ { owner: OWNER, repo: REPO, headers: octokitHeaders },
21
+ );
22
+
23
+ return VulnerabilityAlertsSettings.fill({ enabled: true });
24
+ } catch (error) {
25
+ if (isRecord(error) && hasKey(error, 'status') && error.status === 404) {
26
+ return VulnerabilityAlertsSettings.fill({ enabled: false });
27
+ }
28
+
29
+ throw error;
30
+ }
31
+ };
@@ -0,0 +1,2 @@
1
+ export * from './get-vulnerability-alerts.mjs';
2
+ export * from './set-vulnerability-alerts.mjs';
@@ -0,0 +1,31 @@
1
+ import { type EndpointKeys } from 'octokit-safe-types';
2
+ import { octokitHeaders, OWNER, REPO } from '../../constants.mjs';
3
+ import { octokit } from '../../octokit.mjs';
4
+ import { type VulnerabilityAlertsSettings } from '../constants.mjs';
5
+
6
+ /**
7
+ * Dependabot alerts を JSON の内容に合わせる。
8
+ *
9
+ * 有効化と無効化で別メソッドなので、書き込みは 1 回で済むように分岐する。
10
+ * `enabled: false` はきちんと無効化する — 宣言が現状に合わせて黙るなら、
11
+ * ファイルを読んでも何が有効なのか分からなくなる。
12
+ */
13
+ export const setVulnerabilityAlerts = async (
14
+ settings: VulnerabilityAlertsSettings,
15
+ ): Promise<void> => {
16
+ if (settings.enabled) {
17
+ // https://docs.github.com/rest/repos/repos#enable-vulnerability-alerts
18
+ await octokit.request(
19
+ 'PUT /repos/{owner}/{repo}/vulnerability-alerts' satisfies EndpointKeys,
20
+ { owner: OWNER, repo: REPO, headers: octokitHeaders },
21
+ );
22
+
23
+ return;
24
+ }
25
+
26
+ // https://docs.github.com/rest/repos/repos#disable-vulnerability-alerts
27
+ await octokit.request(
28
+ 'DELETE /repos/{owner}/{repo}/vulnerability-alerts' satisfies EndpointKeys,
29
+ { owner: OWNER, repo: REPO, headers: octokitHeaders },
30
+ );
31
+ };