-
-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathgithub.ts
More file actions
172 lines (157 loc) · 4.56 KB
/
Copy pathgithub.ts
File metadata and controls
172 lines (157 loc) · 4.56 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { Buffer } from "node:buffer";
import * as core from "@actions/core";
import { exec, getExecOutput } from "@actions/exec";
import { context } from "@actions/github";
import { commitChangesSinceBase } from "@changesets/ghcommit";
import { setupOctokit, type Octokit } from "./octokit.ts";
export type CommitMode = "git-cli" | "github-api";
type GitOptions = {
cwd: string;
env?: Record<string, string>;
};
const push = async (branch: string, options: GitOptions) => {
await exec("git", ["push", "origin", `HEAD:${branch}`, "--force"], options);
};
const switchToMaybeExistingBranch = async (
branch: string,
options: GitOptions,
) => {
let { stderr } = await getExecOutput("git", ["checkout", branch], {
ignoreReturnCode: true,
...options,
});
let isCreatingBranch = !stderr
.toString()
.includes(`Switched to a new branch '${branch}'`);
if (isCreatingBranch) {
await exec("git", ["checkout", "-b", branch], options);
}
};
const reset = async (pathSpec: string, options: GitOptions) => {
await exec("git", ["reset", `--hard`, pathSpec], options);
};
const commitAll = async (message: string, options: GitOptions) => {
await exec("git", ["add", "."], options);
await exec("git", ["commit", "-m", message], options);
};
const checkIfClean = async (options: GitOptions): Promise<boolean> => {
const { stdout } = await getExecOutput(
"git",
["status", "--porcelain"],
options,
);
return !stdout.length;
};
export class GitHub {
readonly #githubToken: string;
readonly octokit: Octokit;
readonly cwd: string;
readonly commitMode: CommitMode;
constructor(options: {
githubToken: string;
cwd: string;
commitMode?: CommitMode;
}) {
this.#githubToken = options.githubToken;
this.cwd = options.cwd;
this.commitMode = options.commitMode ?? "git-cli";
this.octokit = setupOctokit(options.githubToken);
}
getToken() {
return this.#githubToken;
}
#getCliAuthEnv(): Record<string, string> {
const basic = Buffer.from(`x-access-token:${this.#githubToken}`).toString(
"base64",
);
const serverUrl = (
context.serverUrl ??
process.env.GITHUB_SERVER_URL ??
"https://github.com"
).replace(/\/+$/, "");
const gitConfigCount = Number(process.env.GIT_CONFIG_COUNT ?? 0);
if (!Number.isInteger(gitConfigCount) || gitConfigCount < 0) {
throw new Error(
`Invalid GIT_CONFIG_COUNT value: ${process.env.GIT_CONFIG_COUNT}`,
);
}
return {
GIT_CONFIG_COUNT: String(gitConfigCount + 1),
[`GIT_CONFIG_KEY_${gitConfigCount}`]: `http.${serverUrl}/.extraheader`,
[`GIT_CONFIG_VALUE_${gitConfigCount}`]: `AUTHORIZATION: basic ${basic}`,
};
}
async setupUser() {
if (this.commitMode === "github-api") {
return;
}
await exec("git", ["config", "user.name", `"github-actions[bot]"`], {
cwd: this.cwd,
});
await exec(
"git",
[
"config",
"user.email",
`"41898282+github-actions[bot]@users.noreply.github.com"`,
],
{
cwd: this.cwd,
},
);
}
async pushTag(tag: string) {
if (this.commitMode === "github-api") {
return this.octokit.rest.git
.createRef({
...context.repo,
ref: `refs/tags/${tag}`,
sha: context.sha,
})
.catch((err) => {
// Assuming tag was manually pushed in custom publish script
core.warning(`Failed to create tag ${tag}: ${err.message}`);
});
}
await exec("git", ["push", "origin", tag], {
cwd: this.cwd,
env: {
...process.env,
...this.#getCliAuthEnv(),
} as Record<string, string>,
});
}
async prepareBranch(branch: string) {
if (this.commitMode === "github-api") {
// Preparing a new local branch is not necessary when using the API
return;
}
await switchToMaybeExistingBranch(branch, { cwd: this.cwd });
await reset(context.sha, { cwd: this.cwd });
}
async pushChanges({ branch, message }: { branch: string; message: string }) {
if (this.commitMode === "github-api") {
await commitChangesSinceBase({
octokit: this.octokit,
...context.repo,
branch,
message,
base: {
commit: context.sha,
},
cwd: this.cwd,
});
return;
}
if (!(await checkIfClean({ cwd: this.cwd }))) {
await commitAll(message, { cwd: this.cwd });
}
await push(branch, {
cwd: this.cwd,
env: {
...process.env,
...this.#getCliAuthEnv(),
} as Record<string, string>,
});
}
}