-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathUtils.cls
3200 lines (2867 loc) · 117 KB
/
Utils.cls
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
Include (%occStatus, %occErrors, SourceControl.Git, %sySecurity)
Class SourceControl.Git.Utils [ Abstract, ProcedureBlock ]
{
Parameter Storage = "^SYS(""SourceControl"",""Git"")";
Parameter InstallNamespace = "%SYS";
Parameter Slash = {$case($system.Version.GetOS(),"Windows":"\",:"/")};
/// Name of the file with version controlled items
Parameter GitMenuItems = ",Settings,Commit,Sync,Pull,Fetch,Push,Revert,";
Parameter ImportAfterGitMenuItems = ",Commit,Sync,Pull,Fetch,Push,";
Parameter GitContextMenuItems = ",%Diff,%Blame,";
ClassMethod %SYSNamespaceStorage() As %String [ CodeMode = expression ]
{
$Replace(..#Storage,"^SYS","^%SYS")
}
/// Returns root temp folder
ClassMethod DefaultTemp() As %String
{
set defaultTemp = ##class(%File).Construct($System.Util.ManagerDirectory(),"repo/")
try {
set defaultTemp = $Get(@..%SYSNamespaceStorage()@("%defaultTemp"), defaultTemp)
} catch e {
// no-op
}
quit defaultTemp
}
ClassMethod MakeError(msg As %String) As %Status [ CodeMode = expression, Private ]
{
$$$ERROR(8012,"Git",msg)
}
ClassMethod TempFolder() As %String
{
set context = ##class(SourceControl.Git.PackageManagerContext).%Get()
if context.IsInGitEnabledPackage {
quit context.Package.Root
}
quit ..DefaultTempFolder()
}
ClassMethod DefaultTempFolder() As %String
{
quit $get(@..#Storage@("settings","namespaceTemp"),..DefaultTemp()_..#Slash_$translate($znspace,"%")_..#Slash)
}
ClassMethod MappingsNode() As %String [ CodeMode = expression ]
{
$Name(@..#Storage@("settings","mappings"))
}
ClassMethod PullEventClass() As %String [ CodeMode = expression ]
{
$Get(@..#Storage@("settings","pullEventClass"), ##class(SourceControl.Git.PullEventHandler.Default).%ClassName(1))
}
ClassMethod PercentClassReplace() As %Status [ CodeMode = expression ]
{
$Get(@..#Storage@("settings","percentClassReplace"), "")
}
ClassMethod SettingsUIReadOnly() As %Status [ CodeMode = expression ]
{
$Get(@..#Storage@("settings","settingsUIReadOnly"), 0)
}
ClassMethod DecomposeProductions() As %Boolean [ CodeMode = expression ]
{
$Get(@..#Storage@("settings","decomposeProductions"), 0)
}
ClassMethod DecomposeProdAllowIDE() As %Boolean [ CodeMode = expression ]
{
$Get(@..#Storage@("settings","decomposeProdAllowIDE"), 1)
}
ClassMethod FavoriteNamespaces() As %String
{
set favNamespaces = []
do ##class(%zpkg.isc.sc.git.Favorites).GetFavoriteNamespaces(.favNamespaces,[])
return favNamespaces
}
/// Returns the current (or previous) value of the flag.
ClassMethod Locked(newFlagValue As %Boolean) As %Boolean
{
set result = $get(@..#Storage@("settings","locked"),0)
if $data(newFlagValue)#2 {
set @..#Storage@("settings","locked") = ''newFlagValue
}
quit result
}
ClassMethod GitBinExists(ByRef version) As %Boolean
{
// Intentionally leak this as an optimization.
if $data(^||GitVersion,version)#2 && (version '= "") {
quit 1
}
try {
do ..RunGitCommand("--version",.err,.out)
set version = out.ReadLine()
} catch e {
set version = ""
}
set ^||GitVersion = version
quit (version '= "")
}
ClassMethod GitBinPath(Output isDefault) As %String
{
set isDefault = 0
set binPath = "git"
try {
if '$data(@..%SYSNamespaceStorage()@("%gitBinPath"),binPath)#2 {
set isDefault = 1
}
} catch e {
// no-op; requires git to be on path in this case.
// (can't easily change storage location for backward compatibility)
}
quit $case($extract(binPath),"""":binPath,:""""_binPath_"""")
}
ClassMethod BasicMode() As %Boolean
{
quit $get(@..#Storage@("settings", "user", $username, "basicMode"), ..SystemBasicMode())
}
ClassMethod UserBasicMode() As %String
{
quit $get(@..#Storage@("settings", "user", $username, "basicMode"), "system")
}
ClassMethod SystemBasicMode() As %Boolean
{
quit $get(@..#Storage@("settings", "basicMode"), 0)
}
ClassMethod DefaultMergeBranch() As %String
{
quit $get(@..#Storage@("settings", "defaultMergeBranch"), "")
}
ClassMethod MappedItemsReadOnly() As %Boolean
{
quit $get(@..#Storage@("settings", "mappedItemsReadOnly"), 1)
}
ClassMethod GitUserName() As %String
{
quit $get(@..#Storage@("settings","user",$username,"gitUserName"),$username)
}
ClassMethod GitUserEmail() As %String
{
quit $get(@..#Storage@("settings","user",$username,"gitUserEmail"),$username_"@"_$zconvert(##class(%SYS.System).GetNodeName(),"L"))
}
ClassMethod PrivateKeyFile() As %String
{
quit $get(@..#Storage@("settings","ssh","privateKeyFile"))
}
ClassMethod CompileOnImport() As %Boolean
{
quit $get(@..#Storage@("settings","compileOnImport"),1)
}
ClassMethod WarnInstanceWideUncommitted() As %Boolean
{
quit $get(@..#Storage@("settings","warnInstanceWideUncommitted"),1)
}
ClassMethod EnvironmentName() As %String
{
quit $SYSTEM.Version.SystemMode()
}
ClassMethod LockBranch() As %Boolean
{
quit $get(@..#Storage@("settings","lockBranch"),0)
}
ClassMethod IsLIVE() As %Boolean
{
quit ..EnvironmentName()="LIVE"
}
ClassMethod NeedSettings() As %Boolean [ CodeMode = expression ]
{
(..TempFolder() = "") || (..GitBinPath() = "") || (..GitBinPath() = """")
}
ClassMethod InstallNamespace() As %String [ CodeMode = expression ]
{
..#InstallNamespace
}
ClassMethod IsMenuGitCommand(menuItemName As %String) As %Boolean [ CodeMode = expression ]
{
$Find(..#GitMenuItems, ","_menuItemName_",") > 0
}
ClassMethod IsContextMenuGitCommand(menuItemName As %String) As %Boolean [ CodeMode = expression ]
{
$Find(..#GitContextMenuItems, ","_menuItemName_",") > 0
}
ClassMethod IsImportAfter(menuItemName As %String) As %Boolean [ CodeMode = expression ]
{
$Find(..#ImportAfterGitMenuItems, ","_menuItemName_",") > 0
}
ClassMethod MigrateInstanceSettings()
{
if $data(^["%SYS"]SYS("SourceControl", "Git")) {
merge ^%SYS("SourceControl", "Git") = ^["%SYS"]SYS("SourceControl", "Git")
kill ^["%SYS"]SYS("SourceControl", "Git")
}
}
ClassMethod UserAction(InternalName As %String, MenuName As %String, ByRef Target As %String, ByRef Action As %String, ByRef Reload As %Boolean, ByRef Msg As %String) As %Status
{
#define Force 1
// MenuName = "<Name of menu>,<Name of menu item>"
#dim menuItemName as %String = $piece(MenuName,",",2)
#dim ec as %Status = $$$OK
if (..Type(InternalName) = "csp") && ($extract(InternalName,1) '= "/") {
set InternalName = "/" _ InternalName
}
set externalBrowser = 0
set urlPrefix = ""
set urlPostfix = ""
if $IsObject($Get(%request)) && (%request.Application = "/api/atelier/") && '%request.Secure {
// In this case, won't work in an iframe. Need to launch in an external browser.
set externalBrowser = 1
set urlPrefix = "http://"_%request.CgiEnvs("HTTP_HOST")
set token = $Get(%session.Data("WebCSPToken"))
set token = ##class(%Atelier.v1.Utils.General).GetCSPToken("/isc/studio/usertemplates/dummy.csp",token)
set %session.Data("WebCSPToken") = token
set urlPostfix = "CSPCHD="_token
}
if (menuItemName = "Settings") {
set Action = 2 + externalBrowser
set Target = urlPrefix _ "/isc/studio/usertemplates/gitsourcecontrol/gitprojectsettings.csp?Namespace="_$namespace_"&Username="_$username_"&"_urlPostfix
} elseif (menuItemName = "Init") {
if ##class(%File).CreateDirectoryChain(..TempFolder()) {
// cleanup items info
kill @..#Storage@("items")
kill @..#Storage@("TSH")
do ..Init()
} else {
set ec = ..MakeError("Unable to create folder "_..TempFolder())
}
} elseif (menuItemName = "GitWebUI") {
set Action = 2 + externalBrowser
set Target = urlPrefix _ "/isc/studio/usertemplates/gitsourcecontrol/webuidriver.csp/"_$namespace_"/"_$zconvert(InternalName,"O","URL")_"?"_urlPostfix
} elseif (menuItemName = "Export") || (menuItemName = "ExportForce") {
write !, "==export start==",!
set ec = ..ExportAll($case(menuItemName="ExportForce",1:$$$Force,:0))
if ec {
write !,"==export done==",!
}
} elseif (menuItemName = "ExportSystemDefaults") {
set ec = ..ExportSystemDefaults()
} elseif (menuItemName = "Import") {
set ec = ..ImportAll()
set Reload = 1
} elseif (menuItemName = "ImportForce") {
set ec = ..ImportAll($$$Force)
set Reload = 1
} elseif (menuItemName = "%OpenRepoFolder") {
set Action = 3
set Target = ..TempFolder()
} elseif (menuItemName = "Revert") {
set Reload = 1
quit ..Revert(InternalName)
} elseif (menuItemName = "NewBranch") {
set Target = "Please enter the name of the new branch"
set Action = 7
quit $$$OK
} elseif (menuItemName = "SwitchBranch") {
set Target = "Please enter the name of the existing branch"
set Action = 7
quit $$$OK
} elseif (menuItemName = "Commit") {
set Target = "Please enter a commit message"
set Action = 7
quit $$$OK
} elseif (menuItemName = "Sync") {
set Action = 2 + externalBrowser
set Target = urlPrefix _ "/isc/studio/usertemplates/gitsourcecontrol/sync.csp?Namespace="_$NAMESPACE
quit $$$OK
} elseif (menuItemName = "Push") {
quit ..Push()
} elseif (menuItemName = "PushForce") {
set Target = "Force pushing is potentially destructive and may overwrite the commit history of the remote branch. Are you sure you want to proceed?"
set Action = 1 // Make sure the user confirms that they want to do this
quit $$$OK
} elseif (menuItemName = "Fetch") {
$$$QuitOnError(..Fetch(.diffFiles))
set pointer = 0
write !, !, "Changed Files: "
while $listnext(diffFiles, pointer, item){
write !,?4, item
}
write !
} elseif (menuItemName = "Pull") {
quit ..Pull()
} elseif (menuItemName = "AddToSC") {
set ec = ..AddToSourceControl(InternalName)
} elseif (menuItemName = "RemoveFromSC") {
set ec = ..RemoveFromSourceControl(InternalName)
} elseif (menuItemName = "Status") {
do ..RunGitCommand("status", .errStream, .outStream)
write !, !, "Git Status: "
do ..PrintStreams(outStream, errStream)
} elseif (menuItemName = "ExportProduction") {
do ##class(SourceControl.Git.Util.Production).BaselineProduction($piece(InternalName,".",1,*-1))
}
quit ec
}
ClassMethod AfterUserAction(Type As %Integer, Name As %String, InternalName As %String, Answer As %Integer, Msg As %String = "", ByRef Reload As %Boolean) As %Status
{
set status = $$$OK
#dim menuName as %String = $piece(Name,",")
#dim menuItemName as %String = $piece(Name,",",2)
if (menuItemName = "Revert") || (menuItemName [ "Import") {
set Reload = 1
}
if (menuItemName = "Commit") {
if (Answer = 1) {
do ..Commit(InternalName, Msg)
set Reload = 1
}
} elseif (menuItemName = "NewBranch") {
if (Answer = 1) {
set status = ..NewBranch(Msg)
set Reload = 1
}
} elseif (menuItemName = "SwitchBranch") {
if (Answer = 1) {
set status = ..SwitchBranch(Msg)
set Reload = 1
}
} elseif (menuItemName = "Sync") {
if (Answer = 1) {
do ..Sync(Msg)
set Reload = 1
}
} elseif (menuItemName = "PushForce") {
if (Answer = 1) {
do ..Push(,1)
set Reload = 1
}
} elseif (menuItemName = "GitWebUI") {
// Always force reload as many things could have possibly changed.
set Reload = 1
}
quit status
}
ClassMethod Init() As %Status
{
do ..RunGitCommand("init",.errStream,.outStream)
do ..PrintStreams(outStream, errStream)
set settings = ##class(SourceControl.Git.Settings).%New()
$$$QuitOnError(settings.SaveWithSourceControl())
quit ..Commit(##class(SourceControl.Git.Settings.Document).#INTERNALNAME,"initial commit")
}
ClassMethod Revert(InternalName As %String) As %Status
{
set filename = ..FullExternalName(.InternalName)
do ##class(SourceControl.Git.DiscardState).SaveDiscardState(InternalName)
do ..RunGitCommand("checkout", .errStream, .outStream, "--", filename)
$$$QuitOnError(##class(SourceControl.Git.Change).RemoveUncommitted(filename,0,1))
$$$QuitOnError(##class(SourceControl.Git.Change).RefreshUncommitted(0,1,,1))
quit ##class(SourceControl.Git.PullEventHandler).ForInternalNames(InternalName)
}
ClassMethod Commit(InternalName As %String, Message As %String = "example commit message") As %Status
{
set filename = ..FullExternalName(.InternalName)
set username = ..GitUserName()
set email = ..GitUserEmail()
set author = ""
if ((username '= "") && (email '= "")) {
set author = username_" <"_email_">"
}
do ..RunGitWithArgs(.errStream, .outStream, "commit", "--author", author, "-m", Message, filename)
do ..PrintStreams(errStream, outStream)
$$$QuitOnError(##class(SourceControl.Git.Change).RemoveUncommitted(filename))
$$$QuitOnError(##class(SourceControl.Git.Change).RefreshUncommitted(,,,1))
quit $$$OK
}
ClassMethod NewBranch(newBranchName As %String) As %Status
{
set settings = ##class(SourceControl.Git.Settings).%New()
if (settings.basicMode) && (settings.defaultMergeBranch '= ""){
set err = ..RunGitWithArgs(.errStream, .outStream, "checkout", settings.defaultMergeBranch)
do ..PrintStreams(errStream, outStream)
if (err) {
quit $$$ERROR($$$GeneralError,errStream.Read()_$c(10)_"Current branch is: "_..GetCurrentBranch())
}
kill errStream, outStream
set err = ..RunGitWithArgs(.errStream, .outStream, "pull")
do ..PrintStreams(errStream, outStream)
if (err) {
quit $$$ERROR($$$GeneralError,errStream.Read()_$c(10)_"Current branch is: "_..GetCurrentBranch())
}
kill errStream, outStream
}
set err = ..RunGitWithArgs(.errStream, .outStream, "checkout", "-b", newBranchName)
do ..PrintStreams(errStream, outStream)
if err {
do errStream.Rewind()
quit $$$ERROR($$$GeneralError,errStream.Read()_$c(10)_"Current branch is: "_..GetCurrentBranch())
}
quit $$$OK
}
ClassMethod SwitchBranch(targetBranchName As %String) As %Status
{
// Make sure that branch exists first (-a lists both local and remote)
do ..RunGitWithArgs(.errStream,.outStream,"branch", "-a")
set branches = outStream.Read()
if ('$find(branches,targetBranchName)) {
quit $$$ERROR($$$GeneralError, "Selected branch does not exist"_$C(10))
}
k outStream, errStream
do ..RunGitWithArgs(.errStream, .outStream, "checkout", targetBranchName)
do ..PrintStreams(errStream, outStream)
// Checkout can fail due to unstaged changes
set errs = errStream.Read()
if ($find(errs, "error")) {
quit $$$ERROR($$$GeneralError, errs)
}
quit $$$OK
}
ClassMethod PreSync() As %String
{
set uncommittedFilesWithAction = ##class(SourceControl.Git.Utils).UncommittedWithAction().%Get("user")
quit ..GenerateCommitMessageFromFiles(uncommittedFilesWithAction)
}
/// Commits all the files as needed by the Sync operation
ClassMethod SyncCommit(Msg As %String) As %Status
{
if ..CheckForUncommittedFiles() {
set uncommittedFilesWithAction = ##class(SourceControl.Git.Utils).UncommittedWithAction().%Get("user")
set username = ..GitUserName()
set email = ..GitUserEmail()
set author = ""
if ((username '= "") && (email '= "")) {
set author = username_" <"_email_">"
}
do ..RunGitWithArgs(.errStream, .outStream, "commit", "--author", author, "-m", Msg)
do ..PrintStreams(errStream, outStream)
$$$QuitOnError(..ClearUncommitted(uncommittedFilesWithAction))
$$$QuitOnError(##class(SourceControl.Git.Change).RefreshUncommitted(,,,1))
}
quit $$$OK
}
ClassMethod CheckForUncommittedFiles() As %Boolean
{
set uncommittedFilesWithAction = ##class(SourceControl.Git.Utils).UncommittedWithAction().%Get("user")
set valInArr = uncommittedFilesWithAction.%Pop()
if valInArr = "" {
return 0
} else {
quit 1
}
}
/// Goes through all the added files and stages them
ClassMethod StageAddedFiles()
{
set uncommittedFilesWithAction = ##class(SourceControl.Git.Utils).UncommittedWithAction().%Get("user")
set iterator = uncommittedFilesWithAction.%GetIterator()
while iterator.%GetNext(,.value,) {
set file = value.%Get("file")
do ..RunGitWithArgs(.errStream, .outStream, "add", file)
do ..PrintStreams(errStream, outStream)
}
}
/// Merges the files from the configured branch as part of the Sync operation
/// Returns true if this resulted in durable changes to the local git repo
ClassMethod MergeDefaultRemoteBranch(Output alert As %String = "") As %Boolean
{
set rebased = 0
set settings = ##class(SourceControl.Git.Settings).%New()
set defaultMergeBranch = settings.defaultMergeBranch
if defaultMergeBranch '= "" {
do ..RunGitWithArgs(.errStream, .outStream, "fetch", "origin", defaultMergeBranch_":"_defaultMergeBranch)
do ..PrintStreams(errStream, outStream)
set startSha = ..GetCurrentRevision()
// Start a transaction so code changes can be rolled back
set initTLevel = $TLevel
try {
TSTART
set code = ..RunGitWithArgs(.errStream, .outStream, "rebase", defaultMergeBranch)
if (code '= 0) {
$$$ThrowStatus($$$ERROR($$$GeneralError,"git rebase reported failure"))
}
set rebased = 1
TCOMMIT
} catch e {
// "rebase" may throw an exception due to errors syncing to IRIS. In that case, roll back and keep going to abort the rebase.
write !,"Attempting to resolve differences in production definition..."
set resolver = ##class(SourceControl.Git.Util.ResolutionManager).FromLog(outStream)
if resolver.resolved {
set rebased = 1
TCOMMIT
write " success!"
} else {
write " unable to resolve - "_resolver.errorMessage
}
}
while $TLevel > initTLevel {
TROLLBACK 1
}
if rebased {
do ##class(SourceControl.Git.Utils).RunGitWithArgs(.errStream, .outStream, "diff", startSha, "HEAD", "--name-status")
do ##class(SourceControl.Git.Utils).ParseDiffStream(outStream,,.finalFileSet)
do ##class(SourceControl.Git.Utils).SyncIrisWithRepoThroughDiff(.finalFileSet)
} else {
do ..RunGitCommand("rebase",.errStream, .outStream,"--abort")
do ..PrintStreams(errStream, outStream)
set alert = "WARNING: Remote branch '"_defaultMergeBranch_"' could not be merged due to conflicts. Changes have been pushed to '"_..GetCurrentBranch()_"' and must be resolved in your git remote. See log for more details."
write !,alert,!
}
}
quit rebased
}
/// Converts the DynamicArray into a list and calls the SourceControl.Git.Change RemoveUncommitted method on the newly created list
ClassMethod ClearUncommitted(filesWithActions) As %Status
{
set files = ""
set iterator = filesWithActions.%GetIterator()
while iterator.%GetNext(,.value,) {
set file = value.%Get("file")
set files = files_$listbuild(file)
}
$$$QuitOnError(##class(SourceControl.Git.Change).RemoveUncommitted(files))
quit $$$OK
}
ClassMethod Sync(Msg As %String, Output alert As %String) As %Status
{
write !, "Syncing local repository...", !
do ..StageAddedFiles()
if '..HasRemoteRepo() {
write "No remote repository configured: skipping fetch, pull and push"
do ..SyncCommit(Msg)
} elseif ..InDefaultBranchBasicMode() {
// Do not commit to default merge branch in basic mode
write "In Basic mode on default merge branch: skipping commit and push"
do ..Fetch()
do ..Pull()
} else {
do ..Fetch()
do ..Pull()
do ..SyncCommit(Msg)
do ..Push(,1)
if ..MergeDefaultRemoteBranch(.alert) {
do ..Push(,1)
}
}
quit $$$OK
}
ClassMethod Push(remote As %String = "origin", force As %Boolean = 0) As %Status
{
do ##class(SourceControl.Git.Utils).RunGitCommandWithInput("branch",,.errStream,.outstream,"--show-current")
set branchName = outstream.ReadLine(outstream.Size)
if (force) {
set args($i(args)) = "--force"
}
set args($i(args)) = remote
set args($i(args)) = branchName
do ..RunGitWithArgs(.errStream, .outStream, "push", args...)
do ..PrintStreams(errStream, outStream)
quit $$$OK
}
ClassMethod Fetch(ByRef diffFiles) As %Status
{
do ..RunGitCommand("fetch", .errStream, .outStream, "--prune")
write !, "Fetch done"
kill errStream, outStream
do ..RunGitCommand("diff", .errStream, .outStream, "..origin/"_..GetCurrentBranch(), "--name-only")
set diffFiles = ""
while (outStream.AtEnd = 0) {
set diffFiles = diffFiles_$listbuild(outStream.ReadLine())
}
quit $$$OK
}
ClassMethod GetCurrentBranch() As %String
{
do ##class(SourceControl.Git.Utils).RunGitCommandWithInput("branch",,.errStream,.outStream,"--show-current")
set branchName = outStream.ReadLine(outStream.Size)
quit branchName
}
ClassMethod GetCurrentRevision() As %String
{
do ##class(SourceControl.Git.Utils).RunGitCommandWithInput("rev-parse",,.errStream,.outStream,"HEAD")
set revision = outStream.ReadLine(outStream.Size)
quit revision
}
ClassMethod Pull(remote As %String = "origin", pTerminateOnError As %Boolean = 0) As %Status
{
New %gitSCOutputFlag
Set %gitSCOutputFlag = 1
#define Force 1
set branchName = ..GetCurrentBranch()
write !, "Pulling from branch: ", branchName
kill errStream, outStream
do ##class(SourceControl.Git.Utils).RunGitCommandWithInput("ls-remote",,.errStream, .outStream, remote, branchName)
if (outStream.Read() = "") {
write !, "Skipping pull because remote branch does not exist."
quit $$$OK
}
kill errStream, outStream
set returnCode = ..RunGitWithArgs(.errStream, .outStream, "pull", remote, branchName)
write !
do outStream.OutputToDevice()
write !
do errStream.OutputToDevice()
write !, "Pull ran with return code: " _ returnCode
set err = errStream.Read()
if ($find(err,"error") || $find(err, "fatal") || $find(err, "ERROR")) && pTerminateOnError {
quit $$$ERROR($$$GeneralError, err)
}
quit $$$OK
}
ClassMethod Clone(remote As %String) As %Status
{
set settings = ##class(SourceControl.Git.Settings).%New()
// TODO: eventually use /ENV flag with GIT_TERMINAL_PROMPT=0. (This isn't doc'd yet and is only in really new versions.)
set sc = ..RunGitWithArgs(.errStream, .outStream, "clone", remote, settings.namespaceTemp)
// can I substitute this with the new print method?
$$$NewLineIfNonEmptyStream(errStream)
while 'errStream.AtEnd {
write errStream.ReadLine(),!
}
$$$NewLineIfNonEmptyStream(outStream)
while 'outStream.AtEnd {
write outStream.ReadLine(),!
}
quit $$$OK
}
ClassMethod GenerateSSHKeyPair() As %Status
{
set settings = ##class(SourceControl.Git.Settings).%New()
set filename = settings.privateKeyFile
set email = settings.gitUserEmail
set dir = ##class(%File).GetDirectory(filename)
if ##class(%File).Exists(filename) {
Throw ##class(%Exception.General).%New("File "_filename_" already exists")
}
do ##class(%File).CreateDirectoryChain(dir)
set outLog = ##class(%Library.File).TempFilename()
set errLog = ##class(%Library.File).TempFilename()
do $zf(-100,"/STDOUT="_$$$QUOTE(outLog)_" /STDERR="_$$$QUOTE(errLog),
"ssh-keygen",
"-t","ed25519",
"-C",email,
"-f",filename,
"-N","")
set errStream = ##class(%Stream.FileCharacter).%OpenId(errLog,,.sc)
set outStream = ##class(%Stream.FileCharacter).%OpenId(outLog,,.sc)
set outStream.TranslateTable="UTF8"
for stream=errStream,outStream {
set stream.RemoveOnClose = 1
}
do ..PrintStreams(outStream, errStream)
quit $$$OK
}
ClassMethod IsNamespaceInGit() As %Boolean [ CodeMode = expression ]
{
##class(%File).Exists(..TempFolder()_".git")
}
/// replaces any slashes with the ones for current OS<br/>
/// removes first slash if present<br/>
/// adds last slash if not present<br/>
ClassMethod NormalizeFolder(folder As %String) As %String
{
set folder = $translate(folder, "/", ..#Slash)
set:$extract(folder)=..#Slash $extract(folder) = ""
set:$extract(folder,*)'=..#Slash folder = folder _ ..#Slash
quit folder
}
ClassMethod ExternalName(InternalName As %String, ByRef MappingExists As %Boolean) As %String
{
set root = ..TempFolder()
set file = $Replace(..Name(.InternalName,.MappingExists),"/",..#Slash)
set fullFile = root_file
if '..Exists(.fullFile) {
quit file
}
quit $Piece(fullFile,root,2,*)
}
/// Check if file exists but case insensitive on file extension
/// Stolen from %IPM.Utils.File
ClassMethod Exists(ByRef pFilename) As %Boolean
{
If ##class(%File).Exists(pFilename) {
Return 1
}
Set tDirectory = ##class(%File).ParentDirectoryName(pFilename)
If '##class(%File).DirectoryExists(tDirectory) {
Return 0
}
Set tName = $Piece(pFilename, tDirectory, 2, *)
Set tFileName = $Piece(tName, ".", 1, * - 1)
Set tFileExt = $Piece(tName, ".", *)
for tExt = $$$LOWER(tFileExt), $$$UPPER(tFileExt) {
If ##class(%File).Exists(tDirectory _ tFileName _ "." _ tExt) {
Set pFilename = tDirectory _ tFileName _ "." _ tExt
Return 1
}
}
Return 0
}
/// Adds this item to the list of items that are tracked by source control
ClassMethod AddToServerSideSourceControl(InternalName As %String) As %Status
{
#dim i as %Integer
#dim ec as %Status = $$$OK
for i = 1:1:$length(InternalName, ",") {
#dim item as %String = ..NormalizeExtension($piece(InternalName, ",", i))
if (item = "") {
continue
}
set @..#Storage@("items", item) = ""
}
quit ec
}
ClassMethod AddToSourceControl(InternalName As %String, refreshUncommitted As %Boolean = 1) As %Status
{
do ##class(SourceControl.Git.PackageManagerContext).ForInternalName(InternalName)
set settings = ##class(SourceControl.Git.Settings).%New()
#dim i as %Integer
#dim ec as %Status = $$$OK
for i = 1:1:$length(InternalName, ",") {
#dim item as %String = ..NormalizeExtension($piece(InternalName, ",", i))
#dim type as %String = ..Type(.item)
#dim sc as %Status = ..ExportItem(item,,1,.filenames)
if 'sc {
set ec = $$$ADDSC(ec, sc)
}
for i=1:1:$Get(filenames) {
set ignoreNonexistent = (type '= "ptd")
set FileInternalName = ##class(SourceControl.Git.Utils).NormalizeExtension(
##class(SourceControl.Git.Utils).NameToInternalName(filenames(i), 0,ignoreNonexistent,1))
if (FileInternalName = "") {
continue
}
// Items mapped to namespace's non default routine database are ignored if set to be read-only
if (settings.mappedItemsReadOnly && ..FileIsMapped(InternalName)) {
continue
}
set FileType = ##class(SourceControl.Git.Utils).Type(.FileInternalName)
set @..#Storage@("items", FileInternalName) = ""
do ..RunGitCommand("add",.errStream,.outStream,filenames(i),"--intent-to-add")
write !, "Added ", FileInternalName, " to source control."
do ..PrintStreams(outStream, errStream)
}
}
if refreshUncommitted {
do ##class(SourceControl.Git.Change).RefreshUncommitted(,,,1)
}
quit ec
}
ClassMethod RemoveFromGit(InternalName)
{
#dim fullName = ##class(Utils).FullExternalName(InternalName)
do ..RunGitCommand("rm",.errStream,.outStream,"--cached", fullName)
do ..PrintStreams(errStream, outStream)
}
ClassMethod DeleteExternalsForItem(InternalName As %String) As %Status
{
#dim type as %String = ..Type(.InternalName)
#dim ec as %Status = $$$OK
if (type = "prj") || (type = "pkg") || (type = "csp" && ..IsCspFolder(InternalName)) {
// we delete complex items
//get all item in files
#dim itemsList
$$$QuitOnError(..ListItemsInFiles(.itemsList))
#dim item as %String = ""
//for all item in files
for {
set item = $order(itemsList(item))
quit:item=""
//if item is not in sc -- delete file
if '..IsInSourceControl(item) {
#dim sc as %Status = ..DeleteExternalFile(item)
if 'sc {
set ec = $$$ADDSC(ec, sc)
}
do ..RemoveFromGit(item)
}
}
} else {
set ec = ..DeleteExternalFile(InternalName)
do ..RemoveFromGit(InternalName)
}
quit ec
}
ClassMethod FindTrackedFilesInPackage(InternalName As %String, ByRef trackedFiles As %String) As %Status
{
Set sc = $$$OK
set item = InternalName_"."
set trackedFiles = ""
for{
set item = $order(@..#Storage@("items",item))
quit:item'[InternalName_"."
if ..IsClassInPackage(item, InternalName) {
if (trackedFiles = ""){
set trackedFiles = item
}
else {
set trackedFiles = trackedFiles_","_item
}
}
}
Return sc
}
ClassMethod FindTrackedFilesInProjects(InternalName As %String, ByRef trackedFiles As %String) As %Status
{
Set sc = $$$OK
#dim item as %String = ""
set trackedFiles = ""
for{
set item = $order(@..#Storage@("items",item))
quit:item=""
if ..IsItemInProject(item, InternalName) {
if (trackedFiles = ""){
set trackedFiles = item
}
else {
set trackedFiles = trackedFiles_","_item
}
}
}
Return sc
}
ClassMethod FindTrackedFilesInCSPFolders(InternalName As %String, ByRef trackedFiles As %String) As %Status
{
Set sc = $$$OK
set item = InternalName_"/"
set trackedFiles = ""
for {
set item = $order(@..#Storage@("items",item))
quit:item'[InternalName_"/"
if ..IsItemInCSPFolder(item, InternalName) {
if (trackedFiles = ""){
set trackedFiles = item
}
else {
set trackedFiles = trackedFiles_","_item
}
}
}
Return sc
}
ClassMethod FindTrackedFiles(InternalName As %String, ByRef trackedFiles As %String) As %Status
{
#dim type as %String = ..Type(.InternalName)
set InternalName = ..NameWithoutExtension(InternalName)
if (type = "pkg") {
set sc = ..FindTrackedFilesInPackage(InternalName, .trackedFiles)
} elseif (type ="prj") {
set sc = ..FindTrackedFilesInProjects(InternalName, .trackedFiles)
} elseif (type = "csp") {
set sc = ..FindTrackedFilesInCSPFolders(InternalName, .trackedFiles)
}
return sc
}
/// Description
ClassMethod FindTrackedParent(InternalName As %String, ByRef parentElement As %String) As %Status
{
#dim type as %String = ..Type(.InternalName)
set isInSourceControl = 0
if type = "cls" {
#define StripExtension(%s) $Piece(%s,".",1,$Length(%s, ".") - 1)
set className = $$$StripExtension(InternalName)
set isInSourceControl = ..FindInPackages(InternalName, .parentElement)
if (isInSourceControl){
set parentElement = parentElement_".pkg"
}
} elseif type = "csp" {
if $extract(InternalName) '= "/" {
set InternalName = "/" _ InternalName
}
set isInSourceControl = ..FindInCspFolders(InternalName, .parentElement)
}
// our last chance to find item -- let's look in projects
if 'isInSourceControl {
set isInSourceControl = ..FindInProjects(InternalName, .parentElement)
if (isInSourceControl){
set parentElement = parentElement_".prj"
}
}
quit isInSourceControl
}
ClassMethod RemoveFromServerSideSourceControl(InternalName As %String) As %Status
{
#dim i as %Integer
#dim ec as %Status = $$$OK
for i = 1:1:$length(InternalName, ",") {
#dim item as %String = ..NormalizeExtension($piece(InternalName, ",", i))
#dim tsc as %Status = $$$OK
#dim type as %String = ..Type(.InternalName)
if $data(@..#Storage@("items", item)) {
kill @..#Storage@("items", item)
do ..RemoveFolderIfEmpty(..TempFolder())
} elseif (type = "cls") {
set tsc = ..MakeError(item _ " is not in SourceControl")
}
set ec = $$$ADDSC(tsc, ec)
}
quit ec
}
ClassMethod RemoveFromSourceControl(InternalName As %String, cascadeDelete As %Boolean = 1) As %Status
{
write !
#dim sc as %Status = $$$OK
if (InternalName = ""){
set sc = ..MakeError("Passed InternalName is empty!")
quit sc
}
for i = 1:1:$length(InternalName, ",") {
#dim tsc as %Status = $$$OK
#dim type as %String = ..Type(.InternalName)