-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush.ts
More file actions
619 lines (571 loc) · 22.8 KB
/
push.ts
File metadata and controls
619 lines (571 loc) · 22.8 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import { basename } from "node:path";
import type { Command } from "commander";
import { predictMergeConflict } from "../lib/analysis";
import {
ArbError,
type CommandContext,
arbAction,
assertNoInProgressOperation,
readWorkspaceConfig,
} from "../lib/core";
import { getCommitsBetweenFull, gitNetwork, networkTimeout } from "../lib/git";
import type { RepoRemotes } from "../lib/git";
import { createRenderContext, finishSummary, render } from "../lib/render";
import type { Cell, OutputNode } from "../lib/render";
import { skipCell, upToDateCell, verboseCommitsToNodes } from "../lib/render";
import { cell, suffix } from "../lib/render";
import { type RepoStatus, resolveWhereFilter } from "../lib/status";
import {
VERBOSE_COMMIT_LIMIT,
buildCachedStatusAssess,
classifyNetworkError,
confirmOrExit,
resolveDefaultFetch,
runPlanFlow,
} from "../lib/sync";
export type { PushAssessment } from "../lib/sync";
import type { PushAssessment } from "../lib/sync";
import { dryRunNotice, info, inlineResult, inlineStart, plural, red } from "../lib/terminal";
import { requireBranch, requireWorkspace, resolveReposFromArgsOrStdin, workspaceRepoDirs } from "../lib/workspace";
export function registerPushCommand(program: Command): void {
program
.command("push [repos...]")
.option("-f, --force", "Force push with lease")
.option("--include-merged", "Include branches already merged into base")
.option("--include-wrong-branch", "Include repos on a different branch than the workspace")
.option("--fetch", "Fetch from all remotes before push (default)")
.option("-N, --no-fetch", "Skip fetching before push")
.option("-y, --yes", "Skip confirmation prompt")
.option("--dry-run", "Show what would happen without executing")
.option("-v, --verbose", "Show outgoing commits in the plan")
.option("-w, --where <filter>", "Only push repos matching status filter (comma = OR, + = AND, ^ = negate)")
.summary("Push feature branches to the remote")
.description(
"Examples:\n\n arb push Push all repos\n arb push api web -v Push specific repos, show commits\n arb push --dry-run Preview without pushing\n\nFetches all repos, then pushes the feature branch for all repos, or only the named repos. Pushes to the share remote (origin by default, or as configured for fork workflows). Sets up tracking on first push. Shows a plan and asks for confirmation before pushing. The plan highlights repos that are behind the base branch, with a hint to rebase before pushing.\n\nSkips repos with no commits to push, or whose branches have been merged into the base branch unless --include-merged is used. Repos on a different branch than the workspace are skipped unless --include-wrong-branch is used; when included, they are pushed to their actual branch. If a remote branch was deleted after merge, use --include-merged to recreate it.\n\nAfter rebase, amend, or squash, Arborist detects that all remote commits are outdated and pushes automatically with --force-with-lease. Use --force when the remote has genuinely new commits that you want to overwrite.\n\nUse --verbose to show the outgoing commits for each repo in the plan. Fetches before push by default; use -N/--no-fetch to skip fetching when refs are known to be fresh. Use --where to filter repos by status flags. See 'arb help filtering' for filter syntax. See 'arb help remotes' for remote role resolution.",
)
.action(
arbAction(async (ctx, repoArgs: string[], options) => {
const { wsDir } = requireWorkspace(ctx);
await assertNoInProgressOperation(wsDir);
const repoNames = await resolveReposFromArgsOrStdin(wsDir, repoArgs);
await runPush(ctx, repoNames, options);
}),
);
}
export async function runPush(
ctx: CommandContext,
repoNames: string[],
options: {
force?: boolean;
includeMerged?: boolean;
includeWrongBranch?: boolean;
fetch?: boolean;
yes?: boolean;
dryRun?: boolean;
verbose?: boolean;
where?: string;
},
): Promise<void> {
const { wsDir, workspace } = requireWorkspace(ctx);
const branch = await requireBranch(wsDir, workspace);
const where = resolveWhereFilter(options);
const selectedRepos = repoNames;
const cache = ctx.cache;
const remotesMap = await cache.resolveRemotesMap(selectedRepos, ctx.reposDir);
const configBase = readWorkspaceConfig(`${wsDir}/.arbws/config.json`)?.base ?? null;
const shouldFetch = resolveDefaultFetch(options.fetch);
const allFetchDirs = workspaceRepoDirs(wsDir);
const selectedSet = new Set(selectedRepos);
const fetchDirs = allFetchDirs.filter((dir) => selectedSet.has(basename(dir)));
const allRepos = fetchDirs.map((d) => basename(d));
const assessWithCache = buildCachedStatusAssess<PushAssessment>({
repos: selectedRepos,
wsDir,
reposDir: ctx.reposDir,
branch,
configBase,
remotesMap,
cache,
analysisCache: ctx.analysisCache,
where,
classify: async ({ repoDir, status }) => {
const headSha = status.headSha ?? "";
return assessPushRepo(status, repoDir, branch, headSha, {
force: options.force,
includeMerged: options.includeMerged,
includeWrongBranch: options.includeWrongBranch,
});
},
});
const assess = async (fetchFailed: string[], unchangedRepos: Set<string>) =>
applyForcePushPolicy(await assessWithCache(fetchFailed, unchangedRepos), options.force === true);
const postAssess = async (nextAssessments: PushAssessment[]) => {
await predictPushBaseConflicts(nextAssessments, remotesMap);
if (options.verbose) return gatherPushVerboseCommits(nextAssessments, remotesMap);
return nextAssessments;
};
const assessments = await runPlanFlow({
shouldFetch,
fetchDirs,
reposForFetchReport: allRepos,
remotesMap,
assess,
postAssess,
formatPlan: (nextAssessments) => formatPushPlan(nextAssessments, remotesMap, options.verbose),
onPostFetch: () => cache.invalidateAfterFetch(),
});
const willPush = assessments.filter(
(a) => a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated",
);
const upToDate = assessments.filter((a) => a.outcome === "up-to-date");
const skipped = assessments.filter((a) => a.outcome === "skip");
if (willPush.length === 0) {
info(upToDate.length > 0 ? "All repos up to date" : "Nothing to do");
return;
}
if (options.dryRun) {
dryRunNotice();
return;
}
// Phase 3: confirm
await confirmOrExit({
yes: options.yes,
message: `Push ${plural(willPush.length, "repo")}?`,
});
process.stderr.write("\n");
// Phase 4: execute
let pushOk = 0;
const pushTimeout = networkTimeout("ARB_PUSH_TIMEOUT", 120);
for (const a of willPush) {
inlineStart(a.repo, "pushing");
const pushArgs =
a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated"
? ["push", "-u", "--force-with-lease", a.shareRemote, a.branch]
: ["push", "-u", a.shareRemote, a.branch];
const pushResult = await gitNetwork(a.repoDir, pushTimeout, pushArgs);
if (pushResult.exitCode === 0) {
const resultMsg = a.ahead === 0 ? "force pushed (overwrote remote)" : `pushed ${plural(a.ahead, "commit")}`;
inlineResult(a.repo, resultMsg);
pushOk++;
} else {
inlineResult(a.repo, red("failed"));
process.stderr.write("\n");
const errText = pushResult.stderr.trim();
if (errText) {
for (const line of errText.split("\n")) {
process.stderr.write(` ${line}\n`);
}
}
const errorClass = classifyNetworkError(errText);
const recoveryHint =
pushResult.exitCode === 124
? "Check your network connection, then re-run 'arb push' to continue. Adjust timeout with ARB_PUSH_TIMEOUT."
: errorClass === "offline"
? "Check your network connection, then re-run 'arb push' to continue."
: errorClass === "auth"
? "Check your credentials or token, then re-run 'arb push' to continue."
: errorClass === "not-found"
? "Verify the remote URL is correct, then re-run 'arb push' to continue."
: "To resolve, check the error above, then re-run 'arb push' to continue.";
process.stderr.write(`\n ${recoveryHint}\n`);
throw new ArbError(`Push failed for ${a.repo}`);
}
}
// Phase 5: summary
process.stderr.write("\n");
const parts = [`Pushed ${plural(pushOk, "repo")}`];
if (upToDate.length > 0) parts.push(`${upToDate.length} up to date`);
if (skipped.length > 0) parts.push(`${skipped.length} skipped`);
finishSummary(parts, false);
}
export function formatPushPlan(
assessments: PushAssessment[],
remotesMap: Map<string, RepoRemotes>,
verbose?: boolean,
): string {
const nodes = buildPushPlanNodes(assessments, remotesMap, verbose);
const ctx = createRenderContext();
return render(nodes, ctx);
}
export function buildPushPlanNodes(
assessments: PushAssessment[],
remotesMap: Map<string, RepoRemotes>,
verbose?: boolean,
): OutputNode[] {
const nodes: OutputNode[] = [{ kind: "gap" }];
const rows = assessments.map((a) => {
let actionCell: Cell;
if (a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated") {
actionCell = pushActionCell(a, remotesMap);
} else if (a.outcome === "up-to-date") {
actionCell = upToDateCell();
} else {
actionCell = skipCell(a.skipReason ?? "", a.skipFlag);
}
let afterRow: OutputNode[] | undefined;
if (
verbose &&
(a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated") &&
a.verbose?.commits &&
a.verbose.commits.length > 0
) {
const label = `Outgoing to ${a.shareRemote}:`;
afterRow = verboseCommitsToNodes(a.verbose.commits, a.verbose.totalCommits ?? a.verbose.commits.length, label);
}
return {
cells: { repo: cell(a.repo), action: actionCell },
afterRow,
};
});
nodes.push({
kind: "table",
columns: [
{ header: "REPO", key: "repo" },
{ header: "ACTION", key: "action" },
],
rows,
});
const behindBaseCount = assessments.filter(
(a) =>
(a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated") &&
a.behindBase > 0,
).length;
if (behindBaseCount > 0) {
nodes.push({
kind: "hint",
cell: cell(
` hint: ${plural(behindBaseCount, "repo")} behind base — consider 'arb rebase' before pushing`,
"muted",
),
});
}
const mergedNewWorkCount = assessments.filter((a) => a.skipFlag === "merged-new-work").length;
if (mergedNewWorkCount > 0) {
nodes.push({
kind: "hint",
cell: cell(
` hint: ${plural(mergedNewWorkCount, "repo")} ${mergedNewWorkCount === 1 ? "was" : "were"} merged but ${mergedNewWorkCount === 1 ? "has" : "have"} new commits since — run 'arb rebase' or 'arb extract <workspace> --starting-with <sha>' to split`,
"muted",
),
});
}
const wrongBranchCount = assessments.filter(
(a) =>
a.wrongBranch &&
(a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated"),
).length;
if (wrongBranchCount > 0) {
nodes.push({
kind: "hint",
cell: cell(` hint: ${plural(wrongBranchCount, "repo")} on a different branch than the workspace`, "muted"),
});
}
const shallowRepos = assessments.filter((a) => a.shallow);
for (const a of shallowRepos) {
nodes.push({
kind: "message",
level: "attention",
text: `${a.repo} is a shallow clone; ahead/behind counts may be inaccurate`,
});
}
nodes.push({ kind: "gap" });
return nodes;
}
export function pushActionCell(a: PushAssessment, remotesMap: Map<string, RepoRemotes>): Cell {
const remotes = remotesMap.get(a.repo);
const forkText = remotes && remotes.base !== remotes.share ? ` → ${a.shareRemote}` : "";
const behindBaseSuffix = (r: Cell): Cell => {
if (a.behindBase <= 0) return r;
const label =
a.baseConflictPrediction === "conflict"
? ", conflict likely"
: a.baseConflictPrediction === "clean"
? ", conflict unlikely"
: "";
return suffix(
r,
` (${a.behindBase} behind base${label})`,
a.baseConflictPrediction === "conflict" ? "attention" : "default",
);
};
let result: Cell;
if (a.outcome === "will-push") {
const remoteBranch = `${a.shareRemote}/${a.branch}`;
const newBranchSuffix = a.recreate
? ` (recreate: ${remoteBranch})`
: a.newBranch
? ` (new branch: ${remoteBranch})`
: "";
let desc: string;
if (a.baseAhead > 0 || a.rebased > 0) {
const fromBase = Math.max(0, a.ahead - a.baseAhead);
const newCount = Math.max(0, a.ahead - fromBase - a.rebased);
const parts: string[] = [];
if (fromBase > 0) parts.push(`${fromBase} from ${a.baseRef}`);
if (a.rebased > 0) parts.push(`${a.rebased} rebased`);
if (newCount > 0) parts.push(`${newCount} new`);
desc = parts.length > 0 ? parts.join(" + ") : plural(a.ahead, "commit");
} else {
desc = plural(a.ahead, "commit");
}
result = cell(`${desc} to push${newBranchSuffix}`);
result = behindBaseSuffix(result);
if (forkText) result = suffix(result, forkText);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
} else if (a.outcome === "will-force-push-outdated") {
// will-force-push-outdated — all remote commits are accounted for (rebased, replaced, or squashed)
const outdatedSuffix = ` (replaces ${a.behind} outdated on ${a.shareRemote})`;
if (a.baseAhead > 0 || a.rebased > 0) {
const fromBase = Math.max(0, a.ahead - a.baseAhead);
const newCount = Math.max(0, a.ahead - fromBase - a.rebased);
const parts: string[] = [];
if (fromBase > 0) parts.push(`${fromBase} from ${a.baseRef}`);
if (a.rebased > 0) parts.push(`${a.rebased} rebased`);
if (newCount > 0) parts.push(`${newCount} new`);
const desc = parts.length > 0 ? parts.join(" + ") : plural(a.ahead, "commit");
result = cell(`${desc} to push${outdatedSuffix}`);
result = behindBaseSuffix(result);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
} else {
result = cell(`${plural(a.ahead, "commit")} to push${outdatedSuffix}`);
result = behindBaseSuffix(result);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
}
} else if (a.ahead === 0) {
// will-force-push with ahead=0 — overwriting remote (behind-remote + force)
result = cell(`force push (overwrite ${a.behind} on ${a.shareRemote})`);
result = behindBaseSuffix(result);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
} else if (a.baseAhead > 0 || a.rebased > 0) {
// will-force-push with base info
const fromBase = Math.max(0, a.ahead - a.baseAhead);
const newCount = Math.max(0, a.ahead - fromBase - a.rebased);
const parts: string[] = [];
if (fromBase > 0) parts.push(`${fromBase} from ${a.baseRef}`);
if (a.rebased > 0) parts.push(`${a.rebased} rebased`);
if (newCount > 0) parts.push(`${newCount} new`);
const desc = parts.length > 0 ? parts.join(" + ") : plural(a.ahead, "commit");
result = cell(`${desc} to push (force)`);
result = behindBaseSuffix(result);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
} else {
// will-force-push without base info
result = cell(`${plural(a.ahead, "commit")} to push (force \u2014 ${a.behind} behind ${a.shareRemote})`);
result = behindBaseSuffix(result);
if (a.headSha) result = suffix(result, ` (HEAD ${a.headSha})`, "muted");
}
if (a.wrongBranch) {
result = suffix(result, ` (branch: ${a.branch})`, "attention");
}
return result;
}
export function applyForcePushPolicy(assessments: PushAssessment[], allowForce: boolean): PushAssessment[] {
return assessments.map((a) => {
if (a.outcome !== "will-force-push" || allowForce) return a;
const rebasedHint = a.rebased > 0 ? `, ${a.rebased} rebased` : "";
return {
...a,
outcome: "skip",
skipReason: `diverged from ${a.shareRemote}${rebasedHint} (use --force)`,
skipFlag: "diverged",
};
});
}
async function gatherPushVerboseCommits(
assessments: PushAssessment[],
remotesMap: Map<string, RepoRemotes>,
): Promise<PushAssessment[]> {
return Promise.all(
assessments.map(async (a) => {
if (!(a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated")) {
return a;
}
const shareRemote = remotesMap.get(a.repo)?.share;
if (!shareRemote) return a;
const ref =
a.newBranch || a.recreate
? `${remotesMap.get(a.repo)?.base ?? shareRemote}/HEAD`
: `${shareRemote}/${a.branch}`;
const commits = await getCommitsBetweenFull(a.repoDir, ref, "HEAD");
const total = commits.length;
return {
...a,
verbose: {
commits: commits.slice(0, VERBOSE_COMMIT_LIMIT).map((c) => ({
shortHash: c.shortHash,
subject: c.subject,
})),
totalCommits: total,
},
};
}),
);
}
async function predictPushBaseConflicts(
assessments: PushAssessment[],
remotesMap: Map<string, RepoRemotes>,
): Promise<void> {
await Promise.all(
assessments
.filter(
(a) =>
a.behindBase > 0 &&
(a.outcome === "will-push" || a.outcome === "will-force-push" || a.outcome === "will-force-push-outdated"),
)
.map(async (a) => {
const baseRemote = remotesMap.get(a.repo)?.base;
if (!baseRemote) return;
const ref = `${baseRemote}/${a.baseRef}`;
const prediction = await predictMergeConflict(a.repoDir, ref);
a.baseConflictPrediction = prediction === null ? null : prediction.hasConflict ? "conflict" : "clean";
}),
);
}
export function assessPushRepo(
status: RepoStatus,
repoDir: string,
branch: string,
headSha: string,
options?: { force?: boolean; includeMerged?: boolean; includeWrongBranch?: boolean },
): PushAssessment {
const behindBase = status.base?.behind ?? 0;
const base = {
repo: status.name,
repoDir,
ahead: 0,
behind: 0,
rebased: 0,
replaced: 0,
squashed: 0,
baseAhead: status.base?.ahead ?? 0,
baseRef: status.base?.ref ?? "base",
branch,
shareRemote: status.share.remote,
newBranch: false,
headSha,
recreate: false,
behindBase,
shallow: status.identity.shallow,
wrongBranch: undefined as boolean | undefined,
};
// Operation in progress
if (status.operation !== null) {
return {
...base,
outcome: "skip",
skipReason: `${status.operation} in progress`,
skipFlag: "operation-in-progress",
};
}
// Branch check — detached or wrong branch
if (status.identity.headMode.kind === "detached") {
return { ...base, outcome: "skip", skipReason: "HEAD is detached", skipFlag: "detached-head" };
}
if (status.identity.headMode.branch !== branch) {
if (!options?.includeWrongBranch) {
return {
...base,
outcome: "skip",
skipReason: `on branch ${status.identity.headMode.branch}, expected ${branch} (use --include-wrong-branch)`,
skipFlag: "wrong-branch",
};
}
base.branch = status.identity.headMode.branch;
base.wrongBranch = true;
}
// Base branch merged into default — retarget before pushing
if (status.base?.baseMergedIntoDefault != null) {
const baseName = status.base.configuredRef ?? status.base.ref;
return {
...base,
outcome: "skip",
skipReason: `base branch ${baseName} was merged into default (retarget first with 'arb retarget')`,
skipFlag: "base-merged-into-default",
};
}
// Remote branch was deleted (gone)
if (status.share.refMode === "gone") {
if (status.base?.merge != null && !options?.includeMerged) {
const n = status.base.merge?.newCommitsAfter;
if (n && n > 0) {
return {
...base,
outcome: "skip",
skipReason: `branch was merged into ${status.base.ref}, but has ${n} new ${n === 1 ? "commit" : "commits"} since (rebase or use --include-merged to push)`,
skipFlag: "merged-new-work",
};
}
return {
...base,
outcome: "skip",
skipReason: `already merged into ${status.base.ref} (use --include-merged to recreate)`,
skipFlag: "already-merged",
};
}
const ahead = status.base?.ahead ?? 1;
return { ...base, outcome: "will-push", ahead, recreate: true };
}
// Merged but not gone — nothing useful to push unless forced
if (status.base?.merge != null && !options?.includeMerged) {
const n = status.base.merge?.newCommitsAfter;
if (n && n > 0) {
return {
...base,
outcome: "skip",
skipReason: `branch was merged into ${status.base.ref}, but has ${n} new ${n === 1 ? "commit" : "commits"} since (rebase or use --include-merged to push)`,
skipFlag: "merged-new-work",
};
}
return {
...base,
outcome: "skip",
skipReason: `already merged into ${status.base.ref} (use --include-merged)`,
skipFlag: "already-merged",
};
}
// Never pushed (noRef) — new branch
if (status.share.refMode === "noRef") {
const ahead = status.base?.ahead ?? 1;
if (ahead === 0) {
return { ...base, outcome: "skip", skipReason: "no commits to push", skipFlag: "no-commits" };
}
return { ...base, outcome: "will-push", ahead, newBranch: true };
}
// Has push/pull counts — compare
const toPush = status.share.toPush ?? 0;
const toPull = status.share.toPull ?? 0;
if (toPush === 0 && toPull === 0) {
return { ...base, outcome: "up-to-date" };
}
if (toPush === 0 && toPull > 0) {
if (options?.force) {
return { ...base, outcome: "will-force-push", ahead: 0, behind: toPull };
}
return {
...base,
outcome: "skip",
skipReason: `behind ${status.share.remote} (pull first?)`,
skipFlag: "behind-remote",
behind: toPull,
};
}
if (toPush > 0 && toPull > 0) {
const rebased = status.share.outdated?.rebased ?? 0;
const replaced = status.share.outdated?.replaced ?? 0;
const squashed = status.share.outdated?.squashed ?? 0;
const allOutdated = rebased + replaced + squashed >= toPull;
if (allOutdated) {
return {
...base,
outcome: "will-force-push-outdated",
ahead: toPush,
behind: toPull,
rebased,
replaced,
squashed,
};
}
return { ...base, outcome: "will-force-push", ahead: toPush, behind: toPull, rebased, replaced, squashed };
}
return { ...base, outcome: "will-push", ahead: toPush };
}