0

Update branch protection

by
Published Oct 25, 2023

Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server.

Script github Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Update branch protection
6
 * Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server.
7
 */
8
export async function main(
9
  auth: Github,
10
  owner: string,
11
  repo: string,
12
  branch: string,
13
  body: {
14
    allow_deletions?: boolean;
15
    allow_force_pushes?: boolean;
16
    allow_fork_syncing?: boolean;
17
    block_creations?: boolean;
18
    enforce_admins: boolean;
19
    lock_branch?: boolean;
20
    required_conversation_resolution?: boolean;
21
    required_linear_history?: boolean;
22
    required_pull_request_reviews: {
23
      bypass_pull_request_allowances?: {
24
        apps?: string[];
25
        teams?: string[];
26
        users?: string[];
27
        [k: string]: unknown;
28
      };
29
      dismiss_stale_reviews?: boolean;
30
      dismissal_restrictions?: {
31
        apps?: string[];
32
        teams?: string[];
33
        users?: string[];
34
        [k: string]: unknown;
35
      };
36
      require_code_owner_reviews?: boolean;
37
      require_last_push_approval?: boolean;
38
      required_approving_review_count?: number;
39
      [k: string]: unknown;
40
    };
41
    required_status_checks: {
42
      checks?: { app_id?: number; context: string; [k: string]: unknown }[];
43
      contexts: string[];
44
      strict: boolean;
45
      [k: string]: unknown;
46
    };
47
    restrictions: {
48
      apps?: string[];
49
      teams: string[];
50
      users: string[];
51
      [k: string]: unknown;
52
    };
53
    [k: string]: unknown;
54
  }
55
) {
56
  const url = new URL(
57
    `https://api.github.com/repos/${owner}/${repo}/branches/${branch}/protection`
58
  );
59

60
  const response = await fetch(url, {
61
    method: "PUT",
62
    headers: {
63
      "Content-Type": "application/json",
64
      Authorization: "Bearer " + auth.token,
65
    },
66
    body: JSON.stringify(body),
67
  });
68
  if (!response.ok) {
69
    const text = await response.text();
70
    throw new Error(`${response.status} ${text}`);
71
  }
72
  return await response.json();
73
}
74