-
-
Notifications
You must be signed in to change notification settings - Fork 413
Expand file tree
/
Copy pathgithub.ts
More file actions
264 lines (245 loc) · 8.16 KB
/
Copy pathgithub.ts
File metadata and controls
264 lines (245 loc) · 8.16 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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";
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;
};
function getHttpUrl(remoteUrl: string): string | undefined {
try {
const url = new URL(remoteUrl);
if (url.protocol !== "http:" && url.protocol !== "https:") {
return;
}
// Git includes the username when deciding which URL-specific config is
// most specific, so retain it. Password, query, and fragment do not
// participate in matching; strip them before copying the URL into the env.
url.password = "";
url.search = "";
url.hash = "";
return url.href;
} catch {
return;
}
}
export class GitHub {
readonly #githubToken: string;
readonly octokit: Octokit;
readonly cwd: string;
readonly pushWithGitCli: boolean;
readonly serverUrl: string;
constructor(options: {
githubToken: string;
cwd: string;
pushWithGitCli?: boolean;
serverUrl?: string;
}) {
this.#githubToken = options.githubToken;
this.cwd = options.cwd;
this.pushWithGitCli = options.pushWithGitCli ?? false;
this.serverUrl = (
options.serverUrl ??
context.serverUrl ??
process.env.GITHUB_SERVER_URL ??
"https://github.com"
).replace(/\/+$/, "");
this.octokit = setupOctokit(options.githubToken);
}
getToken() {
return this.#githubToken;
}
async #getCliAuthEnv(): Promise<Record<string, string>> {
const basic = Buffer.from(`x-access-token:${this.#githubToken}`).toString(
"base64",
);
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}`,
);
}
// `git push origin` may use remote.origin.pushurl instead of the fetch URL,
// and Git supports multiple push URLs. Ask Git for the effective targets so
// the URL-specific auth below applies to every HTTP destination.
const { stdout } = await getExecOutput(
"git",
["remote", "get-url", "--push", "--all", "origin"],
{
cwd: this.cwd,
ignoreReturnCode: true,
// A user-configured remote can contain credentials.
silent: true,
},
);
// Git chooses HTTP config by URL specificity. The host key handles the
// extraheader normally installed by actions/checkout, while an exact push
// URL also outranks any inherited path-specific extraheader. Only the most
// specific matching subsection contributes, so these do not duplicate it.
const extraHeaderKeys = new Set([`http.${this.serverUrl}/.extraheader`]);
for (const remoteUrl of stdout.split(/\r?\n/)) {
const httpUrl = getHttpUrl(remoteUrl);
if (httpUrl !== undefined) {
extraHeaderKeys.add(`http.${httpUrl}.extraheader`);
}
}
const authHeader = `AUTHORIZATION: basic ${basic}`;
const env: Record<string, string> = {
GIT_CONFIG_COUNT: String(gitConfigCount + extraHeaderKeys.size * 2),
};
// GIT_CONFIG_COUNT/KEY_n/VALUE_n add command-scoped config. Preserve any
// existing entries and append ours. `http.extraHeader` is multi-valued, so
// merely adding our Authorization header would make Git send both tokens.
// An empty value resets the list; the following value adds only our token.
//
// In v1, `github-token` lived in ~/.netrc. When checkout had already
// supplied Authorization through an extraheader, that header took
// precedence and ~/.netrc was effectively a fallback. These entries
// intentionally make `github-token` win for pushes.
let index = 0;
for (const extraHeaderKey of extraHeaderKeys) {
const resetIndex = gitConfigCount + index * 2;
const authIndex = resetIndex + 1;
env[`GIT_CONFIG_KEY_${resetIndex}`] = extraHeaderKey;
env[`GIT_CONFIG_VALUE_${resetIndex}`] = "";
env[`GIT_CONFIG_KEY_${authIndex}`] = extraHeaderKey;
env[`GIT_CONFIG_VALUE_${authIndex}`] = authHeader;
index++;
}
return env;
}
async ensureGitUser() {
// Check the exact identities that Git would use for commits without
// allowing Git to fall back to auto-detected values like user@hostname.
// This covers explicit GIT_AUTHOR_* / GIT_COMMITTER_* env vars, local
// config, and global config. A partial identity, with only a name or only
// an email, does not pass this check. If either identity is missing,
// configure our default bot user as a fallback.
const authorIdentity = await getExecOutput(
"git",
["-c", "user.useConfigOnly=true", "var", "GIT_AUTHOR_IDENT"],
{
cwd: this.cwd,
ignoreReturnCode: true,
silent: true,
},
);
const committerIdentity = await getExecOutput(
"git",
["-c", "user.useConfigOnly=true", "var", "GIT_COMMITTER_IDENT"],
{
cwd: this.cwd,
ignoreReturnCode: true,
silent: true,
},
);
if (authorIdentity.exitCode === 0 && committerIdentity.exitCode === 0) {
return;
}
core.info("Setting Git user to github-actions[bot]");
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.pushWithGitCli) {
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,
...(await this.#getCliAuthEnv()),
} as Record<string, string>,
});
}
async prepareBranch(branch: string) {
if (!this.pushWithGitCli) {
// 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.pushWithGitCli) {
await commitChangesSinceBase({
octokit: this.octokit,
...context.repo,
branch,
message,
base: {
commit: context.sha,
},
cwd: this.cwd,
});
return;
}
if (!(await checkIfClean({ cwd: this.cwd }))) {
await this.ensureGitUser();
await commitAll(message, { cwd: this.cwd });
}
await push(branch, {
cwd: this.cwd,
env: {
...process.env,
...(await this.#getCliAuthEnv()),
} as Record<string, string>,
});
}
}