-
Notifications
You must be signed in to change notification settings - Fork 317
/
model.ts
1865 lines (1729 loc) · 53.9 KB
/
model.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
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 { IChangedArgs, PathExt, URLExt } from '@jupyterlab/coreutils';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { JSONExt, JSONObject } from '@lumino/coreutils';
import { Poll } from '@lumino/polling';
import { ISignal, Signal } from '@lumino/signaling';
import { AUTH_ERROR_MESSAGES, requestAPI } from './git';
import { TaskHandler } from './taskhandler';
import { Git, IGitExtension } from './tokens';
import { decodeStage } from './utils';
// Default refresh interval (in milliseconds) for polling the current Git status (NOTE: this value should be the same value as in the plugin settings schema):
const DEFAULT_REFRESH_INTERVAL = 3000; // ms
// Available diff providers
const DIFF_PROVIDERS: {
[key: string]: { name: string; callback: Git.Diff.ICallback };
} = {};
/**
* Get the diff provider for a filename
* @param filename Filename to look for
* @returns The diff provider callback or undefined
*/
export function getDiffProvider(
filename: string
): Git.Diff.ICallback | undefined {
return DIFF_PROVIDERS[PathExt.extname(filename)?.toLocaleLowerCase()]
?.callback;
}
/**
* Class for creating a model for retrieving info from, and interacting with, a remote Git repository.
*/
export class GitExtension implements IGitExtension {
/**
* Returns an extension model.
*
* @param app - frontend application
* @param settings - plugin settings
* @returns extension model
*/
constructor(
docmanager: IDocumentManager = null,
docRegistry: DocumentRegistry = null,
settings?: ISettingRegistry.ISettings
) {
this._docmanager = docmanager;
this._docRegistry = docRegistry;
this._settings = settings || null;
this._taskHandler = new TaskHandler(this);
// Initialize repository status
this._clearStatus();
const interval = DEFAULT_REFRESH_INTERVAL;
this._statusPoll = new Poll({
factory: this._refreshModel,
frequency: {
interval,
backoff: true,
max: 300 * 1000
},
standby: this._refreshStandby
});
this._fetchPoll = new Poll({
auto: false,
factory: this._fetchRemotes,
frequency: {
interval,
backoff: true,
max: 300 * 1000
},
standby: this._refreshStandby
});
if (settings) {
settings.changed.connect(this._onSettingsChange, this);
this._onSettingsChange(settings);
}
}
/**
* Branch list for the current repository.
*/
get branches(): Git.IBranch[] {
return this._branches;
}
/**
* The current repository branch.
*/
get currentBranch(): Git.IBranch {
return this._currentBranch;
}
/**
* Boolean indicating whether the model has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Boolean indicating whether the model is ready.
*/
get isReady(): boolean {
return this._pendingReadyPromise === 0;
}
/**
* Promise which fulfills when the model is ready.
*/
get ready(): Promise<void> {
return this._readyPromise;
}
/**
* Git repository path.
*
* ## Notes
*
* - This is the full path of the top-level folder.
* - The return value is `null` if a repository path is not defined.
*/
get pathRepository(): string | null {
return this._pathRepository;
}
set pathRepository(v: string | null) {
const change: IChangedArgs<string> = {
name: 'pathRepository',
newValue: null,
oldValue: this._pathRepository
};
if (v === null) {
this._pendingReadyPromise += 1;
this._readyPromise.then(() => {
this._pathRepository = null;
this._pendingReadyPromise -= 1;
if (change.newValue !== change.oldValue) {
this.refresh().then(() => this._repositoryChanged.emit(change));
}
});
} else {
const currentReady = this._readyPromise;
this._pendingReadyPromise += 1;
const currentFolder = v;
this._readyPromise = Promise.all([
currentReady,
this.showPrefix(currentFolder)
])
.then(([_, path]) => {
if (path !== null) {
// Remove relative path to get the Git repository root path
path = currentFolder.slice(
0,
Math.max(0, currentFolder.length - path.length)
);
}
change.newValue = this._pathRepository = path;
if (change.newValue !== change.oldValue) {
this.refresh().then(() => this._repositoryChanged.emit(change));
}
this._pendingReadyPromise -= 1;
})
.catch(reason => {
this._pendingReadyPromise -= 1;
console.error(
`Fail to find Git top level for path ${currentFolder}.\n${reason}`
);
});
}
}
/**
* Custom model refresh standby condition
*/
get refreshStandbyCondition(): () => boolean {
return this._standbyCondition;
}
set refreshStandbyCondition(v: () => boolean) {
this._standbyCondition = v;
}
/**
* Selected file for single file history
*/
get selectedHistoryFile(): Git.IStatusFile | null {
return this._selectedHistoryFile;
}
set selectedHistoryFile(file: Git.IStatusFile | null) {
if (this._selectedHistoryFile !== file) {
this._selectedHistoryFile = file;
this._selectedHistoryFileChanged.emit(file);
}
}
/**
* Git repository status
*/
get status(): Git.IStatus {
return this._status;
}
/**
* A signal emitted when the branches of the Git repository changes.
*/
get branchesChanged(): ISignal<IGitExtension, void> {
return this._branchesChanged;
}
/**
* A signal emitted when the `HEAD` of the Git repository changes.
*/
get headChanged(): ISignal<IGitExtension, void> {
return this._headChanged;
}
/**
* A signal emitted when the current marking of the Git repository changes.
*/
get markChanged(): ISignal<IGitExtension, void> {
return this._markChanged;
}
/**
* A signal emitted when the current file selected for history of the Git repository changes.
*/
get selectedHistoryFileChanged(): ISignal<
IGitExtension,
Git.IStatusFile | null
> {
return this._selectedHistoryFileChanged;
}
/**
* A signal emitted when the current Git repository changes.
*/
get repositoryChanged(): ISignal<IGitExtension, IChangedArgs<string | null>> {
return this._repositoryChanged;
}
/**
* A signal emitted when the current status of the Git repository changes.
*/
get statusChanged(): ISignal<IGitExtension, Git.IStatus> {
return this._statusChanged;
}
/**
* A signal emitted whenever a model event occurs.
*/
get taskChanged(): ISignal<IGitExtension, string> {
return this._taskHandler.taskChanged;
}
/**
* A signal emitted when the current Git repository changes.
*/
get notifyRemoteChanges(): ISignal<
IGitExtension,
Git.IRemoteChangedNotification
> {
return this._notifyRemoteChanges;
}
/**
* Boolean indicating whether there are dirty files
* A dirty file is a file with unsaved changes that is staged in classical mode
* or modified in simple mode.
*/
get hasDirtyFiles(): boolean {
return this._hasDirtyFiles;
}
set hasDirtyFiles(value: boolean) {
if (this._hasDirtyFiles !== value) {
this._hasDirtyFiles = value;
this._dirtyFilesStatusChanged.emit(value);
}
}
/**
* A signal emitted indicating whether there are dirty (e.g., unsaved) staged files.
* This signal is emitted when there is a dirty staged file but none previously,
* and vice versa, when there are no dirty staged files but there were some previously.
*/
get dirtyFilesStatusChanged(): ISignal<IGitExtension, boolean> {
return this._dirtyFilesStatusChanged;
}
/**
* Boolean indicating whether credentials are required from the user.
*/
get credentialsRequired(): boolean {
return this._credentialsRequired;
}
set credentialsRequired(value: boolean) {
if (this._credentialsRequired !== value) {
this._credentialsRequired = value;
this._credentialsRequiredChanged.emit(value);
}
}
/**
* A signal emitted whenever credentials are required, or are not required anymore.
*/
get credentialsRequiredChanged(): ISignal<IGitExtension, boolean> {
return this._credentialsRequiredChanged;
}
/**
* Get the current markers
*
* Note: This makes sure it always returns non null value
*/
protected get _currentMarker(): BranchMarker {
if (!this.__currentMarker) {
this._setMarker(
this.pathRepository,
this._currentBranch ? this._currentBranch.name : ''
);
}
return this.__currentMarker;
}
/**
* Add one or more files to the repository staging area.
*
* ## Notes
*
* - If no filename is provided, all files are added.
*
* @param filename - files to add
* @returns promise which resolves upon adding files to the repository staging area
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async add(...filename: string[]): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>('git:add:files', async () => {
await requestAPI<void>(URLExt.join(path, 'add'), 'POST', {
add_all: !filename,
filename: filename || ''
});
});
await this.refreshStatus();
}
/**
* Match files status information based on a provided file path.
*
* If the file is tracked and has no changes, a StatusFile of unmodified will be returned.
*
* @param path the file path relative to the server root
* @returns The file status or null if path repository is null or path not in repository
*/
getFile(path: string): Git.IStatusFile | null {
if (this.pathRepository === null) {
return null;
}
const fileStatus = this._status.files.find(status => {
return this.getRelativeFilePath(status.to) === path;
});
if (!fileStatus) {
const relativePath = PathExt.relative(
'/' + this.pathRepository,
'/' + path
);
if (relativePath.startsWith('../')) {
return null;
} else {
return {
x: '',
y: '',
to: relativePath,
from: '',
is_binary: null,
status: 'unmodified',
type: this._resolveFileType(path)
};
}
} else {
return fileStatus;
}
}
/**
* Add all "unstaged" files to the repository staging area.
*
* @returns promise which resolves upon adding files to the repository staging area
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async addAllUnstaged(): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>(
'git:add:files:all_unstaged',
async () => {
await requestAPI<void>(URLExt.join(path, 'add_all_unstaged'), 'POST');
}
);
await this.refreshStatus();
}
/**
* Add all untracked files to the repository staging area.
*
* @returns promise which resolves upon adding files to the repository staging area
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async addAllUntracked(): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>(
'git:add:files:all_untracked',
async () => {
await requestAPI<void>(URLExt.join(path, 'add_all_untracked'), 'POST');
}
);
await this.refreshStatus();
}
/**
* Add a remote Git repository to the current repository.
*
* @param url - remote repository URL
* @param name - remote name
* @returns promise which resolves upon adding a remote
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async addRemote(url: string, name?: string): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>('git:add:remote', async () => {
await requestAPI<void>(URLExt.join(path, 'remote', 'add'), 'POST', {
url,
name
});
});
}
/**
* Show remote repository for the current repository
* @returns promise which resolves to a list of remote repositories
*/
async getRemotes(): Promise<Git.IGitRemote[]> {
const path = await this._getPathRepository();
const result = await this._taskHandler.execute<Git.IGitRemoteResult>(
'git:show:remote',
async () => {
return await requestAPI<Git.IGitRemoteResult>(
URLExt.join(path, 'remote', 'show'),
'GET'
);
}
);
return result.remotes;
}
/**
* Remove a remote repository by name
* @param name name of remote to remove
*/
async removeRemote(name: string): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>('git:remove:remote', async () => {
await requestAPI<void>(URLExt.join(path, 'remote', name), 'DELETE');
});
}
/**
* Retrieve the repository commit log.
*
* ## Notes
*
* - This API can be used to implicitly check if the current folder is a Git repository.
*
* @param count - number of commits to retrieve
* @returns promise which resolves upon retrieving the repository commit log
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async allHistory(count = 25): Promise<Git.IAllHistory> {
const path = await this._getPathRepository();
return await this._taskHandler.execute<Git.IAllHistory>(
'git:fetch:history',
async () => {
return await requestAPI<Git.IAllHistory>(
URLExt.join(path, 'all_history'),
'POST',
{
history_count: count
}
);
}
);
}
/**
* Checkout a branch.
*
* ## Notes
*
* - If a branch name is provided, checkout the provided branch (with or without creating it)
* - If a filename is provided, checkout the file, discarding all changes.
* - If nothing is provided, checkout all files, discarding all changes.
*
* TODO: Refactor into separate endpoints for each kind of checkout request
*
* @param options - checkout options
* @returns promise which resolves upon performing a checkout
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async checkout(options?: Git.ICheckoutOptions): Promise<Git.ICheckoutResult> {
const path = await this._getPathRepository();
const body = {
checkout_branch: false,
new_check: false,
branchname: '',
startpoint: '',
checkout_all: true,
filename: ''
};
if (options !== undefined) {
if (options.branchname) {
body.branchname = options.branchname;
body.checkout_branch = true;
body.new_check = options.newBranch === true;
if (options.newBranch) {
body.startpoint = options.startpoint || this._currentBranch.name;
}
} else if (options.filename) {
body.filename = options.filename;
body.checkout_all = false;
}
}
const data = await this._taskHandler.execute<Git.ICheckoutResult>(
'git:checkout',
async () => {
let changes;
if (!body.new_check) {
if (body.checkout_branch && !body.new_check) {
changes = await this._changedFiles(
this._currentBranch.name,
body.branchname
);
} else if (body.filename) {
changes = { files: [body.filename] };
} else {
changes = await this._changedFiles('WORKING', 'HEAD');
}
}
const d = await requestAPI<Git.ICheckoutResult>(
URLExt.join(path, 'checkout'),
'POST',
body
);
changes?.files?.forEach(file => this._revertFile(file));
return d;
}
);
if (body.checkout_branch) {
await this.refreshBranch();
} else {
await this.refreshStatus();
}
return data;
}
/**
* Merge a branch into the current branch
*
* @param branch The branch to merge into the current branch
*/
async merge(branch: string): Promise<Git.IResultWithMessage> {
const path = await this._getPathRepository();
return this._taskHandler.execute<Git.IResultWithMessage>(
'git:merge',
() => {
return requestAPI<Git.IResultWithMessage>(
URLExt.join(path, 'merge'),
'POST',
{
branch
}
);
}
);
}
/**
* Clone a repository.
*
* @param path - local path into which the repository will be cloned
* @param url - Git repository URL
* @param auth - remote repository authentication information
* @param versioning - boolean flag of Git metadata (default true)
* @param submodules - boolean flag of Git submodules (default false)
* @returns promise which resolves upon cloning a repository
*
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async clone(
path: string,
url: string,
auth?: Git.IAuth,
versioning = true,
submodules = false
): Promise<Git.IResultWithMessage> {
return await this._taskHandler.execute<Git.IResultWithMessage>(
'git:clone',
async () => {
return await requestAPI<Git.IResultWithMessage>(
URLExt.join(path, 'clone'),
'POST',
{
clone_url: url,
versioning: versioning,
submodules: submodules,
auth: auth as any
}
);
}
);
}
/**
* Commit all staged file changes. If message is None, then the commit is amended
*
* @param message - commit message
* @param amend - whether this is an amend commit
* @returns promise which resolves upon committing file changes
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async commit(message?: string, amend = false): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute('git:commit:create', async () => {
await requestAPI(URLExt.join(path, 'commit'), 'POST', {
commit_msg: message,
amend: amend
});
});
await this.refresh();
}
/**
* Get (or set) Git configuration options.
*
* @param options - configuration options to set
* @returns promise which resolves upon either getting or setting configuration options
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async config(options?: JSONObject): Promise<JSONObject | void> {
const path = await this._getPathRepository();
return await this._taskHandler.execute<JSONObject | void>(
'git:config:' + (options ? 'set' : 'get'),
async () => {
if (options) {
await requestAPI(URLExt.join(path, 'config'), 'POST', {
options
});
} else {
return await requestAPI<JSONObject>(
URLExt.join(path, 'config'),
'POST'
);
}
}
);
}
/**
* Delete a branch
*
* @param branchName Branch name
* @returns promise which resolves when the branch has been deleted.
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async deleteBranch(branchName: string): Promise<void> {
const path = await this._getPathRepository();
await this._taskHandler.execute<void>('git:branch:delete', async () => {
return await requestAPI<void>(
URLExt.join(path, 'branch', 'delete'),
'POST',
{
branch: branchName
}
);
});
}
/**
* Fetch commit information.
*
* @param hash - commit hash
* @returns promise which resolves upon retrieving commit information
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async detailedLog(hash: string): Promise<Git.ISingleCommitFilePathInfo> {
const path = await this._getPathRepository();
const data = await this._taskHandler.execute<Git.ISingleCommitFilePathInfo>(
'git:fetch:commit_log',
async () => {
return await requestAPI<Git.ISingleCommitFilePathInfo>(
URLExt.join(path, 'detailed_log'),
'POST',
{
selected_hash: hash
}
);
}
);
data.modified_files = data.modified_files.map(f => {
f.type = this._resolveFileType(f.modified_file_path);
return f;
});
return data;
}
/**
* Get the diff of two commits.
* If no commit is provided, the diff of HEAD and INDEX is returned.
* If the current commit (the commit to compare) is not provided,
* the diff of the previous commit and INDEX is returned.
*
* @param previous - the commit to compare against
* @param current - the commit to compare
* @returns promise which resolves upon retrieving the diff
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async diff(previous?: string, current?: string): Promise<Git.IDiffResult> {
const path = await this._getPathRepository();
const data = await this._taskHandler.execute<Git.IDiffResult>(
'git:diff',
async () => {
return await requestAPI<Git.IDiffResult>(
URLExt.join(path, 'diff'),
'POST',
{
previous,
current
}
);
}
);
data.result = data.result.map(f => {
f.filetype = this._resolveFileType(f.filename);
return f;
});
return data;
}
/**
* Dispose of model resources.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
this._fetchPoll.dispose();
this._statusPoll.dispose();
this._taskHandler.dispose();
this._settings.changed.disconnect(this._onSettingsChange, this);
Signal.clearData(this);
}
/**
* Ensure a .gitignore file exists
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async ensureGitignore(): Promise<void> {
const path = await this._getPathRepository();
await requestAPI(URLExt.join(path, 'ignore'), 'POST', {});
this._openGitignore();
await this.refreshStatus();
}
/**
* Fetch to get ahead/behind status
*
* @param auth - remote authentication information
* @returns promise which resolves upon fetching
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async fetch(auth?: Git.IAuth): Promise<Git.IResultWithMessage> {
const path = await this._getPathRepository();
const data = this._taskHandler.execute<Git.IResultWithMessage>(
'git:fetch:remote',
async () => {
return await requestAPI<Git.IResultWithMessage>(
URLExt.join(path, 'remote', 'fetch'),
'POST',
{
auth: auth as any
}
);
}
);
return data;
}
/**
* Return the path of a file relative to the Jupyter server root.
*
* ## Notes
*
* - If no path is provided, returns the Git repository top folder relative path.
* - If no Git repository selected, returns `null`
*
* @param path - file path relative to the top folder of the Git repository
* @returns relative path
*/
getRelativeFilePath(path?: string): string | null {
if (this.pathRepository === null) {
return null;
}
return PathExt.join(this.pathRepository, path ?? '');
}
/**
* Add an entry in .gitignore file
*
* @param filePath File to ignore
* @param useExtension Whether to ignore the file or its extension
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async ignore(filePath: string, useExtension: boolean): Promise<void> {
const path = await this._getPathRepository();
await requestAPI(URLExt.join(path, 'ignore'), 'POST', {
file_path: filePath,
use_extension: useExtension
});
this._openGitignore();
await this.refreshStatus();
}
/**
* Initialize a new Git repository at a specified path.
*
* @param path - path at which initialize a Git repository
* @returns promise which resolves upon initializing a Git repository
*
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async init(path: string): Promise<void> {
await this._taskHandler.execute<void>('git:init', async () => {
await requestAPI(URLExt.join(path, 'init'), 'POST');
});
}
/**
* Retrieve commit logs.
*
* @param count - number of commits
* @returns promise which resolves upon retrieving commit logs
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async log(count = 25): Promise<Git.ILogResult> {
const path = await this._getPathRepository();
return await this._taskHandler.execute<Git.ILogResult>(
'git:fetch:log',
async () => {
try {
return await requestAPI<Git.ILogResult>(
URLExt.join(path, 'log'),
'POST',
{
history_count: count,
follow_path: this.selectedHistoryFile?.to
}
);
} catch (error) {
return { code: 1 };
}
}
);
}
/**
* Fetch changes from a remote repository.
*
* @param auth - remote authentication information
* @returns promise which resolves upon fetching changes
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async pull(auth?: Git.IAuth): Promise<Git.IResultWithMessage> {
const path = await this._getPathRepository();
const previousHead = this._currentBranch?.top_commit;
const data = await this._taskHandler.execute<Git.IResultWithMessage>(
'git:pull',
async () => {
return await requestAPI<Git.IResultWithMessage>(
URLExt.join(path, 'pull'),
'POST',
{
auth: auth as any,
cancel_on_conflict:
(this._settings?.composite[
'cancelPullMergeConflict'
] as boolean) || false
}
);
}
);
const changes = await this._changedFiles(previousHead, 'HEAD');
changes?.files?.forEach(file => this._revertFile(file));
await this.refreshBranch(); // Will emit headChanged if required
return data;
}
/**
* Push local changes to a remote repository.
*
* @param auth - remote authentication information
* @param force - whether or not to force the push
* @returns promise which resolves upon pushing changes
*
* @throws {Git.NotInRepository} If the current path is not a Git repository
* @throws {Git.GitResponseError} If the server response is not ok
* @throws {ServerConnection.NetworkError} If the request cannot be made
*/
async push(
auth?: Git.IAuth,
force = false,
remote?: string
): Promise<Git.IResultWithMessage> {
const path = await this._getPathRepository();
const data = this._taskHandler.execute<Git.IResultWithMessage>(
'git:push',
async () => {
return await requestAPI<Git.IResultWithMessage>(
URLExt.join(path, 'push'),
'POST',
{
auth: auth as any,
force: force,
remote
}