-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
push.ts
412 lines (368 loc) · 13.1 KB
/
push.ts
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
import { configuration } from '../../configuration';
import { CoreGitConfiguration, GlyphChars } from '../../constants';
import { Container } from '../../container';
import { GitBranch, GitBranchReference, GitReference, Repository } from '../../git/models';
import { Directive, DirectiveQuickPickItem, FlagsQuickPickItem } from '../../quickpicks';
import { isStringArray } from '../../system/array';
import { fromNow } from '../../system/date';
import { pad, pluralize } from '../../system/string';
import { ViewsWithRepositoryFolders } from '../../views/viewBase';
import {
appendReposToTitle,
AsyncStepResultGenerator,
PartialStepState,
pickRepositoriesStep,
pickRepositoryStep,
QuickCommand,
QuickCommandButtons,
QuickPickStep,
StepGenerator,
StepResult,
StepSelection,
StepState,
} from '../quickCommand';
interface Context {
repos: Repository[];
associatedView: ViewsWithRepositoryFolders;
title: string;
}
type Flags = '--force' | '--set-upstream' | string;
interface State<Repos = string | string[] | Repository | Repository[]> {
repos: Repos;
reference?: GitReference;
flags: Flags[];
}
export interface PushGitCommandArgs {
readonly command: 'push';
confirm?: boolean;
state?: Partial<State>;
}
type PushStepState<T extends State = State> = ExcludeSome<StepState<T>, 'repos', string | string[] | Repository>;
export class PushGitCommand extends QuickCommand<State> {
constructor(container: Container, args?: PushGitCommandArgs) {
super(container, 'push', 'push', 'Push', {
description: 'pushes changes from the current branch to a remote',
});
let counter = 0;
if (args?.state?.repos != null && (!Array.isArray(args.state.repos) || args.state.repos.length !== 0)) {
counter++;
}
this.initialState = {
counter: counter,
confirm: args?.confirm,
...args?.state,
};
}
execute(state: State<Repository[]>) {
const index = state.flags.indexOf('--set-upstream');
if (index !== -1) {
if (!GitReference.isBranch(state.reference)) return Promise.resolve();
return this.container.git.pushAll(state.repos, {
force: false,
publish: { remote: state.flags[index + 1] },
reference: state.reference,
});
}
return this.container.git.pushAll(state.repos, {
force: state.flags.includes('--force'),
reference: state.reference,
});
}
protected async *steps(state: PartialStepState<State>): StepGenerator {
const context: Context = {
repos: this.container.git.openRepositories,
associatedView: this.container.commitsView,
title: this.title,
};
if (state.flags == null) {
state.flags = [];
}
if (state.repos != null && !Array.isArray(state.repos)) {
state.repos = [state.repos as string];
}
let skippedStepOne = false;
while (this.canStepsContinue(state)) {
context.title = this.title;
if (state.counter < 1 || state.repos == null || state.repos.length === 0 || isStringArray(state.repos)) {
skippedStepOne = false;
if (context.repos.length === 1) {
skippedStepOne = true;
state.counter++;
state.repos = [context.repos[0]];
} else if (state.reference != null) {
const result = yield* pickRepositoryStep(
{ ...state, repos: undefined, repo: state.reference.repoPath },
context,
);
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.repos = [result];
} else {
const result = yield* pickRepositoriesStep(
state as ExcludeSome<typeof state, 'repos', string | Repository>,
context,
{ skipIfPossible: state.counter >= 1 },
);
// Always break on the first step (so we will go back)
if (result === StepResult.Break) break;
state.repos = result;
}
}
if (this.confirm(state.confirm)) {
const result = yield* this.confirmStep(state as PushStepState, context);
if (result === StepResult.Break) {
// If we skipped the previous step, make sure we back up past it
if (skippedStepOne) {
state.counter--;
}
continue;
}
state.flags = result;
}
QuickCommand.endSteps(state);
void this.execute(state as State<Repository[]>);
}
return state.counter < 0 ? StepResult.Break : undefined;
}
private async *confirmStep(state: PushStepState, context: Context): AsyncStepResultGenerator<Flags[]> {
const useForceWithLease = configuration.getAny<boolean>(CoreGitConfiguration.UseForcePushWithLease) ?? false;
let step: QuickPickStep<FlagsQuickPickItem<Flags>>;
if (state.repos.length > 1) {
step = this.createConfirmStep(appendReposToTitle(`Confirm ${context.title}`, state, context), [
FlagsQuickPickItem.create<Flags>(state.flags, [], {
label: this.title,
detail: `Will push ${state.repos.length} repositories`,
}),
FlagsQuickPickItem.create<Flags>(state.flags, ['--force'], {
label: `Force ${this.title}${useForceWithLease ? ' (with lease)' : ''}`,
description: `--force${useForceWithLease ? '-with-lease' : ''}`,
detail: `Will force push${useForceWithLease ? ' (with lease)' : ''} ${
state.repos.length
} repositories`,
}),
]);
} else {
const [repo] = state.repos;
const items: FlagsQuickPickItem<Flags>[] = [];
if (GitReference.isBranch(state.reference)) {
if (state.reference.remote) {
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
[],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: 'Cannot push remote branch',
}),
);
} else {
const branch = await repo.getBranch(state.reference.name);
if (branch != null && branch?.upstream == null) {
for (const remote of await repo.getRemotes()) {
items.push(
FlagsQuickPickItem.create<Flags>(
state.flags,
['--set-upstream', remote.name, branch.name],
{
label: `Publish ${branch.name} to ${remote.name}`,
detail: `Will publish ${GitReference.toString(branch)} to ${remote.name}`,
},
),
);
}
if (items.length) {
step = this.createConfirmStep(
appendReposToTitle('Confirm Publish', state, context),
items,
undefined,
{ placeholder: 'Confirm Publish' },
);
} else {
step = this.createConfirmStep(
appendReposToTitle('Confirm Publish', state, context),
[],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: 'Cancel Publish',
detail: 'Cannot publish; No remotes found',
}),
{ placeholder: 'Confirm Publish' },
);
}
} else if (branch != null && branch?.state.behind > 0) {
const currentBranch = await repo.getBranch();
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
branch.id === currentBranch?.id
? [
FlagsQuickPickItem.create<Flags>(state.flags, ['--force'], {
label: `Force ${this.title}${useForceWithLease ? ' (with lease)' : ''}`,
description: `--force${useForceWithLease ? '-with-lease' : ''}`,
detail: `Will force push${useForceWithLease ? ' (with lease)' : ''} ${
branch?.state.ahead ? ` ${pluralize('commit', branch.state.ahead)}` : ''
}${branch.getRemoteName() ? ` to ${branch.getRemoteName()}` : ''}${
branch != null && branch.state.behind > 0
? `, overwriting ${pluralize('commit', branch.state.behind)}${
branch?.getRemoteName()
? ` on ${branch.getRemoteName()}`
: ''
}`
: ''
}`,
}),
]
: [],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `Cannot push; ${GitReference.toString(
branch,
)} is behind ${branch.getRemoteName()} by ${pluralize('commit', branch.state.behind)}`,
}),
);
} else if (branch != null && branch?.state.ahead > 0) {
step = this.createConfirmStep(appendReposToTitle(`Confirm ${context.title}`, state, context), [
FlagsQuickPickItem.create<Flags>(state.flags, [branch.getRemoteName()!], {
label: this.title,
detail: `Will push ${pluralize(
'commit',
branch.state.ahead,
)} from ${GitReference.toString(branch)} to ${branch.getRemoteName()}`,
}),
]);
} else {
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context),
[],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: 'No commits found to push',
}),
);
}
}
} else {
const status = await repo.getStatus();
const branch: GitBranchReference = {
refType: 'branch',
name: status?.branch ?? 'HEAD',
ref: status?.branch ?? 'HEAD',
remote: false,
repoPath: repo.path,
};
if (status?.state.ahead === 0) {
if (state.reference == null && status.upstream == null) {
state.reference = branch;
for (const remote of await repo.getRemotes()) {
items.push(
FlagsQuickPickItem.create<Flags>(
state.flags,
['--set-upstream', remote.name, status.branch],
{
label: `Publish ${branch.name} to ${remote.name}`,
detail: `Will publish ${GitReference.toString(branch)} to ${remote.name}`,
},
),
);
}
}
if (items.length) {
step = this.createConfirmStep(
appendReposToTitle('Confirm Publish', state, context),
items,
undefined,
{ placeholder: 'Confirm Publish' },
);
} else if (status.upstream == null) {
step = this.createConfirmStep(
appendReposToTitle('Confirm Publish', state, context),
[],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: 'Cancel Publish',
detail: 'Cannot publish; No remotes found',
}),
{ placeholder: 'Confirm Publish' },
);
} else {
step = this.createConfirmStep(
appendReposToTitle('Confirm Push', state, context),
[],
DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `Cannot push; No commits ahead of ${GitBranch.getRemote(status.upstream)}`,
}),
);
}
} else {
let lastFetchedOn = '';
const lastFetched = await repo.getLastFetched();
if (lastFetched !== 0) {
lastFetchedOn = `${pad(GlyphChars.Dot, 2, 2)}Last fetched ${fromNow(new Date(lastFetched))}`;
}
let pushDetails;
if (state.reference != null) {
pushDetails = `${
status?.state.ahead
? ` commits up to and including ${GitReference.toString(state.reference, {
label: false,
})}`
: ''
}${status?.upstream ? ` to ${GitBranch.getRemote(status.upstream)}` : ''}`;
} else {
pushDetails = `${status?.state.ahead ? ` ${pluralize('commit', status.state.ahead)}` : ''}${
status?.upstream ? ` to ${GitBranch.getRemote(status.upstream)}` : ''
}`;
}
step = this.createConfirmStep(
appendReposToTitle(`Confirm ${context.title}`, state, context, lastFetchedOn),
[
...(status?.state.behind
? []
: [
FlagsQuickPickItem.create<Flags>(state.flags, [], {
label: this.title,
detail: `Will push${pushDetails}`,
}),
]),
FlagsQuickPickItem.create<Flags>(state.flags, ['--force'], {
label: `Force ${this.title}${useForceWithLease ? ' (with lease)' : ''}`,
description: `--force${useForceWithLease ? '-with-lease' : ''}`,
detail: `Will force push${useForceWithLease ? ' (with lease)' : ''} ${pushDetails}${
status != null && status.state.behind > 0
? `, overwriting ${pluralize('commit', status.state.behind)}${
status?.upstream ? ` on ${GitBranch.getRemote(status.upstream)}` : ''
}`
: ''
}`,
}),
],
status?.state.behind
? DirectiveQuickPickItem.create(Directive.Cancel, true, {
label: `Cancel ${this.title}`,
detail: `Cannot push; ${GitReference.toString(branch)} is behind${
status?.upstream ? ` ${GitBranch.getRemote(status.upstream)}` : ''
} by ${pluralize('commit', status.state.behind)}`,
})
: undefined,
);
step.additionalButtons = [QuickCommandButtons.Fetch];
step.onDidClickButton = async (quickpick, button) => {
if (button !== QuickCommandButtons.Fetch || quickpick.busy) return false;
quickpick.title = `Confirm ${context.title}${pad(GlyphChars.Dot, 2, 2)}Fetching${
GlyphChars.Ellipsis
}`;
quickpick.busy = true;
quickpick.enabled = false;
try {
await repo.fetch({ progress: true });
// Signal that the step should be retried
return true;
} finally {
quickpick.busy = false;
quickpick.enabled = true;
}
};
}
}
}
const selection: StepSelection<typeof step> = yield step;
return QuickCommand.canPickStepContinue(step, state, selection) ? selection[0].item : StepResult.Break;
}
}