-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathGitCli.ts
More file actions
1057 lines (912 loc) · 32.9 KB
/
GitCli.ts
File metadata and controls
1057 lines (912 loc) · 32.9 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
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
/* eslint max-lines:0 */
/*
This module is used to communicate with Git through Cli
Output string from Git should always be parsed here
to provide more sensible outputs than just plain strings.
Format of the output should be specified in Git.js
*/
import * as Promise from "bluebird";
import * as Cli from "../Cli";
import * as ErrorHandler from "../ErrorHandler";
import * as Events from "../Events";
import EventEmitter from "../EventEmitter";
import ExpectedError from "../ExpectedError";
import * as Preferences from "../Preferences";
import { consoleDebug, defer, getProjectRoot, loadPathContent } from "../Utils";
import { _, FileSystem, FileUtils } from "../brackets-modules";
let _gitPath = null;
const _gitQueue = [];
let _gitQueueBusy = false;
export const FILE_STATUS = {
STAGED: "STAGED",
UNMODIFIED: "UNMODIFIED",
IGNORED: "IGNORED",
UNTRACKED: "UNTRACKED",
MODIFIED: "MODIFIED",
ADDED: "ADDED",
DELETED: "DELETED",
RENAMED: "RENAMED",
COPIED: "COPIED",
UNMERGED: "UNMERGED"
};
// This SHA1 represents the empty tree. You get it using `git mktree < /dev/null`
const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
function getGitPath() {
if (_gitPath) { return _gitPath; }
_gitPath = Preferences.get("gitPath");
return _gitPath;
}
export function setGitPath(path) {
const _path = path === true ? "git" : path;
Preferences.set("gitPath", _path);
_gitPath = _path;
}
function strEndsWith(subjectString, searchString, position?) {
let _position = position;
if (_position == null || _position > subjectString.length) {
_position = subjectString.length;
}
_position -= searchString.length;
const lastIndex = subjectString.indexOf(searchString, _position);
return lastIndex !== -1 && lastIndex === _position;
}
/*
function fixCygwinPath(path) {
if (typeof path === "string" && brackets.platform === "win" && path.indexOf("/cygdrive/") === 0) {
path = path.substring("/cygdrive/".length)
.replace(/^([a-z]+)\//, function (a, b) {
return b.toUpperCase() + ":/";
});
}
return path;
}
*/
function _processQueue() {
// do nothing if the queue is busy
if (_gitQueueBusy) {
return;
}
// do nothing if the queue is empty
if (_gitQueue.length === 0) {
_gitQueueBusy = false;
return;
}
// get item from queue
const item = _gitQueue.shift();
const deferObj = item[0];
const args = item[1];
const opts = item[2];
// execute git command in a queue so no two commands are running at the same time
if (opts.nonblocking !== true) { _gitQueueBusy = true; }
Cli.spawnCommand(getGitPath(), args, opts)
.progressed((...progressedArgs) => deferObj.progress(...progressedArgs))
.then((r) => deferObj.resolve(r))
.catch((e) => {
const call = "call: git " + args.join(" ");
e.stack = [call, e.stack].join("\n");
deferObj.reject(e);
})
.finally(() => {
if (opts.nonblocking !== true) { _gitQueueBusy = false; }
_processQueue();
});
}
export function git(args: string[] = [], opts: Cli.CliOptions = {}): Promise<string> {
const rv = defer();
_gitQueue.push([rv, args, opts]);
_processQueue();
return rv.promise as Promise<string>;
}
/*
git branch
-d --delete Delete a branch.
-D Delete a branch irrespective of its merged status.
--no-color Turn off branch colors
-r --remotes List or delete (if used with -d) the remote-tracking branches.
-a --all List both remote-tracking branches and local branches.
--track When creating a new branch, set up branch.<name>.remote and branch.<name>.merge
--set-upstream If specified branch does not exist yet or if --force has been given, acts exactly like --track
*/
export function setUpstreamBranch(remoteName, remoteBranch) {
if (!remoteName) { throw new TypeError("remoteName argument is missing!"); }
if (!remoteBranch) { throw new TypeError("remoteBranch argument is missing!"); }
return git(["branch", "--no-color", "-u", remoteName + "/" + remoteBranch]);
}
export function branchDelete(branchName) {
return git(["branch", "--no-color", "-d", branchName]);
}
export function forceBranchDelete(branchName) {
return git(["branch", "--no-color", "-D", branchName]);
}
export function getBranches(moreArgs = []) {
const args = ["branch", "--no-color"].concat(moreArgs);
return git(args).then((stdout) => {
if (!stdout) { return []; }
return stdout.split("\n").reduce((arr, l) => {
let name = l.trim();
let currentBranch = false;
let remote = null;
let sortPrefix = "";
if (name.indexOf("->") !== -1) {
return arr;
}
if (name.indexOf("* ") === 0) {
name = name.substring(2);
currentBranch = true;
}
if (name.indexOf("remotes/") === 0) {
name = name.substring("remotes/".length);
remote = name.substring(0, name.indexOf("/"));
}
let sortName = name.toLowerCase();
if (remote) {
sortName = sortName.substring(remote.length + 1);
}
if (sortName.indexOf("#") !== -1) {
sortPrefix = sortName.slice(0, sortName.indexOf("#"));
}
arr.push({
name,
sortPrefix,
sortName,
currentBranch,
remote
});
return arr;
}, []);
});
}
export function getAllBranches() {
return getBranches(["-a"]);
}
/*
git fetch
--all Fetch all remotes.
--dry-run Show what would be done, without making any changes.
--multiple Allow several <repository> and <group> arguments to be specified. No <refspec>s may be specified.
--prune After fetching, remove any remote-tracking references that no longer exist on the remote.
--progress This flag forces progress status even if the standard error stream is not directed to a terminal.
*/
function repositoryNotFoundHandler(err) {
const m = ErrorHandler.matches(err, /Repository (.*) not found$/gim);
if (m) {
throw new ExpectedError(m[0]);
}
throw err;
}
export function fetchRemote(remote) {
return git(["fetch", "--progress", remote], {
timeout: false // never timeout this
}).catch(repositoryNotFoundHandler);
}
export function fetchAllRemotes() {
return git(["fetch", "--progress", "--all"], {
timeout: false // never timeout this
}).catch(repositoryNotFoundHandler);
}
/*
git remote
add Adds a remote named <name> for the repository at <url>.
rename Rename the remote named <old> to <new>.
remove Remove the remote named <name>.
show Gives some information about the remote <name>.
prune Deletes all stale remote-tracking branches under <name>.
*/
export function getRemotes() {
return git(["remote", "-v"])
.then((stdout) => {
return !stdout ? [] : _.uniq(stdout.replace(/\((push|fetch)\)/g, "").split("\n")).map((l) => {
const s = l.trim().split("\t");
return {
name: s[0],
url: s[1]
};
});
});
}
export function createRemote(name, url) {
return git(["remote", "add", name, url])
.then(() => {
// stdout is empty so just return success
return true;
});
}
export function deleteRemote(name) {
return git(["remote", "rm", name])
.then(() => {
// stdout is empty so just return success
return true;
});
}
/*
git pull
--no-commit Do not commit result after merge
--ff-only Refuse to merge and exit with a non-zero status
unless the current HEAD is already up-to-date
or the merge can be resolved as a fast-forward.
*/
export function mergeRemote(remote, branch, ffOnly = false, noCommit = false) {
const args = ["merge"];
if (ffOnly) { args.push("--ff-only"); }
if (noCommit) { args.push("--no-commit", "--no-ff"); }
args.push(remote + "/" + branch);
const readMergeMessage = () => loadPathContent(Preferences.get("currentGitRoot") + "/.git/MERGE_MSG");
return git(args)
.then((stdout) => {
// return stdout if available - usually not
if (stdout) { return stdout; }
return readMergeMessage().then((msg) => {
if (msg) { return msg; }
return "Remote branch " + branch + " from " + remote + " was merged to current branch";
});
})
.catch((error) => {
return readMergeMessage().then((msg) => {
if (msg) { return msg; }
throw error;
});
});
}
export function rebaseRemote(remote, branch) {
return git(["rebase", remote + "/" + branch]);
}
export function resetRemote(remote, branch) {
return git(["reset", "--soft", remote + "/" + branch]).then((stdout) => {
return stdout || "Current branch was resetted to branch " + branch + " from " + remote;
});
}
export function mergeBranch(branchName, mergeMessage, useNoff) {
const args = ["merge"];
if (useNoff) { args.push("--no-ff"); }
if (mergeMessage && mergeMessage.trim()) { args.push("-m", mergeMessage); }
args.push(branchName);
return git(args);
}
/*
git push
--porcelain Produce machine-readable output.
--delete All listed refs are deleted from the remote repository.
This is the same as prefixing all refs with a colon.
--force Usually, the command refuses to update a remote ref that
is not an ancestor of the local ref used to overwrite it.
--set-upstream For every branch that is up to date or successfully pushed, add upstream (tracking) reference
--progress This flag forces progress status even if the standard error stream is not directed to a terminal.
*/
/*
returns parsed push response in this format:
{
flag: "="
flagDescription: "Ref was up to date and did not need pushing"
from: "refs/heads/rewrite-remotes"
remoteUrl: "http://github.com/zaggino/brackets-git.git"
status: "Done"
summary: "[up to date]"
to: "refs/heads/rewrite-remotes"
}
*/
export function push(remoteName, remoteBranch, additionalArgs) {
if (!remoteName) { throw new TypeError("remoteName argument is missing!"); }
let args = ["push", "--porcelain", "--progress"];
if (Array.isArray(additionalArgs)) {
args = args.concat(additionalArgs);
}
args.push(remoteName);
if (remoteBranch && Preferences.get("gerritPushref")) {
return getConfig("gerrit.pushref").then((strGerritEnabled) => {
if (strGerritEnabled === "true") {
args.push("HEAD:refs/for/" + remoteBranch);
} else {
args.push(remoteBranch);
}
return doPushWithArgs(args);
});
}
if (remoteBranch) {
args.push(remoteBranch);
}
return doPushWithArgs(args);
}
export interface PushResult {
flag: string;
flagDescription?: string;
from: string;
to: string;
summary: string;
status: string;
remoteUrl: string;
}
function doPushWithArgs(args): Promise<PushResult> {
return git(args)
.catch(repositoryNotFoundHandler)
.then((stdout) => {
if (!stdout) {
return null;
}
// this should clear lines from push hooks
const lines = stdout.split("\n");
while (lines.length > 0 && lines[0].match(/^To/) === null) {
lines.shift();
}
const lineTwo = lines[1].split("\t");
const retObj: PushResult = {
remoteUrl: lines[0].trim().split(" ")[1],
flag: lineTwo[0],
from: lineTwo[1].split(":")[0],
to: lineTwo[1].split(":")[1],
summary: lineTwo[2],
status: lines[2]
};
switch (retObj.flag) {
case " ":
retObj.flagDescription = "Successfully pushed fast-forward";
break;
case "+":
retObj.flagDescription = "Successful forced update";
break;
case "-":
retObj.flagDescription = "Successfully deleted ref";
break;
case "*":
retObj.flagDescription = "Successfully pushed new ref";
break;
case "!":
retObj.flagDescription = "Ref was rejected or failed to push";
break;
case "=":
retObj.flagDescription = "Ref was up to date and did not need pushing";
break;
default:
retObj.flagDescription = "Unknown push flag received: " + retObj.flag;
}
return retObj;
});
}
export function getCurrentBranchName() {
return git(["branch", "--no-color"]).then((branchOut) => {
let branchName = _.find(branchOut.split("\n"), (l) => l[0] === "*");
if (branchName) {
branchName = branchName.substring(1).trim();
const m = branchName.match(/^\(.*\s(\S+)\)$/); // like (detached from f74acd4)
if (m) { return m[1]; }
return branchName;
}
// no branch situation so we need to create one by doing a commit
if (branchOut.match(/^\s*$/)) {
EventEmitter.emit(Events.GIT_NO_BRANCH_EXISTS);
// master is the default name of the branch after git init
return "master";
}
// alternative
return git(["log", "--pretty=format:%H %d", "-1"]).then((logOut) => {
const logMatch = logOut.trim().match(/^(\S+)\s+\((.*)\)$/);
let hash = logMatch[1].substring(0, 20);
logMatch[2].split(",").forEach((_info) => {
const info = _info.trim();
if (info === "HEAD") { return; }
const tagMatch = info.match(/^tag:(.+)$/);
if (tagMatch) {
hash = tagMatch[1].trim();
return;
}
hash = info;
});
return hash;
});
});
}
export function getCurrentUpstreamBranch(): Promise<string | null> {
return git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).catch(() => null);
}
// Get list of deleted files between two branches
export function getDeletedFiles(oldBranch, newBranch) {
return git(["diff", "--no-ext-diff", "--name-status", oldBranch + ".." + newBranch])
.then((stdout) => {
return stdout.split("\n").reduce((arr, row) => {
if (/^D/.test(row)) {
arr.push(row.substring(1).trim());
}
return arr;
}, []);
});
}
export function getConfig(key) {
return git(["config", key.replace(/\s/g, "")]);
}
export function setConfig(key, value, allowGlobal = false) {
const _key = key.replace(/\s/g, "");
return git(["config", _key, value]).catch((err) => {
if (allowGlobal && ErrorHandler.contains(err, "No such file or directory")) {
return git(["config", "--global", _key, value]);
}
throw err;
});
}
export interface CommitInfo {
hashShort: string;
hash: string;
author: string;
date: string;
email: string;
subject: string;
body: string;
tags?: string[];
}
export function getHistory(branch, skipCommits: number = 0, file = null): Promise<CommitInfo[]> {
const separator = "_._";
const newline = "_.nw._";
const format = [
"%h", // abbreviated commit hash
"%H", // commit hash
"%an", // author name
"%ai", // author date, ISO 8601 format
"%ae", // author email
"%s", // subject
"%b", // body
"%d" // tags
].join(separator) + newline;
const args = ["log", "-100"];
if (skipCommits) { args.push("--skip=" + skipCommits); }
args.push("--format=" + format, branch, "--");
// follow is too buggy - do not use
// if (file) { args.push("--follow"); }
if (file) { args.push(file); }
return git(args).then((_stdout) => {
const stdout = _stdout.substring(0, _stdout.length - newline.length);
return !stdout ? [] : stdout.split(newline).map((line) => {
const data = line.trim().split(separator);
const commitInfo: CommitInfo = {
hashShort: data[0],
hash: data[1],
author: data[2],
date: data[3],
email: data[4],
subject: data[5],
body: data[6]
};
if (data[7]) {
const tags = data[7].match(/tag: ([^,|)]+)/g);
for (const key in tags) {
if (tags[key] && tags[key].replace) {
tags[key] = tags[key].replace("tag:", "");
}
}
commitInfo.tags = tags;
}
return commitInfo;
});
});
}
export function init() {
return git(["init"]);
}
export function clone(remoteGitUrl, destinationFolder) {
return git(["clone", remoteGitUrl, destinationFolder, "--progress"], {
timeout: false // never timeout this
});
}
export function stage(fileOrFiles, updateIndex = false) {
const args = ["add"];
if (updateIndex) { args.push("-u"); }
return git(args.concat("--", fileOrFiles));
}
export function stageAll() {
return git(["add", "--all"]);
}
export function commit(message, amend) {
const lines = message.split("\n");
const args = ["commit"];
if (amend) {
args.push("--amend", "--reset-author");
}
if (lines.length === 1) {
args.push("-m", message);
return git(args);
}
return new Promise((resolve, reject) => {
// FUTURE: maybe use git commit --file=-
const fileEntry = FileSystem.getFileForPath(Preferences.get("currentGitRoot") + ".bracketsGitTemp");
Promise.cast(FileUtils.writeText(fileEntry, message))
.then(() => {
args.push("-F", ".bracketsGitTemp");
return git(args);
})
.then((res) => fileEntry.unlink(() => resolve(res)))
.catch((err) => fileEntry.unlink(() => reject(err)));
});
}
export function reset(type = "--mixed", hash = null) {
const args = ["reset", type]; // mixed is the default action
if (hash) { args.push(hash, "--"); }
return git(args);
}
export function unstage(file) {
return git(["reset", "--", file]);
}
export function checkout(hash) {
return git(["checkout", hash], {
timeout: false // never timeout this
});
}
export function createBranch(branchName, originBranch, trackOrigin) {
const args = ["checkout", "-b", branchName];
if (originBranch) {
if (trackOrigin) {
args.push("--track");
}
args.push(originBranch);
}
return git(args);
}
function _isquoted(str) {
return str[0] === "\"" && str[str.length - 1] === "\"";
}
function _unquote(str) {
return str.substring(1, str.length - 1);
}
function _isescaped(str) {
return /\\[0-9]{3}/.test(str);
}
export function status(type = null) {
return git(["status", "-u", "--porcelain"]).then((stdout) => {
if (!stdout) { return []; }
const currentSubFolder = Preferences.get("currentGitSubfolder");
// files that are modified both in index and working tree should be resetted
let isEscaped = false;
const needReset = [];
const results = [];
const lines = stdout.split("\n");
lines.forEach((line) => {
const statusStaged = line.substring(0, 1);
const statusUnstaged = line.substring(1, 2);
const statusArr = [];
let file = line.substring(3);
let display = file;
const io = file.indexOf("->");
if (io !== -1) {
file = file.substring(io + 2).trim();
}
// check if the file is quoted
if (_isquoted(file)) {
file = _unquote(file);
if (io === -1) {
display = file;
}
if (_isescaped(file)) {
isEscaped = true;
}
}
if (statusStaged !== " " && statusUnstaged !== " " &&
statusStaged !== "?" && statusUnstaged !== "?") {
needReset.push(file);
return;
}
let statusChar;
if (statusStaged !== " " && statusStaged !== "?") {
statusArr.push(FILE_STATUS.STAGED);
statusChar = statusStaged;
} else {
statusChar = statusUnstaged;
}
switch (statusChar) {
case " ":
statusArr.push(FILE_STATUS.UNMODIFIED);
break;
case "!":
statusArr.push(FILE_STATUS.IGNORED);
break;
case "?":
statusArr.push(FILE_STATUS.UNTRACKED);
break;
case "M":
statusArr.push(FILE_STATUS.MODIFIED);
break;
case "A":
statusArr.push(FILE_STATUS.ADDED);
break;
case "D":
statusArr.push(FILE_STATUS.DELETED);
break;
case "R":
statusArr.push(FILE_STATUS.RENAMED);
break;
case "C":
statusArr.push(FILE_STATUS.COPIED);
break;
case "U":
statusArr.push(FILE_STATUS.UNMERGED);
break;
default:
throw new Error("Unexpected status: " + statusChar);
}
// we don't want to display paths that lead to this file outside the project
if (currentSubFolder && display.indexOf(currentSubFolder) === 0) {
display = display.substring(currentSubFolder.length);
}
results.push({
status: statusArr,
display,
file,
name: file.substring(file.lastIndexOf("/") + 1)
});
});
if (isEscaped) {
return setConfig("core.quotepath", "false").then(() => {
if (type === "SET_QUOTEPATH") {
throw new Error("git status is calling itself in a recursive loop!");
}
return status("SET_QUOTEPATH");
});
}
if (needReset.length > 0) {
return Promise.all(needReset.map((_fileName) => {
let fileName = _fileName;
if (fileName.indexOf("->") !== -1) {
fileName = fileName.split("->")[1].trim();
}
return unstage(fileName);
})).then(() => {
if (type === "RECURSIVE_CALL") {
throw new Error("git status is calling itself in a recursive loop!");
}
return status("RECURSIVE_CALL");
});
}
return results.sort((a, b) => {
if (a.file < b.file) {
return -1;
}
if (a.file > b.file) {
return 1;
}
return 0;
});
}).then((results) => {
EventEmitter.emit(Events.GIT_STATUS_RESULTS, results);
return results;
});
}
function _isFileStaged(file) {
return git(["status", "-u", "--porcelain", "--", file]).then((stdout) => {
if (!stdout) { return false; }
return _.any(stdout.split("\n"), (line) => {
// first character marks staged status
return line[0] !== " " && line[0] !== "?" &&
// in case another file appeared here?
line.lastIndexOf(" " + file) === line.length - file.length - 1;
});
});
}
export function getDiffOfStagedFiles() {
return git(["diff", "--no-ext-diff", "--no-color", "--staged"], {
timeout: false // never timeout this
});
}
export function getDiffOfAllIndexFiles(files) {
let args = ["diff", "--no-ext-diff", "--no-color", "--full-index"];
if (files) {
args = args.concat("--", files);
}
return git(args, {
timeout: false // never timeout this
});
}
export function getListOfStagedFiles() {
return git(["diff", "--no-ext-diff", "--no-color", "--staged", "--name-only"], {
timeout: false // never timeout this
});
}
export function diffFile(file) {
return _isFileStaged(file).then((staged) => {
const args = ["diff", "--no-ext-diff", "--no-color"];
if (staged) { args.push("--staged"); }
args.push("-U0", "--", file);
return git(args, {
timeout: false // never timeout this
});
});
}
export function diffFileNice(file) {
return _isFileStaged(file).then((staged) => {
const args = ["diff", "--no-ext-diff", "--no-color"];
if (staged) { args.push("--staged"); }
args.push("--", file);
return git(args, {
timeout: false // never timeout this
});
});
}
export function difftool(file) {
return _isFileStaged(file).then((staged) => {
const args = ["difftool"];
if (staged) {
args.push("--staged");
}
args.push("--", file);
return git(args, {
timeout: false, // never timeout this
nonblocking: true // allow running other commands before this command finishes its work
});
});
}
export function clean() {
return git(["clean", "-f", "-d"]);
}
export function getFilesFromCommit(hash, isInitial) {
let args = ["diff", "--no-ext-diff", "--name-only"];
args = args.concat((isInitial ? EMPTY_TREE : hash + "^") + ".." + hash);
args = args.concat("--");
return git(args).then((stdout) => !stdout ? [] : stdout.split("\n"));
}
export function getDiffOfFileFromCommit(hash, file, isInitial) {
let args = ["diff", "--no-ext-diff", "--no-color"];
args = args.concat((isInitial ? EMPTY_TREE : hash + "^") + ".." + hash);
args = args.concat("--", file);
return git(args);
}
export function difftoolFromHash(hash, file, isInitial) {
return git(["difftool", (isInitial ? EMPTY_TREE : hash + "^") + ".." + hash, "--", file], {
timeout: false // never timeout this
});
}
export function rebaseInit(branchName) {
return git(["rebase", "--ignore-date", branchName]);
}
export function rebase(whatToDo) {
return git(["rebase", "--" + whatToDo]);
}
export function getVersion() {
return git(["--version"]).then((stdout) => {
const m = stdout.match(/[0-9].*/);
return m ? m[0] : stdout.trim();
});
}
function getCommitCountsFallback() {
return git(["rev-list", "HEAD", "--not", "--remotes"])
.then((stdout) => {
const ahead = stdout ? stdout.split("\n").length : 0;
return "-1 " + ahead;
})
.catch((err) => {
ErrorHandler.logError(err);
return "-1 -1";
});
}
export function getCommitCounts() {
const remotes = Preferences.get("defaultRemotes") || {};
const remote = remotes[Preferences.get("currentGitRoot")];
return getCurrentBranchName().then((branch) => {
let p;
if (!branch || !remote) {
p = getCommitCountsFallback();
} else {
p = git(["rev-list", "--left-right", "--count", remote + "/" + branch + "...@{0}", "--"])
.catch((err) => {
ErrorHandler.logError(err);
return getCommitCountsFallback();
});
}
return p.then((stdout) => {
const matches = /(-?\d+)\s+(-?\d+)/.exec(stdout);
return matches ? {
behind: parseInt(matches[1], 10),
ahead: parseInt(matches[2], 10)
} : {
behind: -1,
ahead: -1
};
});
});
}
export function getLastCommitMessage() {
return git(["log", "-1", "--pretty=%B"]).then((stdout) => stdout.trim());
}
export interface BlameInfo {
hash: string;
num: string;
content: string;
}
export function getBlame(file, from?, to?): Promise<BlameInfo[]> {
const args = ["blame", "-w", "--line-porcelain"];
if (from || to) { args.push("-L" + from + "," + to); }
args.push(file);
return git(args).then((_stdout) => {
if (!_stdout) { return []; }
const sep = "-@-BREAK-HERE-@-";
const sep2 = "$$#-#$BREAK$$-$#";
const stdout = _stdout.replace(sep, sep2).replace(/^\t(.*)$/gm, (a, b) => b + sep);
return stdout.split(sep).reduce((arr, _lineInfo) => {
const lineInfo = _lineInfo.replace(sep2, sep).replace(/^\s+/, "");
if (!lineInfo) { return arr; }
const lines = lineInfo.split("\n");
const firstLine = _.first(lines).split(" ");
const obj: BlameInfo = {
hash: firstLine[0],
num: firstLine[2],
content: _.last(lines)
};
// process all but first and last lines
const l = lines.length - 1;
for (let i = 1; i < l; i++) {
const line = lines[i];
const io = line.indexOf(" ");
const key = line.substring(0, io);
const val = line.substring(io + 1);
obj[key] = val;
}
arr.push(obj);
return arr;
}, []);
}).catch((stderr) => {
const m = stderr.match(/no such path (\S+)/);
if (m) {
throw new Error("File is not tracked by Git: " + m[1]);
}
throw stderr;
});
}
export function getGitRoot() {
const projectRoot = getProjectRoot();
return git(["rev-parse", "--show-toplevel"], {
cwd: projectRoot
})
.catch((e) => {
if (ErrorHandler.contains(e, "Not a git repository")) {
return null;
}
throw e;
})
.then((root) => {
if (root === null) {
return root;
}
// paths on cygwin look a bit different
// root = fixCygwinPath(root);
// we know projectRoot is in a Git repo now
// because --show-toplevel didn't return Not a git repository