-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathcommandsAndMenu.tsx
2243 lines (2077 loc) · 67.4 KB
/
commandsAndMenu.tsx
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { JupyterFrontEnd } from '@jupyterlab/application';
import {
Dialog,
InputDialog,
MainAreaWidget,
Notification,
ReactWidget,
showDialog,
showErrorMessage
} from '@jupyterlab/apputils';
import {
CodeEditor,
CodeEditorWrapper,
IEditorFactoryService
} from '@jupyterlab/codeeditor';
import { IEditorLanguageRegistry } from '@jupyterlab/codemirror';
import { PathExt, URLExt } from '@jupyterlab/coreutils';
import { FileBrowser, FileBrowserModel } from '@jupyterlab/filebrowser';
import { Contents } from '@jupyterlab/services';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITerminal } from '@jupyterlab/terminal';
import { ITranslator, TranslationBundle } from '@jupyterlab/translation';
import {
ContextMenuSvg,
Toolbar,
ToolbarButton,
closeIcon,
saveIcon
} from '@jupyterlab/ui-components';
import { ArrayExt, find } from '@lumino/algorithm';
import { CommandRegistry } from '@lumino/commands';
import { PromiseDelegate } from '@lumino/coreutils';
import { Message } from '@lumino/messaging';
import { ContextMenu, DockPanel, Menu, Panel, Widget } from '@lumino/widgets';
import * as React from 'react';
import { CancelledError } from './cancelledError';
import { BranchPicker } from './components/BranchPicker';
import { CONTEXT_COMMANDS } from './components/FileList';
import { ManageRemoteDialogue } from './components/ManageRemoteDialogue';
import { NewTagDialogBox } from './components/NewTagDialog';
import { createPlainTextDiff } from './components/diff/PlainTextDiff';
import { PreviewMainAreaWidget } from './components/diff/PreviewMainAreaWidget';
import { DiffModel } from './components/diff/model';
import { AUTH_ERROR_MESSAGES, requestAPI } from './git';
import { GitExtension, getDiffProvider } from './model';
import { showDetails, showError } from './notifications';
import {
addIcon,
diffIcon,
discardIcon,
gitIcon,
historyIcon,
openIcon,
removeIcon,
tagIcon
} from './style/icons';
import { CommandIDs, ContextCommandIDs, Git, IGitExtension } from './tokens';
import { AdvancedPushForm } from './widgets/AdvancedPushForm';
import { GitCredentialsForm } from './widgets/CredentialsBox';
import { CheckboxForm } from './widgets/GitResetToRemoteForm';
import { discardAllChanges } from './widgets/discardAllChanges';
export interface IGitCloneArgs {
/**
* Path in which to clone the Git repository
*/
path: string;
/**
* Git repository url
*/
url: string;
/**
* Whether to activate git versioning in the clone or not.
* If false, this will remove the .git folder after cloning.
*/
versioning?: boolean;
/**
* Whether to activate git recurse submodules clone or not.
*/
submodules?: boolean;
}
/**
* Git operations requiring authentication
*/
export enum Operation {
Clone = 'Clone',
Pull = 'Pull',
Push = 'Push',
ForcePush = 'ForcePush',
Fetch = 'Fetch'
}
interface IFileDiffArgument {
context?: Git.Diff.IContext;
filePath: string;
isText: boolean;
status?: Git.Status;
isPreview?: boolean;
// when file has been relocated
previousFilePath?: string;
}
export namespace CommandArguments {
export interface IGitFileDiff {
files: IFileDiffArgument[];
}
export interface IGitContextAction {
files: Git.IStatusFile[];
}
export interface IGitCommitInfo {
commit: Git.ISingleCommitInfo;
}
}
function pluralizedContextLabel(singular: string, plural: string) {
return (args: any) => {
const { files } = args as any as CommandArguments.IGitContextAction;
if (files.length > 1) {
return plural;
} else {
return singular;
}
};
}
/**
* Add the commands for the git extension.
*/
export function addCommands(
app: JupyterFrontEnd,
gitModel: GitExtension,
editorFactory: IEditorFactoryService,
languageRegistry: IEditorLanguageRegistry,
fileBrowserModel: FileBrowserModel,
settings: ISettingRegistry.ISettings,
translator: ITranslator
): void {
const { commands, shell, serviceManager } = app;
const trans = translator.load('jupyterlab_git');
/**
* Commit using a keystroke combination when in CommitBox.
*
* This command is not accessible from the user interface (not visible),
* as it is handled by a signal listener in the CommitBox component instead.
* The label and caption are given to ensure that the command will
* show up in the shortcut editor UI with a nice description.
*/
commands.addCommand(CommandIDs.gitSubmitCommand, {
label: trans.__('Commit from the Commit Box'),
caption: trans.__(
'Submit the commit using the summary and description from commit box'
),
execute: () => void 0,
isVisible: () => false
});
/**
* Add open terminal in the Git repository
*/
commands.addCommand(CommandIDs.gitTerminalCommand, {
label: trans.__('Open Git Repository in Terminal'),
caption: trans.__('Open a New Terminal to the Git Repository'),
execute: async args => {
const main = (await commands.execute(
'terminal:create-new',
args
)) as MainAreaWidget<ITerminal.ITerminal>;
try {
if (gitModel.pathRepository !== null) {
const terminal = main.content;
terminal.session.send({
type: 'stdin',
content: [
`cd "${gitModel.pathRepository
.split('"')
.join('\\"')
.split('`')
.join('\\`')}"\n`
]
});
}
return main;
} catch (e) {
console.error(e);
main.dispose();
}
},
isEnabled: () =>
gitModel.pathRepository !== null &&
app.serviceManager.terminals.isAvailable()
});
/** Add open/go to git interface command */
commands.addCommand(CommandIDs.gitUI, {
label: trans.__('Git Interface'),
caption: trans.__('Go to Git user interface'),
execute: () => {
try {
shell.activateById('jp-git-sessions');
} catch (err) {
console.error('Fail to open Git tab.');
}
}
});
/** Add git init command */
commands.addCommand(CommandIDs.gitInit, {
label: trans.__('Initialize a Repository'),
caption: trans.__(
'Create an empty Git repository or reinitialize an existing one'
),
execute: async () => {
const currentPath = app.serviceManager.contents.localPath(
fileBrowserModel.path
);
const result = await showDialog({
title: trans.__('Initialize a Repository'),
body: trans.__('Do you really want to make this directory a Git Repo?'),
buttons: [
Dialog.cancelButton({ label: trans.__('Cancel') }),
Dialog.warnButton({ label: trans.__('Yes') })
]
});
if (result.button.accept) {
const id = Notification.emit(trans.__('Initializing…'), 'in-progress', {
autoClose: false
});
try {
await gitModel.init(currentPath);
gitModel.pathRepository = currentPath;
Notification.update({
id,
message: trans.__('Git repository initialized.'),
type: 'success',
autoClose: 5000
});
} catch (error) {
console.error(
trans.__(
'Encountered an error when initializing the repository. Error: '
),
error
);
Notification.update({
id,
message: trans.__('Failed to initialize the Git repository'),
type: 'error',
...showError(error as Error, trans)
});
}
}
},
isEnabled: () => gitModel.pathRepository === null
});
/** Open URL externally */
commands.addCommand(CommandIDs.gitOpenUrl, {
label: args => trans.__(args['text'] as string),
execute: args => {
const url = args['url'] as string;
window.open(url);
}
});
/** add toggle for simple staging */
commands.addCommand(CommandIDs.gitToggleSimpleStaging, {
label: trans.__('Simple staging'),
isToggled: () => !!settings.composite['simpleStaging'],
execute: args => {
settings.set('simpleStaging', !settings.composite['simpleStaging']);
}
});
/** add toggle for double click opens diffs */
commands.addCommand(CommandIDs.gitToggleDoubleClickDiff, {
label: trans.__('Double click opens diff'),
isToggled: () => !!settings.composite['doubleClickDiff'],
execute: args => {
settings.set('doubleClickDiff', !settings.composite['doubleClickDiff']);
}
});
/** Command to add a remote Git repository */
commands.addCommand(CommandIDs.gitManageRemote, {
label: trans.__('Manage Remote Repositories'),
caption: trans.__('Manage Remote Repositories'),
isEnabled: () => gitModel.pathRepository !== null,
execute: () => {
if (gitModel.pathRepository === null) {
console.warn(
trans.__('Not in a Git repository. Unable to add a remote.')
);
return;
}
const widgetId = 'git-dialog-ManageRemote';
let anchor = document.querySelector<HTMLDivElement>(`#${widgetId}`);
if (!anchor) {
anchor = document.createElement('div');
anchor.id = widgetId;
document.body.appendChild(anchor);
}
const dialog = ReactWidget.create(
<ManageRemoteDialogue
trans={trans}
model={gitModel}
onClose={() => dialog.dispose()}
/>
);
Widget.attach(dialog, anchor);
}
});
async function showGitignore(error: any) {
const model = new CodeEditor.Model({});
const repoPath = gitModel.getRelativeFilePath();
const id = repoPath + '/.git-ignore';
const contentData = await gitModel.readGitIgnore();
const gitIgnoreWidget = find(
shell.widgets(),
shellWidget => shellWidget.id === id
);
if (gitIgnoreWidget) {
shell.activateById(id);
return;
}
model.sharedModel.setSource(contentData ? contentData : '');
const editor = new CodeEditorWrapper({
factory: editorFactory.newDocumentEditor.bind(editorFactory),
model: model
});
const modelChangedSignal = model.sharedModel.changed;
editor.disposed.connect(() => {
model.dispose();
});
const preview = new MainAreaWidget({
content: editor
});
preview.title.label = '.gitignore';
preview.id = id;
preview.title.icon = gitIcon;
preview.title.closable = true;
preview.title.caption = repoPath + '/.gitignore';
const saveButton = new ToolbarButton({
icon: saveIcon,
onClick: async () => {
if (saved) {
return;
}
const newContent = model.sharedModel.getSource();
try {
await gitModel.writeGitIgnore(newContent);
preview.title.className = '';
saved = true;
} catch (error) {
console.log('Could not save .gitignore');
}
},
tooltip: trans.__('Saves .gitignore')
});
let saved = true;
preview.toolbar.addItem('save', saveButton);
shell.add(preview);
modelChangedSignal.connect(() => {
if (saved) {
saved = false;
preview.title.className = 'not-saved';
}
});
}
/* Helper: Show gitignore hidden file */
async function showGitignoreHiddenFile(error: any, hidePrompt: boolean) {
if (hidePrompt) {
return showGitignore(error);
}
const result = await showDialog({
title: trans.__('Warning: The .gitignore file is a hidden file.'),
body: (
<div>
{trans.__(
'Hidden files by default cannot be accessed with the regular code editor. In order to open the .gitignore file you must:'
)}
<ol>
<li>
{trans.__(
'Print the command below to create a jupyter_server_config.py file with defaults commented out. If you already have the file located in .jupyter, skip this step.'
)}
<div style={{ padding: '0.5rem' }}>
{'jupyter server --generate-config'}
</div>
</li>
<li>
{trans.__(
'Open jupyter_server_config.py, uncomment out the following line and set it to True:'
)}
<div style={{ padding: '0.5rem' }}>
{'c.ContentsManager.allow_hidden = False'}
</div>
</li>
</ol>
</div>
),
buttons: [
Dialog.cancelButton({ label: trans.__('Cancel') }),
Dialog.okButton({ label: trans.__('Show .gitignore file anyways') })
],
checkbox: {
label: trans.__('Do not show this warning again'),
checked: false
}
});
if (result.button.accept) {
settings.set('hideHiddenFileWarning', result.isChecked);
showGitignore(error);
}
}
/** Add git open gitignore command */
commands.addCommand(CommandIDs.gitOpenGitignore, {
label: trans.__('Open .gitignore'),
caption: trans.__('Open .gitignore'),
isEnabled: () => gitModel.pathRepository !== null,
execute: async () => {
try {
await gitModel.ensureGitignore();
} catch (error: any) {
if (error?.name === 'hiddenFile') {
await showGitignoreHiddenFile(
error,
settings.composite['hideHiddenFileWarning'] as boolean
);
}
}
}
});
/** Add git push command */
commands.addCommand(CommandIDs.gitPush, {
label: args =>
(args['advanced'] as boolean)
? trans.__('Push to Remote (Advanced)')
: trans.__('Push to Remote'),
caption: trans.__('Push code to remote repository'),
isEnabled: () => gitModel.pathRepository !== null,
execute: async args => {
let id: string | null = null;
try {
let remote;
let force;
if (args['advanced'] as boolean) {
const result = await showDialog({
title: trans.__('Please select push options.'),
body: new AdvancedPushForm(trans, gitModel),
buttons: [
Dialog.cancelButton({ label: trans.__('Cancel') }),
Dialog.okButton({ label: trans.__('Proceed') })
]
});
if (result.button.accept && result.value) {
remote = result.value.remoteName;
force = result.value.force;
} else {
return;
}
}
id = Notification.emit(trans.__('Pushing…'), 'in-progress', {
autoClose: false
});
const details = await showGitOperationDialog(
gitModel,
force ? Operation.ForcePush : Operation.Push,
trans,
(args = { remote })
);
Notification.update({
id,
message: trans.__('Successfully pushed'),
type: 'success',
...showDetails(details, trans)
});
} catch (error: any) {
if (error.name !== 'CancelledError') {
console.error(
trans.__('Encountered an error when pushing changes. Error: '),
error
);
const message = trans.__('Failed to push');
const options = showError(error as Error, trans);
if (id) {
Notification.update({
id,
message,
type: 'error',
...options
});
} else {
Notification.error(message, options);
}
} else {
if (id) {
Notification.dismiss(id);
}
}
}
}
});
/** Add git pull command */
commands.addCommand(CommandIDs.gitPull, {
label: args =>
args.force
? trans.__('Pull from Remote (Force)')
: trans.__('Pull from Remote'),
caption: args =>
args.force
? trans.__(
'Discard all current changes and pull from remote repository'
)
: trans.__('Pull latest code from remote repository'),
isEnabled: () => gitModel.pathRepository !== null,
execute: async args => {
let id: string | null = null;
try {
if (args.force) {
await discardAllChanges(gitModel, trans, args.fallback as boolean);
}
id = Notification.emit(trans.__('Pulling…'), 'in-progress', {
autoClose: false
});
const details = await showGitOperationDialog(
gitModel,
Operation.Pull,
trans
);
Notification.update({
id,
message: trans.__('Successfully pulled'),
type: 'success',
...showDetails(details, trans)
});
} catch (error: any) {
if (error.name !== 'CancelledError') {
console.error(
'Encountered an error when pulling changes. Error: ',
error
);
const errorMsg =
typeof error === 'string' ? error : (error as Error).message;
// Discard changes then retry pull
if (
errorMsg
.toLowerCase()
.includes(
'your local changes to the following files would be overwritten by merge'
)
) {
await commands.execute(CommandIDs.gitPull, {
force: true,
fallback: true
});
} else {
if ((error as any).cancelled) {
if (id) {
Notification.dismiss(id);
}
} else {
const message = trans.__('Failed to pull');
const options = showError(error, trans);
if (id) {
Notification.update({
id,
message,
...options
});
} else {
Notification.error(message, options);
}
}
}
} else {
if (id) {
Notification.dismiss(id);
}
}
}
}
});
/** Add git reset --hard <remote-tracking-branch> command */
commands.addCommand(CommandIDs.gitResetToRemote, {
label: trans.__('Reset to Remote'),
caption: trans.__('Reset Current Branch to Remote State'),
isEnabled: () => gitModel.pathRepository !== null,
execute: async () => {
const result = await showDialog({
title: trans.__('Reset to Remote'),
body: new CheckboxForm(
trans.__(
'To bring the current branch to the state of its corresponding remote tracking branch, \
a hard reset will be performed, which may result in some files being permanently deleted \
and some changes being permanently discarded. Are you sure you want to proceed? \
This action cannot be undone.'
),
trans.__('Close all opened files to avoid conflicts')
),
buttons: [
Dialog.cancelButton({ label: trans.__('Cancel') }),
Dialog.warnButton({ label: trans.__('Proceed') })
]
});
if (result.button.accept) {
let id: string | null = null;
try {
if (result.value?.checked) {
id = Notification.emit(
trans.__('Closing all opened files...'),
'in-progress'
);
await fileBrowserModel.manager.closeAll();
}
const message = trans.__('Resetting...');
if (id) {
Notification.update({ id, message });
} else {
id = Notification.emit(message, 'in-progress', {
autoClose: false
});
}
await gitModel.resetToCommit(gitModel.status.remote ?? undefined);
Notification.update({
id,
message: trans.__('Successfully reset'),
type: 'success',
...showDetails(
trans.__(
'Successfully reset the current branch to its remote state'
),
trans
)
});
} catch (error) {
console.error(
'Encountered an error when resetting the current branch to its remote state. Error: ',
error
);
const message = trans.__('Reset failed');
const options = showError(error as Error, trans);
if (id) {
Notification.update({
id,
type: 'error',
message,
...options
});
} else {
Notification.error(message, options);
}
}
}
}
});
/**
* Git display diff command - internal command
*
* @params model: The diff model to display
* @params isText: Optional, whether the content is a plain text
* @params isMerge: Optional, whether the diff is a merge conflict
* @returns the main area widget or null
*/
commands.addCommand(CommandIDs.gitShowDiff, {
label: trans.__('Show Diff'),
caption: trans.__('Display a file diff.'),
execute: async args => {
const { model, isText, isPreview } = args as any as {
model: Git.Diff.IModel;
isText?: boolean;
isPreview?: boolean;
};
const fullPath = PathExt.join(
model.repositoryPath ?? '/',
model.filename
);
const buildDiffWidget =
getDiffProvider(fullPath) ??
(isText &&
(options =>
createPlainTextDiff({
...options,
editorFactory: editorFactory.newInlineEditor.bind(editorFactory),
languageRegistry
})));
if (buildDiffWidget) {
const id = `git-diff-${fullPath}-${model.reference.label}-${model.challenger.label}`;
const mainAreaItems = shell.widgets('main');
let mainAreaItem: Widget | null = null;
for (const item of mainAreaItems) {
if (item.id === id) {
shell.activateById(id);
mainAreaItem = item;
break;
}
}
if (!mainAreaItem) {
const content = new Panel();
const modelIsLoading = new PromiseDelegate<void>();
const diffWidget = (mainAreaItem = new PreviewMainAreaWidget<Panel>({
content,
reveal: modelIsLoading.promise,
isPreview
}));
diffWidget.id = id;
diffWidget.title.label = PathExt.basename(model.filename);
diffWidget.title.caption = fullPath;
diffWidget.title.icon = diffIcon;
diffWidget.title.closable = true;
diffWidget.title.className = 'jp-git-diff-title';
diffWidget.addClass('jp-git-diff-parent-widget');
shell.add(diffWidget, 'main');
shell.activateById(diffWidget.id);
// Search for the tab
const dockPanel = (app.shell as any)._dockPanel as DockPanel;
// Get the index of the most recent tab opened
let tabPosition = -1;
const tabBar = Array.from(dockPanel.tabBars()).find(bar => {
tabPosition = bar.titles.indexOf(diffWidget.title);
return tabPosition !== -1;
});
// Pin the preview screen if applicable
if (tabBar) {
PreviewMainAreaWidget.pinWidget(tabPosition, tabBar, diffWidget);
}
// Create the diff widget
try {
const widget = await buildDiffWidget({
model,
toolbar: diffWidget.toolbar,
translator
});
diffWidget.toolbar.addItem('spacer', Toolbar.createSpacerItem());
// Do not allow the user to refresh during merge conflicts
if (model.hasConflict) {
const resolveButton = new ToolbarButton({
label: trans.__('Mark as resolved'),
onClick: async () => {
if (!widget.isFileResolved) {
const result = await showDialog({
title: trans.__('Resolve with conflicts'),
body: trans.__(
'Are you sure you want to mark this file as resolved with merge conflicts?'
)
});
// Bail early if the user wants to finish resolving conflicts
if (!result.button.accept) {
return;
}
}
try {
await serviceManager.contents.save(
fullPath,
await widget.getResolvedFile()
);
await gitModel.add(model.filename);
await gitModel.refresh();
} catch (reason) {
Notification.error(
(reason as Error).message ?? (reason as string)
);
} finally {
diffWidget.dispose();
}
},
tooltip: trans.__('Mark file as resolved'),
className: 'jp-git-diff-resolve'
});
diffWidget.toolbar.addItem('resolve', resolveButton);
} else {
const refreshButton = new ToolbarButton({
label: trans.__('Refresh'),
onClick: async () => {
await widget.refresh();
refreshButton.hide();
},
tooltip: trans.__('Refresh diff widget'),
className: 'jp-git-diff-refresh'
});
refreshButton.hide();
diffWidget.toolbar.addItem('refresh', refreshButton);
const refresh = () => {
refreshButton.show();
};
model.changed.connect(refresh);
widget.disposed.connect(() => model.changed.disconnect(refresh));
}
// Load the diff widget
modelIsLoading.resolve();
content.addWidget(widget);
} catch (reason) {
console.error(reason);
const msg = `Load Diff Model Error (${
(reason as Error).message || reason
})`;
modelIsLoading.reject(msg);
}
if (
model.challenger.source === Git.Diff.SpecialRef.INDEX ||
model.challenger.source === Git.Diff.SpecialRef.WORKING ||
model.reference.source === Git.Diff.SpecialRef.INDEX ||
model.reference.source === Git.Diff.SpecialRef.WORKING
) {
const maybeClose = (_: IGitExtension, status: Git.IStatus) => {
const targetFile = status.files.find(
fileStatus => model.filename === fileStatus.from
);
if (!targetFile || targetFile.status === 'unmodified') {
gitModel.statusChanged.disconnect(maybeClose);
mainAreaItem!.dispose();
}
};
gitModel.statusChanged.connect(maybeClose);
}
}
return mainAreaItem;
} else {
await showErrorMessage(
trans.__('Diff Not Supported'),
trans.__(
'Diff is not supported for %1 files.',
PathExt.extname(model.filename).toLocaleLowerCase()
)
);
return null;
}
},
icon: diffIcon.bindprops({ stylesheet: 'menuItem' })
});
commands.addCommand(CommandIDs.gitMerge, {
label: trans.__('Merge Branch…'),
caption: trans.__('Merge selected branch in the current branch'),
execute: async args => {
let { branch }: { branch?: string } = args ?? {};
if (!branch) {
// Prompts user to pick a branch
const localBranches = gitModel.branches.filter(
branch => !branch.is_current_branch && !branch.is_remote_branch
);
const widgetId = 'git-dialog-MergeBranch';
let anchor = document.querySelector<HTMLDivElement>(`#${widgetId}`);
if (!anchor) {
anchor = document.createElement('div');
anchor.id = widgetId;
document.body.appendChild(anchor);
}
const waitForDialog = new PromiseDelegate<string | null>();
const dialog = ReactWidget.create(
<BranchPicker
action="merge"
currentBranch={gitModel.currentBranch?.name ?? ''}
branches={localBranches}
onClose={(branch?: string) => {
dialog.dispose();
waitForDialog.resolve(branch ?? null);
}}
trans={trans}
/>
);
Widget.attach(dialog, anchor);
branch = (await waitForDialog.promise) ?? undefined;
}
if (branch) {
const id = Notification.emit(
trans.__("Merging branch '%1'…", branch),
'in-progress'
);
try {
await gitModel.merge(branch);
} catch (err) {
Notification.update({
id,
type: 'error',
message: trans.__(
"Failed to merge branch '%1' into '%2'.",
branch,
gitModel.currentBranch?.name
),
...showError(err as Error, trans)
});
return;
}
Notification.update({
id,
type: 'success',
message: trans.__(
"Branch '%1' merged into '%2'.",
branch,
gitModel.currentBranch?.name
)
});
}
},
isEnabled: () =>
gitModel.branches.some(
branch => !branch.is_current_branch && !branch.is_remote_branch
)
});
commands.addCommand(CommandIDs.gitRebase, {
label: trans.__('Rebase branch…'),
caption: trans.__('Rebase current branch onto the selected branch'),
execute: async args => {
let { branch }: { branch?: string } = args ?? {};
if (!branch) {
// Prompts user to pick a branch
const localBranches = gitModel.branches.filter(
branch => !branch.is_current_branch && !branch.is_remote_branch
);
const widgetId = 'git-dialog-MergeBranch';
let anchor = document.querySelector<HTMLDivElement>(`#${widgetId}`);
if (!anchor) {
anchor = document.createElement('div');
anchor.id = widgetId;
document.body.appendChild(anchor);
}
const waitForDialog = new PromiseDelegate<string | null>();
const dialog = ReactWidget.create(
<BranchPicker
action="rebase"
currentBranch={gitModel.currentBranch?.name ?? ''}
branches={localBranches}
onClose={(branch?: string) => {
dialog.dispose();
waitForDialog.resolve(branch ?? null);
}}
trans={trans}
/>
);
Widget.attach(dialog, anchor);
branch = (await waitForDialog.promise) ?? undefined;
}
if (branch) {
const id = Notification.emit(
trans.__("Rebasing current branch onto '%1'…", branch),
'in-progress'
);
try {
await gitModel.rebase(branch);
} catch (err) {