/
GitAPITestCase.java
3838 lines (3335 loc) · 168 KB
/
GitAPITestCase.java
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 org.jenkinsci.plugins.gitclient;
import static java.util.Collections.unmodifiableList;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.jenkinsci.plugins.gitclient.StringSharesPrefix.sharesPrefix;
import static org.junit.Assert.assertNotEquals;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.ProxyConfiguration;
import hudson.model.TaskListener;
import hudson.plugins.git.Branch;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitLockFailedException;
import hudson.plugins.git.IGitAPI;
import hudson.plugins.git.IndexEntry;
import hudson.remoting.VirtualChannel;
import hudson.util.IOUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.TemporaryDirectoryAllocator;
import org.objenesis.ObjenesisStd;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
public abstract class GitAPITestCase extends TestCase {
public final TemporaryDirectoryAllocator temporaryDirectoryAllocator = new TemporaryDirectoryAllocator();
protected hudson.EnvVars env = new hudson.EnvVars();
protected TaskListener listener;
protected LogHandler handler = null;
private int logCount = 0;
private static final String LOGGING_STARTED = "Logging started";
private static final String SRC_DIR = (new File(".")).getAbsolutePath();
private String revParseBranchName = null;
private void createRevParseBranch() throws GitException, InterruptedException {
revParseBranchName = "rev-parse-branch-" + UUID.randomUUID().toString();
w.git.checkout("origin/master", revParseBranchName);
}
/**
* One local workspace of a Git repository on a temporary directory
* that gets automatically cleaned up in the end.
*
* Every test case automatically gets one in {@link #w} but additional ones can be created if multi-repository
* interactions need to be tested.
*/
class WorkingArea {
final File repo;
final GitClient git;
boolean bare = false;
WorkingArea() throws Exception {
this(temporaryDirectoryAllocator.allocate());
}
WorkingArea(File repo) throws Exception {
this.repo = repo;
git = setupGitAPI(repo);
setupProxy(git);
}
private void setupProxy(GitClient gitClient)
throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
final String proxyHost = getSystemProperty("proxyHost", "http.proxyHost", "https.proxyHost");
final String proxyPort = getSystemProperty("proxyPort", "http.proxyPort", "https.proxyPort");
final String proxyUser = getSystemProperty("proxyUser", "http.proxyUser", "https.proxyUser");
//final String proxyPassword = getSystemProperty("proxyPassword", "http.proxyPassword", "https.proxyPassword");
final String noProxyHosts = getSystemProperty("noProxyHosts", "http.noProxyHosts", "https.noProxyHosts");
if(isBlank(proxyHost) || isBlank(proxyPort)) return;
ProxyConfiguration proxyConfig = new ObjenesisStd().newInstance(ProxyConfiguration.class);
setField(ProxyConfiguration.class, "name", proxyConfig, proxyHost);
setField(ProxyConfiguration.class, "port", proxyConfig, Integer.parseInt(proxyPort));
setField(ProxyConfiguration.class, "userName", proxyConfig, proxyUser);
setField(ProxyConfiguration.class, "noProxyHost", proxyConfig, noProxyHosts);
//Password does not work since a set password results in a "Secret" call which expects a running Jenkins
setField(ProxyConfiguration.class, "password", proxyConfig, null);
setField(ProxyConfiguration.class, "secretPassword", proxyConfig, null);
gitClient.setProxy(proxyConfig);
}
private void setField(Class<?> clazz, String fieldName, Object object, Object value)
throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
Field declaredField = clazz.getDeclaredField(fieldName);
declaredField.setAccessible(true);
declaredField.set(object, value);
}
private String getSystemProperty(String ... keyVariants)
{
for(String key : keyVariants) {
String value = System.getProperty(key);
if(value != null) return value;
}
return null;
}
String cmd(String args) throws IOException, InterruptedException {
return launchCommand(args.split(" "));
}
String cmd(boolean ignoreError, String args) throws IOException, InterruptedException {
return launchCommand(ignoreError, args.split(" "));
}
String launchCommand(String... args) throws IOException, InterruptedException {
return launchCommand(false, args);
}
String launchCommand(boolean ignoreError, String... args) throws IOException, InterruptedException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int st = new Launcher.LocalLauncher(listener).launch().pwd(repo).cmds(args).
envs(env).stdout(out).join();
String s = out.toString();
if (!ignoreError) {
if (s == null || s.isEmpty()) {
s = StringUtils.join(args, ' ');
}
assertEquals(s, 0, st); /* Reports full output of failing commands */
}
return s;
}
String repoPath() {
return repo.getAbsolutePath();
}
WorkingArea init() throws IOException, InterruptedException {
git.init();
return this;
}
WorkingArea init(boolean bare) throws IOException, InterruptedException {
git.init_().workspace(repoPath()).bare(bare).execute();
return this;
}
void tag(String tag) throws IOException, InterruptedException {
cmd("git tag " + tag);
}
void commitEmpty(String msg) throws IOException, InterruptedException {
cmd("git commit --allow-empty -m " + msg);
}
/**
* Refers to a file in this workspace
*/
File file(String path) {
return new File(repo, path);
}
boolean exists(String path) {
return file(path).exists();
}
/**
* Creates a file in the workspace.
*/
void touch(String path) throws IOException {
file(path).createNewFile();
}
/**
* Creates a file in the workspace.
*/
File touch(String path, String content) throws IOException {
File f = file(path);
FileUtils.writeStringToFile(f, content, "UTF-8");
return f;
}
public void rm(String path) {
file(path).delete();
}
public String contentOf(String path) throws IOException {
return FileUtils.readFileToString(file(path), "UTF-8");
}
/**
* Creates a CGit implementation. Sometimes we need this for testing JGit impl.
*/
protected CliGitAPIImpl cgit() throws Exception {
return (CliGitAPIImpl)Git.with(listener, env).in(repo).using("git").getClient();
}
/**
* Creates a {@link Repository} object out of it.
*/
protected FileRepository repo() throws IOException {
return bare ? new FileRepository(repo) : new FileRepository(new File(repo, ".git"));
}
/**
* Obtain the current HEAD revision
*/
ObjectId head() throws IOException, InterruptedException {
return git.revParse("HEAD");
}
/**
* Casts the {@link #git} to {@link IGitAPI}
*/
public IGitAPI igit() {
return (IGitAPI)git;
}
}
private WorkingArea w;
WorkingArea clone(String src) throws Exception {
WorkingArea x = new WorkingArea();
x.launchCommand("git", "clone", src, x.repoPath());
return new WorkingArea(x.repo);
}
private boolean timeoutVisibleInCurrentTest;
/**
* Returns true if the current test is expected to have a timeout
* value visible written to the listener log. Used to assert
* timeout values are passed correctly through the layers without
* requiring that the timeout actually expire.
* @see #setTimeoutVisibleInCurrentTest(boolean)
*/
protected boolean getTimeoutVisibleInCurrentTest() {
return timeoutVisibleInCurrentTest;
}
/**
* Pass visible = true to cause the current test to assert that a
* timeout value should be reported in at least one of the log
* entries.
* @param visible set to false if current test performs no operation which should report a timeout value
* @see #getTimeoutVisibleInCurrentTest()
*/
protected void setTimeoutVisibleInCurrentTest(boolean visible) {
timeoutVisibleInCurrentTest = visible;
}
/**
* Array of integer values of the timeouts expected to be passed
* to launchCommandIn() during a single test. Simplest to use if
* the first or the last call in a test is the only call which
* uses a timeout, then the expectedTimeouts array can be
* initialized with default values in all the other entries.
*/
private List<Integer> expectedTimeouts = null;
protected void setExpectedTimeouts(List<Integer> timeouts) {
expectedTimeouts = timeouts;
}
@Override
protected void setUp() throws Exception {
revParseBranchName = null;
setTimeoutVisibleInCurrentTest(true);
expectedTimeouts = null;
Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++);
handler = new LogHandler();
handler.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
logger.setLevel(Level.ALL);
listener = new hudson.util.LogTaskListener(logger, Level.ALL);
listener.getLogger().println(LOGGING_STARTED);
w = new WorkingArea();
}
/* HEAD ref of local mirror - all read access should use getMirrorHead */
private static ObjectId mirrorHead = null;
private ObjectId getMirrorHead() throws IOException, InterruptedException
{
if (mirrorHead == null) {
final String mirrorPath = new File(localMirror()).getAbsolutePath();
mirrorHead = ObjectId.fromString(w.launchCommand("git", "--git-dir=" + mirrorPath, "rev-parse", "HEAD").substring(0,40));
}
return mirrorHead;
}
private final String remoteMirrorURL = "https://github.com/jenkinsci/git-client-plugin.git";
private final String remoteSshURL = "git@github.com:ndeloof/git-client-plugin.git";
/**
* Obtains the local mirror of https://github.com/jenkinsci/git-client-plugin.git and return URLish to it.
*/
public String localMirror() throws IOException, InterruptedException {
File base = new File(".").getAbsoluteFile();
for (File f=base; f!=null; f=f.getParentFile()) {
if (new File(f,"target").exists()) {
File clone = new File(f, "target/clone.git");
if (!clone.exists()) { // TODO: perhaps some kind of quick timestamp-based up-to-date check?
w.launchCommand("git", "clone", "--mirror", "https://github.com/jenkinsci/git-client-plugin.git", clone.getAbsolutePath());
}
return clone.getPath();
}
}
throw new IllegalStateException();
}
/* JENKINS-33258 detected many calls to git rev-parse. This checks
* those calls are not being made. The createRevParseBranch call
* creates a branch whose name is unknown to the tests. This
* checks that the branch name is not mentioned in a call to
* git rev-parse.
*/
private void checkRevParseCalls(String branchName) {
String messages = StringUtils.join(handler.getMessages(), ";");
// Linux uses rev-parse without quotes
assertFalse("git rev-parse called: " + messages, handler.containsMessageSubstring("rev-parse " + branchName));
// Windows quotes the rev-parse argument
assertFalse("git rev-parse called: " + messages, handler.containsMessageSubstring("rev-parse \"" + branchName));
}
private void checkTimeout() {
List<Integer> timeouts = handler.getTimeouts();
if (expectedTimeouts == null) {
expectedTimeouts = new ArrayList<Integer>();
for (int i = 0; i < timeouts.size(); i++) {
expectedTimeouts.add(i, CliGitAPIImpl.TIMEOUT);
}
} else {
assertEquals("Wrong timeout count", expectedTimeouts.size(), timeouts.size());
timeouts = expectedTimeouts;
}
assertEquals("Wrong timeout", expectedTimeouts, timeouts);
}
protected abstract GitClient setupGitAPI(File ws) throws Exception;
@Override
protected void tearDown() throws Exception {
try {
temporaryDirectoryAllocator.dispose();
} catch (IOException e) {
e.printStackTrace(System.err);
}
try {
String messages = StringUtils.join(handler.getMessages(), ";");
assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED));
if (getTimeoutVisibleInCurrentTest()) {
checkTimeout();
}
if (revParseBranchName != null) {
checkRevParseCalls(revParseBranchName);
}
} finally {
handler.close();
}
}
private void check_remote_url(final String repositoryName) throws InterruptedException, IOException {
assertEquals("Wrong remote URL", localMirror(), w.git.getRemoteUrl(repositoryName));
String remotes = w.cmd("git remote -v");
assertTrue("remote URL has not been updated", remotes.contains(localMirror()));
}
private void assertBranchesExist(Set<Branch> branches, String ... names) throws InterruptedException {
Collection<String> branchNames = Collections2.transform(branches, new Function<Branch, String>() {
public String apply(Branch branch) {
return branch.getName();
}
});
for (String name : names) {
assertTrue(name + " branch not found in " + branchNames, branchNames.contains(name));
}
}
public void test_setAuthor() throws Exception {
final String authorName = "Test Author";
final String authorEmail = "jenkins@example.com";
w.init();
w.touch("file1", "Varying content " + java.util.UUID.randomUUID().toString());
w.git.add("file1");
w.git.setAuthor(authorName, authorEmail);
w.git.commit("Author was set explicitly on this commit");
List<String> revision = w.git.showRevision(w.head());
assertTrue("Wrong author in " + revision, revision.get(2).startsWith("author " + authorName + " <" + authorEmail +"> "));
}
public void test_setCommitter() throws Exception {
final String committerName = "Test Commiter";
final String committerEmail = "jenkins.plugin@example.com";
w.init();
w.touch("file1", "Varying content " + java.util.UUID.randomUUID().toString());
w.git.add("file1");
w.git.setCommitter(committerName, committerEmail);
w.git.commit("Committer was set explicitly on this commit");
List<String> revision = w.git.showRevision(w.head());
assertTrue("Wrong committer in " + revision, revision.get(3).startsWith("committer " + committerName + " <" + committerEmail + "> "));
}
private void setExpectedTimeoutWithAdjustedEnd(final int newTimeout) {
setExpectedTimeoutWithAdjustedEnd(newTimeout, 1);
}
private void setExpectedTimeoutWithAdjustedEnd(final int newTimeout, int adjustmentCount) {
if (getTimeoutVisibleInCurrentTest()) {
int size = handler.getTimeouts().size();
List<Integer> expected = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
expected.add(i, CliGitAPIImpl.TIMEOUT);
}
for (int i = 0; i < adjustmentCount; i++) {
expected.set(size - i - 1, newTimeout);
}
setExpectedTimeouts(expected);
}
}
/** Clone arguments include:
* repositoryName(String) - if omitted, CliGit does not set a remote repo name
* shallow() - no relevant assertion of success or failure of this argument
* shared() - not implemented on CliGit, not verified on JGit
* reference() - implemented on JGit, not verified on either JGit or CliGit
*
* CliGit and JGit both require the w.git.checkout() call
* otherwise no branch is checked out. That is different than the
* command line git program, but consistent within the git API.
*/
public void test_clone() throws IOException, InterruptedException
{
int newTimeout = 7;
w.git.clone_().timeout(newTimeout).url(localMirror()).repositoryName("origin").execute();
createRevParseBranch(); // Verify JENKINS-32258 is fixed
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertFalse("Alternates file found: " + alternates, w.exists(alternates));
setExpectedTimeoutWithAdjustedEnd(newTimeout);
}
public void test_clone_repositoryName() throws IOException, InterruptedException
{
w.git.clone_().url(localMirror()).repositoryName("upstream").execute();
w.git.checkout("upstream/master", "master");
check_remote_url("upstream");
assertBranchesExist(w.git.getBranches(), "master");
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertFalse("Alternates file found: " + alternates, w.exists(alternates));
}
public void test_clone_shallow() throws IOException, InterruptedException
{
w.git.clone_().url(localMirror()).repositoryName("origin").shallow().execute();
createRevParseBranch(); // Verify JENKINS-32258 is fixed
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertFalse("Alternates file found: " + alternates, w.exists(alternates));
}
public void test_clone_shallow_with_depth() throws IOException, InterruptedException
{
w.git.clone_().url(localMirror()).repositoryName("origin").shallow().depth(2).execute();
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertFalse("Alternates file found: " + alternates, w.exists(alternates));
}
public void test_clone_shared() throws IOException, InterruptedException
{
w.git.clone_().url(localMirror()).repositoryName("origin").shared().execute();
createRevParseBranch(); // Verify JENKINS-32258 is fixed
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
assertAlternateFilePointsToLocalMirror();
assertNoObjectsInRepository();
}
public void test_clone_reference() throws IOException, InterruptedException
{
w.git.clone_().url(localMirror()).repositoryName("origin").reference(localMirror()).execute();
createRevParseBranch(); // Verify JENKINS-32258 is fixed
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
assertAlternateFilePointsToLocalMirror();
assertNoObjectsInRepository();
}
private void assertNoObjectsInRepository() {
List<String> objectsDir = new ArrayList<String>(Arrays.asList(w.file(".git/objects").list()));
objectsDir.remove("info");
objectsDir.remove("pack");
assertTrue("Objects directory must not contain anything but 'info' and 'pack' folders", objectsDir.isEmpty());
File packDir = w.file(".git/objects/pack");
if (packDir.isDirectory()) {
assertEquals("Pack dir must noct contain anything", 0, packDir.list().length);
}
}
private void assertAlternateFilePointsToLocalMirror() throws IOException, InterruptedException {
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertTrue("Alternates file not found: " + alternates, w.exists(alternates));
final String expectedContent = localMirror().replace("\\", "/") + "/objects";
final String actualContent = w.contentOf(alternates);
assertEquals("Alternates file wrong content", expectedContent, actualContent);
final File alternatesDir = new File(actualContent);
assertTrue("Alternates destination " + actualContent + " missing", alternatesDir.isDirectory());
}
public void test_clone_reference_working_repo() throws IOException, InterruptedException
{
assertTrue("SRC_DIR " + SRC_DIR + " has no .git subdir", (new File(SRC_DIR + File.separator + ".git").isDirectory()));
w.git.clone_().url(localMirror()).repositoryName("origin").reference(SRC_DIR).execute();
w.git.checkout("origin/master", "master");
check_remote_url("origin");
assertBranchesExist(w.git.getBranches(), "master");
final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates";
assertTrue("Alternates file not found: " + alternates, w.exists(alternates));
final String expectedContent = SRC_DIR.replace("\\", "/") + "/.git/objects";
final String actualContent = w.contentOf(alternates);
assertEquals("Alternates file wrong content", expectedContent, actualContent);
final File alternatesDir = new File(actualContent);
assertTrue("Alternates destination " + actualContent + " missing", alternatesDir.isDirectory());
}
public void test_clone_refspec() throws Exception {
w.git.clone_().url(localMirror()).repositoryName("origin").execute();
final WorkingArea w2 = new WorkingArea();
w2.launchCommand("git", "clone", localMirror(), "./");
w2.git.withRepository(new RepositoryCallback<Void>() {
public Void invoke(final Repository realRepo, VirtualChannel channel) throws IOException, InterruptedException {
return w.git.withRepository(new RepositoryCallback<Void>() {
public Void invoke(final Repository implRepo, VirtualChannel channel) {
final String realRefspec = realRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
final String implRefspec = implRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
assertEquals("Refspec not as git-clone", realRefspec, implRefspec);
return null;
}
});
}
});
}
public void test_clone_refspecs() throws Exception {
List<RefSpec> refspecs = Lists.newArrayList(
new RefSpec("+refs/heads/master:refs/remotes/origin/master"),
new RefSpec("+refs/heads/1.4.x:refs/remotes/origin/1.4.x")
);
w.git.clone_().url(localMirror()).refspecs(refspecs).repositoryName("origin").execute();
w.git.withRepository(new RepositoryCallback<Void>() {
public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException {
String[] fetchRefSpecs = repo.getConfig().getStringList(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
assertEquals("Expected 2 refspecs", 2, fetchRefSpecs.length);
assertEquals("Incorrect refspec 1", "+refs/heads/master:refs/remotes/origin/master", fetchRefSpecs[0]);
assertEquals("Incorrect refspec 2", "+refs/heads/1.4.x:refs/remotes/origin/1.4.x", fetchRefSpecs[1]);
return null;
}});
Set<Branch> remoteBranches = w.git.getRemoteBranches();
assertBranchesExist(remoteBranches, "origin/master");
assertBranchesExist(remoteBranches, "origin/1.4.x");
assertEquals(2, remoteBranches.size());
}
public void test_detect_commit_in_repo() throws Exception {
w.init();
assertFalse(w.git.isCommitInRepo(null)); // NPE safety check
w.touch("file1");
w.git.add("file1");
w.git.commit("commit1");
assertTrue("HEAD commit not found", w.git.isCommitInRepo(w.head()));
// this MAY fail if commit has this exact sha1, but please admit this would be unlucky
assertFalse(w.git.isCommitInRepo(ObjectId.fromString("1111111111111111111111111111111111111111")));
assertFalse(w.git.isCommitInRepo(null)); // NPE safety check
}
@Deprecated
public void test_lsTree_non_recursive() throws IOException, InterruptedException {
w.init();
w.touch("file1", "file1 fixed content");
w.git.add("file1");
w.git.commit("commit1");
String expectedBlobSHA1 = "3f5a898e0c8ea62362dbf359cf1a400f3cfd46ae";
List<IndexEntry> tree = w.igit().lsTree("HEAD", false);
assertEquals("Wrong blob sha1", expectedBlobSHA1, tree.get(0).getObject());
assertEquals("Wrong number of tree entries", 1, tree.size());
final String remoteUrl = localMirror();
w.igit().setRemoteUrl("origin", remoteUrl, w.repoPath() + File.separator + ".git");
assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin"));
assertEquals("Wrong invalid default remote", "origin", w.igit().getDefaultRemote("invalid"));
}
@Deprecated
public void test_lsTree_recursive() throws IOException, InterruptedException {
w.init();
assertTrue("mkdir dir1 failed", w.file("dir1").mkdir());
w.touch("dir1/file1", "dir1/file1 fixed content");
w.git.add("dir1/file1");
w.touch("file2", "file2 fixed content");
w.git.add("file2");
w.git.commit("commit-dir-and-file");
String expectedBlob1SHA1 = "a3ee484019f0576fcdeb48e682fa1058d0c74435";
String expectedBlob2SHA1 = "aa1b259ac5e8d6cfdfcf4155a9ff6836b048d0ad";
List<IndexEntry> tree = w.igit().lsTree("HEAD", true);
assertEquals("Wrong blob 1 sha1", expectedBlob1SHA1, tree.get(0).getObject());
assertEquals("Wrong blob 2 sha1", expectedBlob2SHA1, tree.get(1).getObject());
assertEquals("Wrong number of tree entries", 2, tree.size());
final String remoteUrl = "https://github.com/jenkinsci/git-client-plugin.git";
w.git.setRemoteUrl("origin", remoteUrl);
assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin"));
assertEquals("Wrong invalid default remote", "origin", w.igit().getDefaultRemote("invalid"));
}
@Deprecated
public void test_getRemoteURL_two_args() throws Exception {
w.init();
String originUrl = "https://github.com/bogus/bogus.git";
w.git.setRemoteUrl("origin", originUrl);
assertEquals("Wrong remote URL", originUrl, w.git.getRemoteUrl("origin"));
assertEquals("Wrong null remote URL", originUrl, w.igit().getRemoteUrl("origin", null));
assertEquals("Wrong blank remote URL", originUrl, w.igit().getRemoteUrl("origin", ""));
if (w.igit() instanceof CliGitAPIImpl) {
String gitDir = w.repoPath() + File.separator + ".git";
assertEquals("Wrong repoPath/.git remote URL for " + gitDir, originUrl, w.igit().getRemoteUrl("origin", gitDir));
assertEquals("Wrong .git remote URL", originUrl, w.igit().getRemoteUrl("origin", ".git"));
} else {
assertEquals("Wrong repoPath remote URL", originUrl, w.igit().getRemoteUrl("origin", w.repoPath()));
}
// Fails on both JGit and CliGit, though with different failure modes in each
// assertEquals("Wrong . remote URL", originUrl, w.igit().getRemoteUrl("origin", "."));
}
@Deprecated
public void test_getDefaultRemote() throws Exception {
w.init();
w.cmd("git remote add origin https://github.com/jenkinsci/git-client-plugin.git");
w.cmd("git remote add ndeloof git@github.com:ndeloof/git-client-plugin.git");
assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin"));
assertEquals("Wrong ndeloof default remote", "ndeloof", w.igit().getDefaultRemote("ndeloof"));
/* CliGitAPIImpl and JGitAPIImpl return different ordered lists for default remote if invalid */
assertEquals("Wrong invalid default remote", w.git instanceof CliGitAPIImpl ? "ndeloof" : "origin",
w.igit().getDefaultRemote("invalid"));
}
public void test_getRemoteURL() throws Exception {
w.init();
w.cmd("git remote add origin https://github.com/jenkinsci/git-client-plugin.git");
w.cmd("git remote add ndeloof git@github.com:ndeloof/git-client-plugin.git");
String remoteUrl = w.git.getRemoteUrl("origin");
assertEquals("unexepected remote URL " + remoteUrl, "https://github.com/jenkinsci/git-client-plugin.git", remoteUrl);
}
public void test_getRemoteURL_local_clone() throws Exception {
w = clone(localMirror());
assertEquals("Wrong origin URL", localMirror(), w.git.getRemoteUrl("origin"));
String remotes = w.cmd("git remote -v");
assertTrue("remote URL has not been updated", remotes.contains(localMirror()));
}
public void test_setRemoteURL() throws Exception {
w.init();
w.cmd("git remote add origin https://github.com/jenkinsci/git-client-plugin.git");
w.git.setRemoteUrl("origin", "git@github.com:ndeloof/git-client-plugin.git");
String remotes = w.cmd("git remote -v");
assertTrue("remote URL has not been updated", remotes.contains("git@github.com:ndeloof/git-client-plugin.git"));
}
public void test_setRemoteURL_local_clone() throws Exception {
w = clone(localMirror());
String originURL = "https://github.com/jenkinsci/git-client-plugin.git";
w.git.setRemoteUrl("origin", originURL);
assertEquals("Wrong origin URL", originURL, w.git.getRemoteUrl("origin"));
String remotes = w.cmd("git remote -v");
assertTrue("remote URL has not been updated", remotes.contains(originURL));
}
public void test_addRemoteUrl_local_clone() throws Exception {
w = clone(localMirror());
assertEquals("Wrong origin URL before add", localMirror(), w.git.getRemoteUrl("origin"));
String upstreamURL = "https://github.com/jenkinsci/git-client-plugin.git";
w.git.addRemoteUrl("upstream", upstreamURL);
assertEquals("Wrong upstream URL", upstreamURL, w.git.getRemoteUrl("upstream"));
assertEquals("Wrong origin URL after add", localMirror(), w.git.getRemoteUrl("origin"));
}
@Bug(20410)
public void test_clean() throws Exception {
w.init();
w.commitEmpty("init");
/* String starts with a surrogate character, mathematical
* double struck small t as the first character of the file
* name. The last three characters of the file name are three
* different forms of the a-with-ring character. Refer to
* http://unicode.org/reports/tr15/#Detecting_Normalization_Forms
* for the source of those example characters.
*/
String fileName = "\uD835\uDD65-\u5c4f\u5e55\u622a\u56fe-\u0041\u030a-\u00c5-\u212b-fileName.xml";
w.touch(fileName, "content " + fileName);
w.git.add(fileName);
w.git.commit(fileName);
/* JENKINS-27910 reported that certain cyrillic file names
* failed to delete if the encoding was not UTF-8.
*/
String fileNameSwim = "\u00d0\u00bf\u00d0\u00bb\u00d0\u00b0\u00d0\u00b2\u00d0\u00b0\u00d0\u00bd\u00d0\u00b8\u00d0\u00b5-swim.png";
w.touch(fileNameSwim, "content " + fileNameSwim);
w.git.add(fileNameSwim);
w.git.commit(fileNameSwim);
String fileNameFace = "\u00d0\u00bb\u00d0\u00b8\u00d1\u2020\u00d0\u00be-face.png";
w.touch(fileNameFace, "content " + fileNameFace);
w.git.add(fileNameFace);
w.git.commit(fileNameFace);
w.touch(".gitignore", ".test");
w.git.add(".gitignore");
w.git.commit("ignore");
String dirName1 = "\u5c4f\u5e55\u622a\u56fe-dir-not-added";
String fileName1 = dirName1 + File.separator + "\u5c4f\u5e55\u622a\u56fe-fileName1-not-added.xml";
String fileName2 = ".test-\u00f8\u00e4\u00fc\u00f6-fileName2-not-added";
assertTrue("Did not create dir " + dirName1, w.file(dirName1).mkdir());
w.touch(fileName1);
w.touch(fileName2);
w.touch(fileName, "new content");
w.git.clean();
assertFalse(w.exists(dirName1));
assertFalse(w.exists(fileName1));
assertFalse(w.exists(fileName2));
assertEquals("content " + fileName, w.contentOf(fileName));
assertEquals("content " + fileNameFace, w.contentOf(fileNameFace));
assertEquals("content " + fileNameSwim, w.contentOf(fileNameSwim));
String status = w.cmd("git status");
assertTrue("unexpected status " + status, status.contains("working directory clean"));
/* A few poorly placed tests of hudson.FilePath - testing JENKINS-22434 */
FilePath fp = new FilePath(w.file(fileName));
assertTrue(fp + " missing", fp.exists());
assertTrue("mkdir " + dirName1 + " failed", w.file(dirName1).mkdir());
assertTrue("dir " + dirName1 + " missing", w.file(dirName1).isDirectory());
FilePath dir1 = new FilePath(w.file(dirName1));
w.touch(fileName1);
assertTrue("Did not create file " + fileName1, w.file(fileName1).exists());
assertTrue(dir1 + " missing", dir1.exists());
dir1.deleteRecursive(); /* Fails on Linux JDK 7 with LANG=C, ok with LANG=en_US.UTF-8 */
/* Java reports "Malformed input or input contains unmappable chacraters" */
assertFalse("Did not delete file " + fileName1, w.file(fileName1).exists());
assertFalse(dir1 + " not deleted", dir1.exists());
w.touch(fileName2);
FilePath fp2 = new FilePath(w.file(fileName2));
assertTrue(fp2 + " missing", fp2.exists());
fp2.delete();
assertFalse(fp2 + " not deleted", fp2.exists());
String dirContents = Arrays.toString((new File(w.repoPath())).listFiles());
String finalStatus = w.cmd("git status");
assertTrue("unexpected final status " + finalStatus + " dir contents: " + dirContents, finalStatus.contains("working directory clean"));
}
public void test_fetch() throws Exception {
/* Create a working repo containing a commit */
w.init();
w.touch("file1", "file1 content " + java.util.UUID.randomUUID().toString());
w.git.add("file1");
w.git.commit("commit1");
ObjectId commit1 = w.head();
/* Clone working repo into a bare repo */
WorkingArea bare = new WorkingArea();
bare.init(true);
w.git.setRemoteUrl("origin", bare.repoPath());
Set<Branch> remoteBranchesEmpty = w.git.getRemoteBranches();
assertEquals("Unexpected branch count", 0, remoteBranchesEmpty.size());
w.git.push("origin", "master");
ObjectId bareCommit1 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare != working", commit1, bareCommit1);
assertEquals(commit1, bare.git.getHeadRev(bare.repoPath(), "refs/heads/master"));
/* Clone new working repo from bare repo */
WorkingArea newArea = clone(bare.repoPath());
ObjectId newAreaHead = newArea.head();
assertEquals("bare != newArea", bareCommit1, newAreaHead);
Set<Branch> remoteBranches1 = newArea.git.getRemoteBranches();
assertEquals("Unexpected branch count in " + remoteBranches1, 2, remoteBranches1.size());
assertEquals(bareCommit1, newArea.git.getHeadRev(newArea.repoPath(), "refs/heads/master"));
/* Commit a new change to the original repo */
w.touch("file2", "file2 content " + java.util.UUID.randomUUID().toString());
w.git.add("file2");
w.git.commit("commit2");
ObjectId commit2 = w.head();
assertEquals(commit2, w.git.getHeadRev(w.repoPath(), "refs/heads/master"));
/* Push the new change to the bare repo */
w.git.push("origin", "master");
ObjectId bareCommit2 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare2 != working2", commit2, bareCommit2);
assertEquals(commit2, bare.git.getHeadRev(bare.repoPath(), "refs/heads/master"));
/* Fetch new change into newArea repo */
RefSpec defaultRefSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
List<RefSpec> refSpecs = new ArrayList<RefSpec>();
refSpecs.add(defaultRefSpec);
newArea.git.fetch(new URIish(bare.repo.toString()), refSpecs);
/* Confirm the fetch did not alter working branch */
assertEquals("beforeMerge != commit1", commit1, newArea.head());
/* Merge the fetch results into working branch */
newArea.git.merge().setRevisionToMerge(bareCommit2).execute();
assertEquals("bare2 != newArea2", bareCommit2, newArea.head());
/* Commit a new change to the original repo */
w.touch("file3", "file3 content " + java.util.UUID.randomUUID().toString());
w.git.add("file3");
w.git.commit("commit3");
ObjectId commit3 = w.head();
/* Push the new change to the bare repo */
w.git.push("origin", "master");
ObjectId bareCommit3 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare3 != working3", commit3, bareCommit3);
/* Fetch new change into newArea repo using different argument forms */
newArea.git.fetch(null, defaultRefSpec);
newArea.git.fetch(null, defaultRefSpec, defaultRefSpec);
/* Merge the fetch results into working branch */
newArea.git.merge().setRevisionToMerge(bareCommit3).execute();
assertEquals("bare3 != newArea3", bareCommit3, newArea.head());
/* Commit a new change to the original repo */
w.touch("file4", "file4 content " + java.util.UUID.randomUUID().toString());
w.git.add("file4");
w.git.commit("commit4");
ObjectId commit4 = w.head();
/* Push the new change to the bare repo */
w.git.push("origin", "master");
ObjectId bareCommit4 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare4 != working4", commit4, bareCommit4);
/* Fetch new change into newArea repo using a different argument form */
RefSpec [] refSpecArray = { defaultRefSpec, defaultRefSpec };
newArea.git.fetch("origin", refSpecArray);
/* Merge the fetch results into working branch */
newArea.git.merge().setRevisionToMerge(bareCommit4).execute();
assertEquals("bare4 != newArea4", bareCommit4, newArea.head());
/* Commit a new change to the original repo */
w.touch("file5", "file5 content " + java.util.UUID.randomUUID().toString());
w.git.add("file5");
w.git.commit("commit5");
ObjectId commit5 = w.head();
/* Push the new change to the bare repo */
w.git.push("origin", "master");
ObjectId bareCommit5 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare5 != working5", commit5, bareCommit5);
/* Fetch into newArea repo with null RefSpec - should only
* pull tags, not commits in git versions prior to git 1.9.0.
* In git 1.9.0, fetch -t pulls tags and versions. */
newArea.git.fetch("origin", null, null);
assertEquals("null refSpec fetch modified local repo", bareCommit4, newArea.head());
ObjectId expectedHead = bareCommit4;
try {
/* Assert that change did not arrive in repo if git
* command line less than 1.9. Assert that change arrives in
* repo if git command line 1.9 or later. */
newArea.git.merge().setRevisionToMerge(bareCommit5).execute();
assertTrue("JGit should not have copied the revision", newArea.git instanceof CliGitAPIImpl);
assertTrue("Wrong git version", w.cgit().isAtLeastVersion(1, 9, 0, 0));
expectedHead = bareCommit5;
} catch (org.eclipse.jgit.api.errors.JGitInternalException je) {
String expectedSubString = "Missing commit " + bareCommit5.name();
assertTrue("Wrong message :" + je.getMessage(), je.getMessage().contains(expectedSubString));
} catch (GitException ge) {
assertTrue("Wrong message :" + ge.getMessage(), ge.getMessage().contains("Could not merge"));
assertTrue("Wrong message :" + ge.getMessage(), ge.getMessage().contains(bareCommit5.name()));
}
/* Assert that expected change is in repo after merge. With
* git 1.7 and 1.8, it should be bareCommit4. With git 1.9
* and later, it should be bareCommit5. */
assertEquals("null refSpec fetch modified local repo", expectedHead, newArea.head());
try {
/* Fetch into newArea repo with invalid repo name and no RefSpec */
newArea.git.fetch("invalid-remote-name");
fail("Should have thrown an exception");
} catch (GitException ge) {
assertTrue("Wrong message :" + ge.getMessage(), ge.getMessage().contains("invalid-remote-name"));
}
}
public void test_push_tags() throws Exception {
/* Create a working repo containing a commit */
w.init();
w.touch("file1", "file1 content " + java.util.UUID.randomUUID().toString());
w.git.add("file1");
w.git.commit("commit1");
ObjectId commit1 = w.head();
/* Clone working repo into a bare repo */
WorkingArea bare = new WorkingArea();
bare.init(true);
w.git.setRemoteUrl("origin", bare.repoPath());
Set<Branch> remoteBranchesEmpty = w.git.getRemoteBranches();
assertEquals("Unexpected branch count", 0, remoteBranchesEmpty.size());
w.git.push("origin", "master");
ObjectId bareCommit1 = bare.git.getHeadRev(bare.repoPath(), "master");
assertEquals("bare != working", commit1, bareCommit1);
assertEquals(commit1, bare.git.getHeadRev(bare.repoPath(), "refs/heads/master"));
/* Add tag to working repo and without pushing it to the bare repo */
w.tag("tag1");
assertTrue("tag1 wasn't created", w.git.tagExists("tag1"));
w.git.push().ref("master").to(new URIish(bare.repoPath())).tags(false).execute();
assertFalse("tag1 wasn't pushed", bare.cmd("git tag").contains("tag1"));
/* Add tag to working repo without pushing it to the bare
* repo, tests the default behavior when tags() is not added
* to PushCommand.
*/
w.tag("tag3");
assertTrue("tag3 wasn't created", w.git.tagExists("tag3"));
w.git.push().ref("master").to(new URIish(bare.repoPath())).execute();
assertFalse("tag3 was pushed", bare.cmd("git tag").contains("tag3"));
/* Add another tag to working repo and push tags to the bare repo */
w.touch("file2", "file2 content " + java.util.UUID.randomUUID().toString());
w.git.add("file2");