-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GitSCM.java
2193 lines (1907 loc) · 90.4 KB
/
GitSCM.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 hudson.plugins.git;
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.google.common.collect.Iterables;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.init.Initializer;
import hudson.model.*;
import hudson.model.Descriptor.FormException;
import hudson.plugins.git.browser.GitRepositoryBrowser;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import hudson.plugins.git.extensions.impl.AuthorInChangelog;
import hudson.plugins.git.extensions.impl.BuildChooserSetting;
import hudson.plugins.git.extensions.impl.BuildSingleRevisionOnly;
import hudson.plugins.git.extensions.impl.ChangelogToBranch;
import hudson.plugins.git.extensions.impl.CloneOption;
import hudson.plugins.git.extensions.impl.PathRestriction;
import hudson.plugins.git.extensions.impl.LocalBranch;
import hudson.plugins.git.extensions.impl.RelativeTargetDirectory;
import hudson.plugins.git.extensions.impl.PreBuildMerge;
import hudson.plugins.git.opt.PreBuildMergeOptions;
import hudson.plugins.git.util.Build;
import hudson.plugins.git.util.*;
import hudson.remoting.Channel;
import hudson.scm.AbstractScmTagAction;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.security.Permission;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import jenkins.plugins.git.GitHooksConfiguration;
import jenkins.plugins.git.GitSCMMatrixUtil;
import jenkins.plugins.git.GitToolChooser;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.plugins.gitclient.*;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.collect.Lists.newArrayList;
import static hudson.init.InitMilestone.JOB_LOADED;
import static hudson.init.InitMilestone.PLUGINS_STARTED;
import hudson.plugins.git.browser.BitbucketWeb;
import hudson.plugins.git.browser.GitLab;
import hudson.plugins.git.browser.GithubWeb;
import static hudson.scm.PollingResult.*;
import hudson.Util;
import hudson.plugins.git.extensions.impl.ScmName;
import hudson.util.LogTaskListener;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* Git SCM.
*
* @author Nigel Magnay
* @author Andrew Bayer
* @author Nicolas Deloof
* @author Kohsuke Kawaguchi
* ... and many others
*/
public class GitSCM extends GitSCMBackwardCompatibility {
static final String ALLOW_LOCAL_CHECKOUT_PROPERTY = GitSCM.class.getName() + ".ALLOW_LOCAL_CHECKOUT";
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL")
public static /* not final */ boolean ALLOW_LOCAL_CHECKOUT =
SystemProperties.getBoolean(ALLOW_LOCAL_CHECKOUT_PROPERTY);
/**
* Store a config version so we're able to migrate config on various
* functionality upgrades.
*/
private Long configVersion;
/**
* All the remote repositories that we know about.
*/
private List<UserRemoteConfig> userRemoteConfigs;
private transient List<RemoteConfig> remoteRepositories;
/**
* All the branches that we wish to care about building.
*/
private List<BranchSpec> branches;
private boolean doGenerateSubmoduleConfigurations = false;
@CheckForNull
public String gitTool;
@CheckForNull
private GitRepositoryBrowser browser;
private Collection<SubmoduleConfig> submoduleCfg = Collections.emptyList();
public static final String GIT_BRANCH = "GIT_BRANCH";
public static final String GIT_LOCAL_BRANCH = "GIT_LOCAL_BRANCH";
public static final String GIT_CHECKOUT_DIR = "GIT_CHECKOUT_DIR";
public static final String GIT_COMMIT = "GIT_COMMIT";
public static final String GIT_PREVIOUS_COMMIT = "GIT_PREVIOUS_COMMIT";
public static final String GIT_PREVIOUS_SUCCESSFUL_COMMIT = "GIT_PREVIOUS_SUCCESSFUL_COMMIT";
public static final String GIT_URL = "GIT_URL";
/**
* All the configured extensions attached to this.
*/
@SuppressFBWarnings(value="SE_BAD_FIELD", justification="Known non-serializable field")
private DescribableList<GitSCMExtension,GitSCMExtensionDescriptor> extensions;
@Whitelisted
@Deprecated
public Collection<SubmoduleConfig> getSubmoduleCfg() {
return submoduleCfg;
}
@DataBoundSetter
public void setSubmoduleCfg(Collection<SubmoduleConfig> submoduleCfg) {
}
public static List<UserRemoteConfig> createRepoList(String url, String credentialsId) {
List<UserRemoteConfig> repoList = new ArrayList<>();
repoList.add(new UserRemoteConfig(url, null, null, credentialsId));
return repoList;
}
/**
* A convenience constructor that sets everything to default.
*
* @param repositoryUrl git repository URL
* Repository URL to clone from.
*/
public GitSCM(String repositoryUrl) {
this(
createRepoList(repositoryUrl, null),
Collections.singletonList(new BranchSpec("")),
null, null, Collections.emptyList());
}
@Deprecated
public GitSCM(
List<UserRemoteConfig> userRemoteConfigs,
List<BranchSpec> branches,
Boolean doGenerateSubmoduleConfigurations,
Collection<SubmoduleConfig> submoduleCfg,
@CheckForNull GitRepositoryBrowser browser,
@CheckForNull String gitTool,
List<GitSCMExtension> extensions) {
this(userRemoteConfigs, branches, browser, gitTool, extensions);
}
@DataBoundConstructor
public GitSCM(
List<UserRemoteConfig> userRemoteConfigs,
List<BranchSpec> branches,
@CheckForNull GitRepositoryBrowser browser,
@CheckForNull String gitTool,
List<GitSCMExtension> extensions) {
// moved from createBranches
this.branches = isEmpty(branches) ? newArrayList(new BranchSpec("*/master")) : branches;
this.userRemoteConfigs = userRemoteConfigs;
updateFromUserData();
this.browser = browser;
this.configVersion = 2L;
this.gitTool = gitTool;
this.extensions = new DescribableList<>(Saveable.NOOP,Util.fixNull(extensions));
getBuildChooser(); // set the gitSCM field.
}
/**
* All the configured extensions attached to this {@link GitSCM}.
*
* Going forward this is primarily how we'll support esoteric use cases.
*
* @since 2.0
*/
@Whitelisted
public DescribableList<GitSCMExtension, GitSCMExtensionDescriptor> getExtensions() {
return extensions;
}
private void updateFromUserData() throws GitException {
// do what newInstance used to do directly from the request data
if (userRemoteConfigs == null) {
return; /* Prevent NPE when no remote config defined */
}
try {
String[] pUrls = new String[userRemoteConfigs.size()];
String[] repoNames = new String[userRemoteConfigs.size()];
String[] refSpecs = new String[userRemoteConfigs.size()];
for (int i = 0; i < userRemoteConfigs.size(); ++i) {
pUrls[i] = userRemoteConfigs.get(i).getUrl();
repoNames[i] = userRemoteConfigs.get(i).getName();
refSpecs[i] = userRemoteConfigs.get(i).getRefspec();
}
this.remoteRepositories = DescriptorImpl.createRepositoryConfigurations(pUrls, repoNames, refSpecs);
// TODO: replace with new repositories
} catch (IOException e1) {
throw new GitException("Error creating repositories", e1);
}
}
@SuppressWarnings("deprecation") // `source` field is deprecated but required
public Object readResolve() throws IOException {
// Migrate data
// Default unspecified to v0
if (configVersion == null) {
configVersion = 0L;
}
// Deprecated field needed to retain compatibility
if (source != null) {
remoteRepositories = new ArrayList<>();
branches = new ArrayList<>();
List<RefSpec> rs = new ArrayList<>();
rs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
remoteRepositories.add(newRemoteConfig("origin", source, rs.toArray(new RefSpec[0])));
if (branch != null) {
branches.add(new BranchSpec(branch));
} else {
branches.add(new BranchSpec("*/master"));
}
}
if (configVersion < 1 && branches != null) {
// Migrate the branch specs from
// single * wildcard, to ** wildcard.
for (BranchSpec branchSpec : branches) {
String name = branchSpec.getName();
name = name.replace("*", "**");
branchSpec.setName(name);
}
}
if (remoteRepositories != null && userRemoteConfigs == null) {
userRemoteConfigs = new ArrayList<>();
for(RemoteConfig cfg : remoteRepositories) {
// converted as in config.jelly
String url = "";
if (cfg.getURIs().size() > 0 && cfg.getURIs().get(0) != null)
url = cfg.getURIs().get(0).toPrivateString();
String refspec = "";
if (cfg.getFetchRefSpecs().size() > 0 && cfg.getFetchRefSpecs().get(0) != null)
refspec = cfg.getFetchRefSpecs().get(0).toString();
userRemoteConfigs.add(new UserRemoteConfig(url, cfg.getName(), refspec, null));
}
}
// patch internal objects from user data
// if (configVersion == 2) {
if (remoteRepositories == null) {
// if we don't catch GitException here, the whole job fails to load
try {
updateFromUserData();
} catch (GitException e) {
LOGGER.log(Level.WARNING, "Failed to load SCM data", e);
}
}
if (extensions==null)
extensions = new DescribableList<>(Saveable.NOOP);
readBackExtensionsFromLegacy();
if (choosingStrategy != null && getBuildChooser().getClass()==DefaultBuildChooser.class) {
for (BuildChooserDescriptor d : BuildChooser.all()) {
if (choosingStrategy.equals(d.getLegacyId())) {
try {
setBuildChooser(d.clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
LOGGER.log(Level.WARNING, "Failed to instantiate the build chooser", e);
}
}
}
}
getBuildChooser(); // set the gitSCM field.
return this;
}
@Override
@Whitelisted
public GitRepositoryBrowser getBrowser() {
return browser;
}
public void setBrowser(GitRepositoryBrowser browser) {
this.browser = browser;
}
private static final String HOSTNAME_MATCH
= "([\\w\\d[-.]]+)" // hostname
;
private static final String REPOSITORY_PATH_MATCH
= "/*" // Zero or more slashes as start of repository path
+ "(.+?)" // repository path without leading slashes
+ "(?:[.]git)?" // optional '.git' suffix
+ "/*" // optional trailing '/'
;
private static final Pattern[] URL_PATTERNS = {
/* URL style - like https://github.com/jenkinsci/git-plugin */
Pattern.compile(
"(?:\\w+://)" // protocol (scheme)
+ "(?:.+@)?" // optional username/password
+ HOSTNAME_MATCH
+ "(?:[:][\\d]+)?" // optional port number (only honored by git for ssh:// scheme)
+ "/" // separator between hostname and repository path - '/'
+ REPOSITORY_PATH_MATCH
),
/* Alternate ssh style - like git@github.com:jenkinsci/git-plugin */
Pattern.compile(
"(?:git@)" // required username (only optional if local username is 'git')
+ HOSTNAME_MATCH
+ ":" // separator between hostname and repository path - ':'
+ REPOSITORY_PATH_MATCH
)
};
@Override public RepositoryBrowser<?> guessBrowser() {
Set<String> webUrls = new HashSet<>();
if (remoteRepositories != null) {
for (RemoteConfig config : remoteRepositories) {
for (URIish uriIsh : config.getURIs()) {
String uri = uriIsh.toString();
for (Pattern p : URL_PATTERNS) {
Matcher m = p.matcher(uri);
if (m.matches()) {
webUrls.add("https://" + m.group(1) + "/" + m.group(2) + "/");
}
}
}
}
}
if (webUrls.isEmpty()) {
return null;
}
if (webUrls.size() == 1) {
String url = webUrls.iterator().next();
if (url.startsWith("https://bitbucket.org/")) {
return new BitbucketWeb(url);
}
if (url.startsWith("https://gitlab.com/")) {
return new GitLab(url);
}
if (url.startsWith("https://github.com/")) {
return new GithubWeb(url);
}
return null;
}
LOGGER.log(Level.INFO, "Multiple browser guess matches for {0}", remoteRepositories);
return null;
}
public boolean isCreateAccountBasedOnEmail() {
DescriptorImpl gitDescriptor = getDescriptor();
return (gitDescriptor != null && gitDescriptor.isCreateAccountBasedOnEmail());
}
public boolean isUseExistingAccountWithSameEmail() {
DescriptorImpl gitDescriptor = getDescriptor();
return (gitDescriptor != null && gitDescriptor.isUseExistingAccountWithSameEmail());
}
public boolean isHideCredentials() {
DescriptorImpl gitDescriptor = getDescriptor();
return gitDescriptor != null && gitDescriptor.isHideCredentials();
}
public boolean isAllowSecondFetch() {
DescriptorImpl gitDescriptor = getDescriptor();
return (gitDescriptor != null && gitDescriptor.isAllowSecondFetch());
}
public boolean isDisableGitToolChooser() {
DescriptorImpl gitDescriptor = getDescriptor();
return (gitDescriptor != null && gitDescriptor.isDisableGitToolChooser());
}
public boolean isAddGitTagAction() {
DescriptorImpl gitDescriptor = getDescriptor();
return (gitDescriptor != null && gitDescriptor.isAddGitTagAction());
}
@Whitelisted
public BuildChooser getBuildChooser() {
BuildChooser bc;
BuildChooserSetting bcs = getExtensions().get(BuildChooserSetting.class);
if (bcs!=null) bc = bcs.getBuildChooser();
else bc = new DefaultBuildChooser();
bc.gitSCM = this;
return bc;
}
public void setBuildChooser(BuildChooser buildChooser) throws IOException {
if (buildChooser.getClass()==DefaultBuildChooser.class) {
getExtensions().remove(BuildChooserSetting.class);
} else {
getExtensions().replace(new BuildChooserSetting(buildChooser));
}
}
@Deprecated
public String getParamLocalBranch(Run<?, ?> build) throws IOException, InterruptedException {
return getParamLocalBranch(build, new LogTaskListener(LOGGER, Level.INFO));
}
/**
* Gets the parameter-expanded effective value in the context of the current build.
* @param build run whose local branch name is returned
* @param listener build log
* @throws IOException on input or output error
* @throws InterruptedException when interrupted
* @return parameter-expanded local branch name in build.
*/
public String getParamLocalBranch(Run<?, ?> build, TaskListener listener) throws IOException, InterruptedException {
LocalBranch localBranch = getExtensions().get(LocalBranch.class);
// substitute build parameters if available
return getParameterString(localBranch == null ? null : localBranch.getLocalBranch(), build.getEnvironment(listener));
}
@Deprecated
public List<RemoteConfig> getParamExpandedRepos(Run<?, ?> build) throws IOException, InterruptedException {
return getParamExpandedRepos(build, new LogTaskListener(LOGGER, Level.INFO));
}
/**
* Expand parameters in {@link #remoteRepositories} with the parameter values provided in the given build
* and return them.
*
* @param build run whose local branch name is returned
* @param listener build log
* @throws IOException on input or output error
* @throws InterruptedException when interrupted
* @return can be empty but never null.
*/
public List<RemoteConfig> getParamExpandedRepos(Run<?, ?> build, TaskListener listener) throws IOException, InterruptedException {
List<RemoteConfig> expandedRepos = new ArrayList<>();
EnvVars env = build.getEnvironment(listener);
for (RemoteConfig oldRepo : Util.fixNull(remoteRepositories)) {
expandedRepos.add(getParamExpandedRepo(env, oldRepo));
}
return expandedRepos;
}
/**
* Expand Parameters in the supplied remote repository with the parameter values provided in the given environment variables
* @param env Environment variables with parameter values
* @param remoteRepository Remote repository with parameters
* @return remote repository with expanded parameters
*/
public RemoteConfig getParamExpandedRepo(EnvVars env, RemoteConfig remoteRepository) {
List<RefSpec> refSpecs = getRefSpecs(remoteRepository, env);
return newRemoteConfig(
getParameterString(remoteRepository.getName(), env),
getParameterString(remoteRepository.getURIs().get(0).toPrivateString(), env),
refSpecs.toArray(new RefSpec[0]));
}
public RemoteConfig getRepositoryByName(String repoName) {
for (RemoteConfig r : getRepositories()) {
if (r.getName().equals(repoName)) {
return r;
}
}
return null;
}
@Exported
@Whitelisted
public List<UserRemoteConfig> getUserRemoteConfigs() {
if (userRemoteConfigs == null) {
/* Prevent NPE when no remote config defined */
userRemoteConfigs = new ArrayList<>();
}
return Collections.unmodifiableList(userRemoteConfigs);
}
@Whitelisted
public List<RemoteConfig> getRepositories() {
// Handle null-value to ensure backwards-compatibility, ie project configuration missing the <repositories/> XML element
if (remoteRepositories == null) {
return new ArrayList<>();
}
return remoteRepositories;
}
/**
* Derives a local branch name from the remote branch name by removing the
* name of the remote from the remote branch name.
* <p>
* Ex. origin/master becomes master
* <p>
* Cycles through the list of user remotes looking for a match allowing user
* to configure an alternate (not origin) name for the remote.
*
* @param remoteBranchName branch name whose remote repository name will be removed
* @return a local branch name derived by stripping the remote repository
* name from the {@code remoteBranchName} parameter. If a matching
* remote is not found, the original {@code remoteBranchName} will
* be returned.
*/
public String deriveLocalBranchName(String remoteBranchName) {
// default remoteName is 'origin' used if list of user remote configs is empty.
String remoteName = "origin";
for (final UserRemoteConfig remote : getUserRemoteConfigs()) {
remoteName = remote.getName();
if (remoteName == null || remoteName.isEmpty()) {
remoteName = "origin";
}
if (remoteBranchName.startsWith(remoteName + "/")) {
// found the remote config associated with remoteBranchName
break;
}
}
// now strip the remote name and return the resulting local branch name.
String localBranchName = remoteBranchName.replaceFirst("^" + remoteName + "/", "");
return localBranchName;
}
@CheckForNull
@Whitelisted
public String getGitTool() {
return gitTool;
}
@NonNull
public static String getParameterString(@CheckForNull String original, @NonNull EnvVars env) {
return env.expand(original);
}
private List<RefSpec> getRefSpecs(RemoteConfig repo, EnvVars env) {
List<RefSpec> refSpecs = new ArrayList<>();
for (RefSpec refSpec : repo.getFetchRefSpecs()) {
refSpecs.add(new RefSpec(getParameterString(refSpec.toString(), env)));
}
return refSpecs;
}
/**
* If the configuration is such that we are tracking just one branch of one repository
* return that branch specifier (in the form of something like "origin/master" or a SHA1-hash
*
* Otherwise return [@code null}.
*/
@CheckForNull
private String getSingleBranch(EnvVars env) {
// if we have multiple branches skip to advanced usecase
if (getBranches().size() != 1) {
return null;
}
String branch = getBranches().get(0).getName();
String repository = null;
if (getRepositories().size() != 1) {
for (RemoteConfig repo : getRepositories()) {
if (branch.startsWith(repo.getName() + "/")) {
repository = repo.getName();
break;
}
}
} else {
repository = getRepositories().get(0).getName();
}
// replace repository wildcard with repository name
if (branch.startsWith("*/") && repository != null) {
branch = repository + branch.substring(1);
}
// if the branch name contains more wildcards then the simple usecase
// does not apply and we need to skip to the advanced usecase
if (branch.contains("*")) {
return null;
}
// substitute build parameters if available
branch = getParameterString(branch, env);
// Check for empty string - replace with "**" when seen.
if (branch.equals("")) {
branch = "**";
}
return branch;
}
@Override
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> abstractBuild, FilePath workspace, Launcher launcher, TaskListener taskListener) throws IOException, InterruptedException {
return SCMRevisionState.NONE;
}
@Override
public boolean requiresWorkspaceForPolling() {
// TODO would need to use hudson.plugins.git.util.GitUtils.getPollEnvironment
return requiresWorkspaceForPolling(new EnvVars());
}
/* Package protected for test access */
boolean requiresWorkspaceForPolling(EnvVars environment) {
for (GitSCMExtension ext : getExtensions()) {
if (ext.requiresWorkspaceForPolling()) return true;
}
return getSingleBranch(environment) == null;
}
@Override
public PollingResult compareRemoteRevisionWith(Job<?, ?> project, Launcher launcher, FilePath workspace, final TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
try {
return compareRemoteRevisionWithImpl( project, launcher, workspace, listener);
} catch (GitException e){
throw new IOException(e);
}
}
public static final Pattern GIT_REF = Pattern.compile("^(refs/[^/]+)/(.+)");
private PollingResult compareRemoteRevisionWithImpl(Job<?, ?> project, Launcher launcher, FilePath workspace, final @NonNull TaskListener listener) throws IOException, InterruptedException {
// Poll for changes. Are there any unbuilt revisions that Hudson ought to build ?
listener.getLogger().println("Using strategy: " + getBuildChooser().getDisplayName());
final Run lastBuild = project.getLastBuild();
if (lastBuild == null) {
// If we've never been built before, well, gotta build!
listener.getLogger().println("[poll] No previous build, so forcing an initial build.");
return BUILD_NOW;
}
final BuildData buildData = fixNull(getBuildData(lastBuild));
if (buildData.lastBuild != null) {
listener.getLogger().println("[poll] Last Built Revision: " + buildData.lastBuild.revision);
}
final EnvVars pollEnv = project instanceof AbstractProject ? GitUtils.getPollEnvironment((AbstractProject) project, workspace, launcher, listener, false) : lastBuild.getEnvironment(listener);
final String singleBranch = getSingleBranch(pollEnv);
if (!requiresWorkspaceForPolling(pollEnv)) {
final EnvVars environment = project instanceof AbstractProject ? GitUtils.getPollEnvironment((AbstractProject) project, workspace, launcher, listener, false) : new EnvVars();
GitClient git = createClient(listener, environment, lastBuild, Jenkins.get(), null);
for (RemoteConfig remoteConfig : getParamExpandedRepos(lastBuild, listener)) {
String remote = remoteConfig.getName();
List<RefSpec> refSpecs = getRefSpecs(remoteConfig, environment);
for (URIish urIish : remoteConfig.getURIs()) {
String gitRepo = urIish.toString();
Map<String, ObjectId> heads = git.getHeadRev(gitRepo);
if (heads==null || heads.isEmpty()) {
listener.getLogger().println("[poll] Couldn't get remote head revision");
return BUILD_NOW;
}
listener.getLogger().println("Found "+ heads.size() +" remote heads on " + urIish);
Iterator<Entry<String, ObjectId>> it = heads.entrySet().iterator();
while (it.hasNext()) {
String head = it.next().getKey();
boolean match = false;
for (RefSpec spec : refSpecs) {
if (spec.matchSource(head)) {
match = true;
break;
}
}
if (!match) {
listener.getLogger().println("Ignoring " + head + " as it doesn't match any of the configured refspecs");
it.remove();
}
}
for (BranchSpec branchSpec : getBranches()) {
for (Entry<String, ObjectId> entry : heads.entrySet()) {
final String head = entry.getKey();
// head is "refs/(heads|tags|whatever)/branchName
// first, check the a canonical git reference is configured
if (!branchSpec.matches(head, environment)) {
// convert head `refs/(heads|tags|whatever)/branch` into shortcut notation `remote/branch`
String name;
Matcher matcher = GIT_REF.matcher(head);
if (matcher.matches()) name = remote + head.substring(matcher.group(1).length());
else name = remote + "/" + head;
if (!branchSpec.matches(name, environment)) continue;
}
final ObjectId sha1 = entry.getValue();
Build built = buildData.getLastBuild(sha1);
if (built != null) {
listener.getLogger().println("[poll] Latest remote head revision on " + head + " is: " + sha1.getName() + " - already built by " + built.getBuildNumber());
continue;
}
listener.getLogger().println("[poll] Latest remote head revision on " + head + " is: " + sha1.getName());
return BUILD_NOW;
}
}
}
}
return NO_CHANGES;
}
final Node node = GitUtils.workspaceToNode(workspace);
final EnvVars environment = project instanceof AbstractProject ? GitUtils.getPollEnvironment((AbstractProject) project, workspace, launcher, listener) : project.getEnvironment(node, listener);
FilePath workingDirectory = workingDirectory(project,workspace,environment,listener);
// (Re)build if the working directory doesn't exist
if (workingDirectory == null || !workingDirectory.exists()) {
listener.getLogger().println("[poll] Working Directory does not exist");
return BUILD_NOW;
}
GitClient git = createClient(listener, environment, lastBuild, node, workingDirectory);
if (git.hasGitRepo(false)) {
GitHooksConfiguration.configure(git);
// Repo is there - do a fetch
listener.getLogger().println("Fetching changes from the remote Git repositories");
// Fetch updates
for (RemoteConfig remoteRepository : getParamExpandedRepos(lastBuild, listener)) {
fetchFrom(git, null, listener, remoteRepository);
}
listener.getLogger().println("Polling for changes in");
Collection<Revision> candidates = getBuildChooser().getCandidateRevisions(
true, singleBranch, git, listener, buildData, new BuildChooserContextImpl(project, null, environment));
for (Revision c : candidates) {
if (!isRevExcluded(git, c, listener, buildData)) {
return PollingResult.SIGNIFICANT;
}
}
return NO_CHANGES;
} else {
listener.getLogger().println("No Git repository yet, an initial checkout is required");
return PollingResult.SIGNIFICANT;
}
}
/**
* Allows {@link Builder}s and {@link Publisher}s to access a configured {@link GitClient} object to
* perform additional git operations.
* @param listener build log
* @param environment environment variables to be used
* @param build run context for the returned GitClient
* @param workspace client workspace
* @return git client for additional git operations
* @throws IOException on input or output error
* @throws InterruptedException when interrupted
*/
@NonNull
public GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run<?,?> build, FilePath workspace) throws IOException, InterruptedException {
FilePath ws = workingDirectory(build.getParent(), workspace, environment, listener);
/* ws will be null if the node which ran the build is offline */
if (ws != null) {
ws.mkdirs(); // ensure it exists
}
return createClient(listener,environment, build, GitUtils.workspaceToNode(workspace), ws, null);
}
/**
* Allows {@link Publisher} and other post build actions to access a configured {@link GitClient}.
* The post build action can use the {@code postBuildUnsupportedCommand} argument to control the
* selection of a git tool by {@link GitToolChooser}.
* @param listener build log
* @param environment environment variables to be used
* @param build run context for the returned GitClient
* @param workspace client workspace
* @param postBuildUnsupportedCommand passed by caller to control choice of git tool by GitTooChooser
* @return git client for additional git operations
* @throws IOException on input or output error
* @throws InterruptedException when interrupted
*/
@NonNull
public GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run<?,?> build, FilePath workspace, UnsupportedCommand postBuildUnsupportedCommand) throws IOException, InterruptedException {
FilePath ws = workingDirectory(build.getParent(), workspace, environment, listener);
/* ws will be null if the node which ran the build is offline */
if (ws != null) {
ws.mkdirs(); // ensure it exists
}
return createClient(listener,environment, build, GitUtils.workspaceToNode(workspace), ws, postBuildUnsupportedCommand);
}
@NonNull
private GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run<?, ?> build, Node n, FilePath ws) throws IOException, InterruptedException {
return createClient(listener, environment, build, n, ws, null);
}
@NonNull
private GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run<?, ?> build, Node n, FilePath ws, UnsupportedCommand postBuildUnsupportedCommand) throws IOException, InterruptedException {
if (postBuildUnsupportedCommand == null) {
/* UnsupportedCommand supports JGit by default */
postBuildUnsupportedCommand = new UnsupportedCommand();
}
String gitExe = getGitExe(n, listener);
GitTool gitTool = getGitTool(n, null, listener);
if (!isDisableGitToolChooser()) {
UnsupportedCommand unsupportedCommand = new UnsupportedCommand();
for (GitSCMExtension ext : extensions) {
ext.determineSupportForJGit(this, unsupportedCommand);
}
GitToolChooser chooser = null;
for (UserRemoteConfig uc : getUserRemoteConfigs()) {
String ucCredentialsId = uc.getCredentialsId();
String url = getParameterString(uc.getUrl(), environment);
/* If any of the extensions do not support JGit, it should not be suggested */
/* If the post build action does not support JGit, it should not be suggested */
chooser = new GitToolChooser(url, build.getParent(), ucCredentialsId, gitTool, n, listener,
unsupportedCommand.determineSupportForJGit() && postBuildUnsupportedCommand.determineSupportForJGit());
}
if (chooser != null) {
listener.getLogger().println("The recommended git tool is: " + chooser.getGitTool());
String updatedGitExe = chooser.getGitTool();
if (!updatedGitExe.equals("NONE")) {
gitExe = updatedGitExe;
}
}
}
Git git = Git.with(listener, environment).in(ws).using(gitExe);
GitClient c = git.getClient();
for (GitSCMExtension ext : extensions) {
c = ext.decorate(this,c);
}
for (UserRemoteConfig uc : getUserRemoteConfigs()) {
String ucCredentialsId = uc.getCredentialsId();
if (ucCredentialsId == null) {
listener.getLogger().println("No credentials specified");
} else {
String url = getParameterString(uc.getUrl(), environment);
StandardUsernameCredentials credentials = lookupScanCredentials(build, url, ucCredentialsId);
if (credentials != null) {
c.addCredentials(url, credentials);
if(!isHideCredentials()) {
listener.getLogger().printf("using credential %s%n", credentials.getId());
}
CredentialsProvider.track(build, credentials); // TODO unclear if findCredentialById was meant to do this in all cases
} else {
if(!isHideCredentials()) {
listener.getLogger().printf("Warning: CredentialId \"%s\" could not be found.%n", ucCredentialsId);
}
}
}
}
// TODO add default credentials
return c;
}
private static StandardUsernameCredentials lookupScanCredentials(@NonNull Run<?, ?> build,
@CheckForNull String url,
@CheckForNull String ucCredentialsId) {
if (Util.fixEmpty(ucCredentialsId) == null) {
return null;
} else {
StandardUsernameCredentials c = CredentialsProvider.findCredentialById(
ucCredentialsId,
StandardUsernameCredentials.class,
build,
URIRequirementBuilder.fromUri(url).build());
return c != null && GitClient.CREDENTIALS_MATCHER.matches(c) ? c : null;
}
}
private static CredentialsMatcher gitScanCredentialsMatcher() {
return CredentialsMatchers.anyOf(CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class));
}
@NonNull
private BuildData fixNull(BuildData bd) {
ScmName sn = getExtensions().get(ScmName.class);
String scmName = sn == null ? null : sn.getName();
return bd != null ? bd : new BuildData(scmName, getUserRemoteConfigs());
}
/**
* Fetch information from a particular remote repository.
*
* @param git git client
* @param run run context if it's running for build
* @param listener build log
* @param remoteRepository remote git repository
* @throws InterruptedException when interrupted
* @throws IOException on input or output error
*/
private void fetchFrom(GitClient git,
@CheckForNull Run<?, ?> run,
TaskListener listener,
RemoteConfig remoteRepository) throws InterruptedException, IOException {
boolean first = true;
for (URIish url : remoteRepository.getURIs()) {
try {
if (first) {
git.setRemoteUrl(remoteRepository.getName(), url.toPrivateASCIIString());
first = false;
} else {
git.addRemoteUrl(remoteRepository.getName(), url.toPrivateASCIIString());
}
FetchCommand fetch = git.fetch_().from(url, remoteRepository.getFetchRefSpecs());
for (GitSCMExtension extension : extensions) {
extension.decorateFetchCommand(this, run, git, listener, fetch);
}