-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathgit-branch-ops.mts
More file actions
253 lines (238 loc) · 6.68 KB
/
Copy pathgit-branch-ops.mts
File metadata and controls
253 lines (238 loc) · 6.68 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
/**
* Branch operations for Socket CLI's git utilities: checkout, create,
* delete, push, existence checks, and default/base-branch detection.
*
* Extracted from operations.mts to keep that file under the 1000-line
* File size hard cap.
*
* Every branch name here can originate from `GITHUB_BASE_REF`,
* `GITHUB_REF_NAME`, or the scanned repository's `socket.json`, so it travels
* as a `spawnGit` operand and is fenced behind `--end-of-options`.
*/
import { debug, debugDir } from '@socketsecurity/lib-stable/debug/output'
import {
getGithubBaseRef,
getGithubRefName,
getGithubRefType,
} from '@socketsecurity/lib-stable/env/github'
import { isSpawnError } from '@socketsecurity/lib-stable/process/spawn/errors'
import { FLAG_QUIET } from '../../constants/cli.mts'
import { SOCKET_DEFAULT_BRANCH } from '../../constants/socket.mts'
import { debugGit } from '../debug.mts'
import { gitQuietStdio, spawnGit } from './spawn-git.mts'
// Listed in order of check preference.
const COMMON_DEFAULT_BRANCH_NAMES = [
// Modern default (GitHub, GitLab, Bitbucket have switched to this).
'main',
// inclusive-language: external-api — git's historical default branch.
'master',
// Common in Git Flow workflows, main for stable, develop for ongoing work.
'develop',
// Used by teams adopting trunk-based development practices.
'trunk',
// Used in some older enterprise setups and tools.
'default',
]
/**
* Try to detect the default branch name by checking common patterns. Returns
* the first branch that exists in the repository.
*/
export async function detectDefaultBranch(
cwd = process.cwd(),
): Promise<string> {
// First pass: check all local branches
for (
let i = 0, { length } = COMMON_DEFAULT_BRANCH_NAMES;
i < length;
i += 1
) {
const branch = COMMON_DEFAULT_BRANCH_NAMES[i]!
if (await gitLocalBranchExists(branch, cwd)) {
return branch
}
}
// Second pass: check remote branches only if no local branch found
for (
let i = 0, { length } = COMMON_DEFAULT_BRANCH_NAMES;
i < length;
i += 1
) {
const branch = COMMON_DEFAULT_BRANCH_NAMES[i]!
if (await gitRemoteBranchExists(branch, cwd)) {
return branch
}
}
return SOCKET_DEFAULT_BRANCH
}
export async function getBaseBranch(cwd = process.cwd()): Promise<string> {
// 1. In a pull request, this is always the base branch.
const githubBaseRef = getGithubBaseRef()
if (githubBaseRef) {
return githubBaseRef
}
// 2. If it's a branch, not a tag, GITHUB_REF_TYPE should be 'branch'.
const githubRefType = getGithubRefType()
const githubRefName = getGithubRefName()
if (githubRefType === 'branch' && githubRefName) {
return githubRefName
}
// 3. Try to resolve the default remote branch using 'git remote show origin'.
// This handles detached HEADs or workflows triggered by tags/releases.
try {
const result = await spawnGit(['remote', 'show'], {
cwd,
operands: ['origin'],
})
if (!result) {
return 'main'
}
const originDetails = result.stdout
const match = /(?<=HEAD branch: ).+/.exec(originDetails)
if (match && match.length > 0 && match[0]) {
return match[0].trim()
}
} catch {}
// GitHub and GitLab default to branch name "main"
// https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-branches#about-the-default-branch
return 'main'
}
export async function gitCheckoutBranch(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
await spawnGit(['checkout'], {
cwd,
operands: [branch],
stdio: gitQuietStdio(),
})
debugGit(`checkout ${branch}`, true)
return true
} catch (e) {
debugGit(`checkout ${branch}`, false, { error: e })
}
return false
}
export async function gitCreateBranch(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
if (await gitLocalBranchExists(branch)) {
return true
}
try {
await spawnGit(['branch'], {
cwd,
operands: [branch],
stdio: gitQuietStdio(),
})
debugGit(`branch ${branch}`, true)
return true
} catch (e) {
debugGit(`branch ${branch}`, false, { error: e })
}
return false
}
export async function gitDeleteBranch(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
// Will throw with exit code 1 if branch does not exist.
await spawnGit(['branch', '-D'], {
cwd,
operands: [branch],
stdio: gitQuietStdio(),
})
return true
} catch (e) {
// Expected failure when branch doesn't exist.
debugDir({
message: `Branch deletion failed (may not exist): ${branch}`,
error: e,
})
}
return false
}
export async function gitDeleteRemoteBranch(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
// Will throw with exit code 1 if branch does not exist.
await spawnGit(['push', '--delete'], {
cwd,
operands: ['origin', branch],
stdio: gitQuietStdio(),
})
return true
} catch (e) {
// Expected failure when remote branch doesn't exist.
debugDir({
message: `Remote branch deletion failed (may not exist): ${branch}`,
error: e,
})
}
return false
}
export async function gitLocalBranchExists(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
// Will throw with exit code 1 if the branch does not exist.
await spawnGit(['show-ref', FLAG_QUIET], {
cwd,
operands: [`refs/heads/${branch}`],
stdio: gitQuietStdio(),
})
return true
} catch {
// Expected when branch doesn't exist - no logging needed.
}
return false
}
export async function gitPushBranch(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
await spawnGit(['push', '--force', '--set-upstream'], {
cwd,
operands: ['origin', branch],
stdio: gitQuietStdio(),
})
debugGit(`push ${branch}`, true)
return true
} catch (e) {
if (isSpawnError(e) && e.code === 128) {
debug(
"Push denied: token requires write permissions for 'contents' and 'pull-requests'",
)
debugDir(e)
debugDir({ branch })
} else {
debugGit(`push ${branch}`, false, { error: e })
}
}
return false
}
export async function gitRemoteBranchExists(
branch: string,
cwd = process.cwd(),
): Promise<boolean> {
try {
const lsRemoteResult = await spawnGit(['ls-remote', '--heads'], {
cwd,
operands: ['origin', branch],
})
return lsRemoteResult.stdout.length > 0
} catch (e) {
// Expected when remote is not accessible or branch doesn't exist.
debugDir({
message: `Remote branch check failed: ${branch}`,
error: e,
})
}
return false
}