-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAbstractGitSCMSourceTest.java
More file actions
1365 lines (1237 loc) · 67 KB
/
AbstractGitSCMSourceTest.java
File metadata and controls
1365 lines (1237 loc) · 67 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
package jenkins.plugins.git;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.Actionable;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.GitException;
import hudson.plugins.git.UserRemoteConfig;
import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit;
import hudson.scm.SCMRevisionState;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.BuildChooserSetting;
import hudson.plugins.git.extensions.impl.LocalBranch;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import jenkins.plugins.git.traits.BranchDiscoveryTrait;
import jenkins.plugins.git.traits.DiscoverOtherRefsTrait;
import jenkins.plugins.git.traits.IgnoreOnPushNotificationTrait;
import jenkins.plugins.git.traits.PruneStaleBranchTrait;
import jenkins.plugins.git.traits.TagDiscoveryTrait;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction;
import jenkins.scm.api.trait.SCMSourceTrait;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.plugins.gitclient.FetchCommand;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.TestJGitAPIImpl;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Stopwatch;
import org.junit.rules.TestName;
import org.junit.runner.OrderWith;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link AbstractGitSCMSource}
*/
@OrderWith(RandomOrder.class)
public class AbstractGitSCMSourceTest {
static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
static final String GitBranchSCMHead_DEV_DEV2_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
@Rule
public JenkinsRule r = new JenkinsRule();
@Rule
public GitSampleRepoRule sampleRepo = new GitSampleRepoRule();
@Rule
public GitSampleRepoRule sampleRepo2 = new GitSampleRepoRule();
@ClassRule
public static Stopwatch stopwatch = new Stopwatch();
@Rule
public TestName testName = new TestName();
private static final int MAX_SECONDS_FOR_THESE_TESTS = 210;
private boolean isTimeAvailable() {
String env = System.getenv("CI");
if (env == null || !Boolean.parseBoolean(env)) {
// Run all tests when not in CI environment
return true;
}
return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS;
}
// TODO AbstractGitSCMSourceRetrieveHeadsTest *sounds* like it would be the right place, but it does not in fact retrieve any heads!
@Issue("JENKINS-37482")
@Test
@Deprecated // Tests deprecated GitSCMSource constructor
public void retrieveHeads() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Test
public void retrieveHeadsRequiresBranchDiscovery() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.singletonList(new BranchDiscoveryTrait()));
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_ignoreTagsWithoutTagDiscoveryTrait() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.singletonList(new BranchDiscoveryTrait()));
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev-commit-message", "--no-verify");
long beforeLightweightTag = System.currentTimeMillis();
sampleRepo.git("tag", "lightweight");
long afterLightweightTag = System.currentTimeMillis();
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2-commit-message", "--no-verify");
long beforeAnnotatedTag = System.currentTimeMillis();
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
long afterAnnotatedTag = System.currentTimeMillis();
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3-commit-message", "--no-verify");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<>());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
Set<SCMHead> scmHeadSet = source.fetch(listener);
long now = System.currentTimeMillis();
for (SCMHead scmHead : scmHeadSet) {
if (scmHead instanceof GitTagSCMHead) {
GitTagSCMHead tagHead = (GitTagSCMHead) scmHead;
// FAT file system time stamps only resolve to 2 second boundary
// EXT3 file system time stamps only resolve to 1 second boundary
long fileTimeStampFuzz = isWindows() ? 2000L : 1000L;
fileTimeStampFuzz = 12 * fileTimeStampFuzz / 10; // 20% grace for file system noise
switch (scmHead.getName()) {
case "lightweight":
{
long timeStampDelta = afterLightweightTag - tagHead.getTimestamp();
assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterLightweightTag - beforeLightweightTag + fileTimeStampFuzz))));
break;
}
case "annotated":
{
long timeStampDelta = afterAnnotatedTag - tagHead.getTimestamp();
assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterAnnotatedTag - beforeAnnotatedTag + fileTimeStampFuzz))));
break;
}
default:
fail("Unexpected tag head '" + scmHead.getName() + "'");
break;
}
}
}
String expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
assertEquals(expected, scmHeadSet.toString());
// And reuse cache:
assertEquals(expected, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
assertEquals(expected, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrait() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<>());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.singletonList(new TagDiscoveryTrait()));
assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString());
// And reuse cache:
assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString());
}
@Issue("JENKINS-45953")
@Test
public void retrieveRevisions() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<>());
TaskListener listener = StreamTaskListener.fromStderr();
assertThat(source.fetchRevisions(listener, null), hasSize(0));
source.setTraits(Collections.singletonList(new BranchDiscoveryTrait()));
assertThat(source.fetchRevisions(listener, null), containsInAnyOrder("dev", "master"));
source.setTraits(Collections.singletonList(new TagDiscoveryTrait()));
assertThat(source.fetchRevisions(listener, null), containsInAnyOrder("annotated", "lightweight"));
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
assertThat(source.fetchRevisions(listener, null), containsInAnyOrder("dev", "master", "annotated", "lightweight"));
}
@Issue("JENKINS-64803")
@Test
public void retrieveTags_folderScopedCredentials() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// Create a Folder and add a folder credentials
Folder f = r.jenkins.createProject(Folder.class, "test");
Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
CredentialsStore folderStore = null;
for (CredentialsStore s : stores) {
if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
folderStore = s;
break;
}
}
assert folderStore != null;
String fCredentialsId = "fcreds";
StandardCredentials fCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
fCredentialsId, "fcreds", "user", "password");
folderStore.addCredentials(Domain.global(), fCredentials);
folderStore.save();
WorkflowJob p = f.createProject(WorkflowJob.class, "wjob");
source.setTraits(new ArrayList<>());
source.setCredentialsId(fCredentialsId);
Git git = mock(Git.class, CALLS_REAL_METHODS);
GitClient gitClient = spy(git.getClient());
// Spy on GitClient methods
try (MockedStatic<Git> gitMock = mockStatic(Git.class, CALLS_REAL_METHODS)) {
gitMock.when(() -> Git.with(any(), any())).thenReturn(git);
doReturn(gitClient).when(git).getClient();
String className = "jenkins.plugins.git.AbstractGitSCMSourceTest";
String testName = "retrieveTags_folderScopedCredentials";
String flag = className + "." + testName + ".enabled";
String defaultValue = "The source.fetch() unexpectedly modifies the git remote.origin.url in the working repo";
/* If -Djenkins.plugins.git.AbstractGitSCMSourceTest.retrieveTags_folderScopedCredentials.enabled=true */
if (!System.getProperty(flag, defaultValue).equals(defaultValue)) {
/* The source.fetch() unexpectedly modifies the git remote.origin.url in the working repo */
SCMRevision rev = source.fetch("lightweight", listener, p);
assertThat(rev, notNullValue());
assertThat(rev.getHead().toString(), equalTo("SCMHead{'lightweight'}"));
verify(gitClient, times(0)).addDefaultCredentials(null);
verify(gitClient, atLeastOnce()).addDefaultCredentials(fCredentials);
}
}
}
@Issue("JENKINS-47824")
@Test
public void retrieveByName() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
String masterHash = sampleRepo.head();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "v1");
String v1Hash = sampleRepo.head();
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "v2", "-m", "annotated");
String v2Hash = sampleRepo.head();
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
String devHash = sampleRepo.head();
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<>());
TaskListener listener = StreamTaskListener.fromStderr();
listener.getLogger().println("\n=== fetch('master') ===\n");
SCMRevision rev = source.fetch("master", listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(masterHash));
listener.getLogger().println("\n=== fetch('dev') ===\n");
rev = source.fetch("dev", listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(devHash));
listener.getLogger().println("\n=== fetch('v1') ===\n");
rev = source.fetch("v1", listener, null);
assertThat(rev, instanceOf(GitTagSCMRevision.class));
assertThat(((GitTagSCMRevision)rev).getHash(), is(v1Hash));
listener.getLogger().println("\n=== fetch('v2') ===\n");
rev = source.fetch("v2", listener, null);
assertThat(rev, instanceOf(GitTagSCMRevision.class));
assertThat(((GitTagSCMRevision)rev).getHash(), is(v2Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", masterHash);
rev = source.fetch(masterHash, listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(masterHash));
assertThat(rev.getHead().getName(), is("master"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", masterHash.substring(0, 10));
rev = source.fetch(masterHash.substring(0, 10), listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(masterHash));
assertThat(rev.getHead().getName(), is("master"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", devHash);
rev = source.fetch(devHash, listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(devHash));
assertThat(rev.getHead().getName(), is("dev"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", devHash.substring(0, 10));
rev = source.fetch(devHash.substring(0, 10), listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(devHash));
assertThat(rev.getHead().getName(), is("dev"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v1Hash);
rev = source.fetch(v1Hash, listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v1Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v1Hash.substring(0, 10));
rev = source.fetch(v1Hash.substring(0, 10), listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v1Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Hash);
rev = source.fetch(v2Hash, listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Hash.substring(0, 10));
rev = source.fetch(v2Hash.substring(0, 10), listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
String v2Tag = "refs/tags/v2";
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Tag);
rev = source.fetch(v2Tag, listener, null);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
}
public static abstract class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner {
}
@Test
@Deprecated
public void retrievePrimaryHead_NotDuplicated() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
retrievePrimaryHead(false);
}
@Test
@Deprecated
public void retrievePrimaryHead_Duplicated() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
retrievePrimaryHead(true);
}
@Deprecated // Calls deprecated GitSCMSource constructor
private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception {
sampleRepo.init();
sampleRepo.write("file.txt", "");
sampleRepo.git("add", "file.txt");
sampleRepo.git("commit", "--all", "--message=add-empty-file");
sampleRepo.git("checkout", "-b", "new-primary");
sampleRepo.write("file.txt", "content");
sampleRepo.git("add", "file.txt");
sampleRepo.git("commit", "--all", "--message=add-file");
if (duplicatePrimary) {
// If more than one branch points to same sha1 as new-primary and the
// command line git implementation is older than 2.8.0, then the guesser
// for primary won't be able to choose between the two alternatives.
// The next line illustrates that case with older command line git.
sampleRepo.git("checkout", "-b", "new-primary-duplicate", "new-primary");
}
sampleRepo.git("checkout", "master");
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.git("symbolic-ref", "HEAD", "refs/heads/new-primary");
SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
ActionableSCMSourceOwner owner = Mockito.mock(ActionableSCMSourceOwner.class);
when(owner.getSCMSource(source.getId())).thenReturn(source);
when(owner.getSCMSources()).thenReturn(Collections.singletonList(source));
source.setOwner(owner);
TaskListener listener = StreamTaskListener.fromStderr();
Map<String, SCMHead> headByName = new TreeMap<>();
for (SCMHead h: source.fetch(listener)) {
headByName.put(h.getName(), h);
}
if (duplicatePrimary) {
assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary", "new-primary-duplicate"));
} else {
assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary"));
}
List<Action> actions = source.fetchActions(null, listener);
GitRemoteHeadRefAction refAction = null;
for (Action a: actions) {
if (a instanceof GitRemoteHeadRefAction) {
refAction = (GitRemoteHeadRefAction) a;
break;
}
}
final boolean CLI_GIT_LESS_THAN_280 = !sampleRepo.gitVersionAtLeast(2, 8);
if (duplicatePrimary && CLI_GIT_LESS_THAN_280) {
assertThat(refAction, is(nullValue()));
} else {
assertThat(refAction, notNullValue());
assertThat(refAction.getName(), is("new-primary"));
when(owner.getAction(GitRemoteHeadRefAction.class)).thenReturn(refAction);
when(owner.getActions(GitRemoteHeadRefAction.class)).thenReturn(Collections.singletonList(refAction));
actions = source.fetchActions(headByName.get("new-primary"), null, listener);
}
PrimaryInstanceMetadataAction primary = null;
for (Action a : actions) {
if (a instanceof PrimaryInstanceMetadataAction) {
primary = (PrimaryInstanceMetadataAction) a;
break;
}
}
if (duplicatePrimary && CLI_GIT_LESS_THAN_280) {
assertThat(primary, is(nullValue()));
} else {
assertThat(primary, notNullValue());
}
}
@Issue("JENKINS-31155")
@Test
public void retrieveRevision() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of branches:
assertEquals("v2", fileAt("master", run, source, listener));
assertEquals("v3", fileAt("dev", run, source, listener));
// Tags:
assertEquals("v1", fileAt("v1", run, source, listener));
// And commit hashes:
assertEquals("v1", fileAt(v1, run, source, listener));
assertEquals("v1", fileAt(v1.substring(0, 7), run, source, listener));
// Nonexistent stuff:
assertNull(fileAt("nonexistent", run, source, listener));
assertNull(fileAt("1234567", run, source, listener));
assertNull(fileAt("", run, source, listener));
assertNull(fileAt("\n", run, source, listener));
assertThat(source.fetchRevisions(listener, null), hasItems("master", "dev", "v1"));
// we do not care to return commit hashes or other references
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_nonHead() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
// @Ignore("At least file:// protocol doesn't allow fetching unannounced commits")
public void retrieveRevision_nonAdvertised() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("reset", "--hard", "HEAD^"); // dev, the v3 ref is eligible for GC but still fetchable
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
// Fails with a file:// URL, do not assert
// @Ignore("At least file:// protocol doesn't allow fetching unannounced commits")
// assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/foo")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef_descendant() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
String v2 = sampleRepo.head();
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD~2"); // dev
String dev = sampleRepo.head();
assertNotEquals(dev, v3); //Just verifying the reset nav got correct
assertEquals(dev, v2);
sampleRepo.write("file", "v5");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef_abbrev_sha1() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/foo")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3.substring(0, 7), run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_pr_refspec() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("pull-requests/*/from")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt("pull-requests/1/from", run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_pr_local_refspec() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
//new RefSpecsSCMSourceTrait("+refs/pull-requests/*/from:refs/remotes/@{remote}/pr/*")
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("/pull-requests/*/from", "pr/@{1}")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt("pr/1", run, source, listener));
}
private int wsCount;
private String fileAt(String revision, Run<?,?> run, SCMSource source, TaskListener listener) throws Exception {
SCMRevision rev = source.fetch(revision, listener, null);
if (rev == null) {
return null;
} else {
FilePath ws = new FilePath(run.getRootDir()).child("ws" + ++wsCount);
source.build(rev.getHead(), rev).checkout(run, new Launcher.LocalLauncher(listener), ws, listener, null, SCMRevisionState.NONE);
return ws.child("file").readToString();
}
}
@Issue("JENKINS-48061")
@Test
public void fetchOtherRef() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/1", v3);
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
final SCMHeadObserver.Collector collector =
source.fetch((SCMSourceCriteria) (probe, listener1) -> true, new SCMHeadObserver.Collector(), listener);
final Map<SCMHead, SCMRevision> result = collector.result();
assertThat(result.entrySet(), hasSize(4));
assertThat(result, hasKey(allOf(
instanceOf(GitRefSCMHead.class),
hasProperty("name", equalTo("custom-1"))
)));
}
@Issue("JENKINS-48061")
@Test
public void fetchOtherRevisions() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/1", v3);
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
final Set<String> revisions = source.fetchRevisions(listener, null);
assertThat(revisions, hasSize(4));
assertThat(revisions, containsInAnyOrder(
equalTo("custom-1"),
equalTo("v1"),
equalTo("dev"),
equalTo("master")
));
}
@Issue("JENKINS-37727")
@Test
@Deprecated // Check GitSCMSource deprecated constructor
public void pruneRemovesDeletedBranches() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
/* Write a file to the master branch */
sampleRepo.write("master-file", "master-content-" + UUID.randomUUID());
sampleRepo.git("add", "master-file");
sampleRepo.git("commit", "--message=master-branch-commit-message");
/* Write a file to the dev branch */
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("dev-file", "dev-content-" + UUID.randomUUID());
sampleRepo.git("add", "dev-file");
sampleRepo.git("commit", "--message=dev-branch-commit-message");
/* Fetch from sampleRepo */
GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
/* Create dev2 branch and write a file to it */
sampleRepo.git("checkout", "-b", "dev2", "master");
sampleRepo.write("dev2-file", "dev2-content-" + UUID.randomUUID());
sampleRepo.git("add", "dev2-file");
sampleRepo.git("commit", "--message=dev2-branch-commit-message");
// Verify new branch is visible
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
/* Delete the dev branch */
sampleRepo.git("branch", "-D", "dev");
/* Fetch and confirm dev branch was pruned */
assertEquals("[GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]", source.fetch(listener).toString());
}
@Test
@Deprecated // Tests deprecated getExtensions() and setExtensions()
public void testSpecificRevisionBuildChooser() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
/* Write a file to the master branch */
sampleRepo.write("master-file", "master-content-" + UUID.randomUUID());
sampleRepo.git("add", "master-file");
sampleRepo.git("commit", "--message=master-branch-commit-message");
/* Fetch from sampleRepo */
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Collections.singletonList(new IgnoreOnPushNotificationTrait()));
List<GitSCMExtension> extensions = new ArrayList<>();
assertThat(source.getExtensions(), is(empty()));
LocalBranch localBranchExtension = new LocalBranch("**");
extensions.add(localBranchExtension);
source.setExtensions(extensions);
assertThat(source.getExtensions(), contains(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
)
));
SCMHead head = new SCMHead("master");
SCMRevision revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "beaded4deed2bed4feed2deaf78933d0f97a5a34");
// because we are ignoring push notifications we also ignore commits
extensions.add(new IgnoreNotifyCommit());
/* Check that BuildChooserSetting not added to extensions by build() */
GitSCM scm = (GitSCM) source.build(head);
assertThat(scm.getExtensions(), containsInAnyOrder(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
),
// no BuildChooserSetting
instanceOf(IgnoreNotifyCommit.class),
instanceOf(GitSCMSourceDefaults.class)
));
/* Check that BuildChooserSetting has been added to extensions by build() */
GitSCM scmRevision = (GitSCM) source.build(head, revision);
assertThat(scmRevision.getExtensions(), containsInAnyOrder(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
),
instanceOf(BuildChooserSetting.class),
instanceOf(IgnoreNotifyCommit.class),
instanceOf(GitSCMSourceDefaults.class)
));
}
@Test
@Deprecated // Tests deprecated GitSCMSource constructor
public void testCustomRemoteName() throws Exception {
assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable());
sampleRepo.init();
GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "upstream", null, "*", "", true);
SCMHead head = new SCMHead("master");
GitSCM scm = (GitSCM) source.build(head);
List<UserRemoteConfig> configs = scm.getUserRemoteConfigs();
assertEquals(1, configs.size());
UserRemoteConfig config = configs.get(0);