forked from jenkinsci/git-parameter-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitParameterDefinition.java
More file actions
818 lines (715 loc) · 31.1 KB
/
GitParameterDefinition.java
File metadata and controls
818 lines (715 loc) · 31.1 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
package net.uaznia.lukanus.hudson.plugins.gitparameter;
import static hudson.util.FormValidation.error;
import static hudson.util.FormValidation.ok;
import static hudson.util.FormValidation.warning;
import static net.uaznia.lukanus.hudson.plugins.gitparameter.Consts.*;
import static net.uaznia.lukanus.hudson.plugins.gitparameter.Messages.*;
import static net.uaznia.lukanus.hudson.plugins.gitparameter.Utils.getParentJob;
import static net.uaznia.lukanus.hudson.plugins.gitparameter.scms.SCMFactory.getGitSCMs;
import static org.apache.commons.lang3.BooleanUtils.isTrue;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.apache.commons.lang3.StringUtils.trim;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.cli.CLICommand;
import hudson.model.ChoiceParameterDefinition;
import hudson.model.Failure;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Run;
import hudson.model.StringParameterDefinition;
import hudson.model.TaskListener;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitSCM;
import hudson.util.FormValidation;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.regex.PatternSyntaxException;
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.uaznia.lukanus.hudson.plugins.gitparameter.jobs.JobWrapper;
import net.uaznia.lukanus.hudson.plugins.gitparameter.jobs.JobWrapperFactory;
import net.uaznia.lukanus.hudson.plugins.gitparameter.model.ItemsErrorModel;
import net.uaznia.lukanus.hudson.plugins.gitparameter.scms.RepoSCM;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.FetchCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.export.Exported;
public class GitParameterDefinition extends ParameterDefinition implements Comparable<GitParameterDefinition> {
private static final long serialVersionUID = 9157832967140868122L;
private static final Logger LOGGER = Logger.getLogger(GitParameterDefinition.class.getName());
private static final String ALLOW_ANY_PARAMETER_VALUE_PROPERTY_NAME =
GitParameterDefinition.class.getName() + ".allowAnyParameterValue";
/**
* Allow any parameter value, without validating that the value is valid.
* SECURITY-3419 escape hatch.
*/
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Escape hatch must allow runtime modification")
public static boolean allowAnyParameterValue =
SystemProperties.getBoolean(ALLOW_ANY_PARAMETER_VALUE_PROPERTY_NAME, false);
private UUID uuid;
private String type;
private String branch;
private String tagFilter;
private String branchFilter;
private SortMode sortMode;
private String defaultValue;
private SelectedValue selectedValue;
private String useRepository;
private Boolean quickFilterEnabled;
private String listSize;
private Boolean requiredParameter;
@DataBoundConstructor
public GitParameterDefinition(
String name,
String type,
String defaultValue,
String description,
String branch,
String branchFilter,
String tagFilter,
SortMode sortMode,
SelectedValue selectedValue,
String useRepository,
Boolean quickFilterEnabled) {
super(name, description);
this.defaultValue = defaultValue;
this.branch = branch;
this.uuid = UUID.randomUUID();
this.sortMode = sortMode;
this.selectedValue = selectedValue;
this.quickFilterEnabled = quickFilterEnabled;
this.listSize = DEFAULT_LIST_SIZE;
this.requiredParameter = false;
setUseRepository(useRepository);
setParameterType(type);
setTagFilter(tagFilter);
setBranchFilter(branchFilter);
}
private Object readResolve() {
// Jobs created before UUID was introduced can deserialize with a null UUID.
// Assign one to preserve stable identity matching and prevent null handling bugs.
if (uuid == null) {
uuid = UUID.randomUUID();
}
return this;
}
@Override
public ParameterValue createValue(StaplerRequest2 request) {
String value[] = request.getParameterValues(getName());
if (value == null || value.length == 0 || isBlank(value[0])) {
if (isTrue(requiredParameter)) {
throw new Failure("Parameter: " + getName() + " is required to have a value please select an option");
} else {
return getDefaultParameterValue();
}
}
GitParameterValue gitParameterValue = new GitParameterValue(getName(), value[0]);
if (!isValid(gitParameterValue)) {
throw new Failure("Parameter " + getName() + " provided value '" + value[0] + "' is invalid");
}
return gitParameterValue;
}
@Override
public ParameterValue createValue(StaplerRequest2 request, JSONObject jO) {
Object value = jO.get("value");
StringBuilder strValue = new StringBuilder();
if (value instanceof String) {
strValue.append(value);
} else if (value instanceof JSONArray) {
JSONArray jsonValues = (JSONArray) value;
for (int i = 0; i < jsonValues.size(); i++) {
strValue.append(jsonValues.getString(i));
if (i < jsonValues.size() - 1) {
strValue.append(",");
}
}
}
if (strValue.length() == 0) {
if (isTrue(requiredParameter) && isBlank(defaultValue)) {
throw new Failure("Parameter: " + getName() + " is required to have a value please select an option");
} else {
strValue.append(defaultValue);
}
}
GitParameterValue gitParameterValue = new GitParameterValue(jO.getString("name"), strValue.toString());
if (!strValue.toString().equals(defaultValue) && !isValid(gitParameterValue)) {
throw new Failure("Parameter " + jO.getString("name") + " value '" + strValue.toString() + "' is invalid");
}
return gitParameterValue;
}
@Override
public ParameterValue createValue(CLICommand command, String value) throws IOException, InterruptedException {
// Clear the allowedValues cache when invoked through CLI to ensure fresh data.
// The isValid() method will refresh the cache if needed.
allowedValues = null;
if (isNotEmpty(value)) {
GitParameterValue gitParameterValue = new GitParameterValue(getName(), value);
if (!isValid(gitParameterValue)) {
throw new Failure("Parameter " + getName() + " value '" + value + "' is invalid");
}
return gitParameterValue;
}
if (isTrue(requiredParameter)
&& isBlank(getDefaultValue())
&& !getSelectedValue().equals(SelectedValue.TOP)) {
throw new Failure("Parameter: " + getName() + " is required to have a value please select an option");
} else {
ParameterValue defVal = getDefaultParameterValue();
if (defVal != null && !isValid(defVal) && defVal.getValue() instanceof String strValue) {
throw new Failure("Parameter " + getName() + " default value '" + strValue + "' is invalid");
}
return defVal;
}
}
@Override
public ParameterValue getDefaultParameterValue() {
// If 'Default Value' is set has high priority!
String defValue = getDefaultValue();
if (!isBlank(defValue)) {
return new GitParameterValue(getName(), defValue);
}
switch (getSelectedValue()) {
case TOP:
try {
ItemsErrorModel valueItems = getAllValueItems();
if (valueItems.size() > 0) {
return new GitParameterValue(getName(), valueItems.get(0).value);
}
} catch (Exception e) {
LOGGER.log(
Level.SEVERE,
getCustomJobName() + " " + Messages.GitParameterDefinition_unexpectedError(),
e);
}
break;
case DEFAULT:
case NONE:
default:
return super.getDefaultParameterValue();
}
return super.getDefaultParameterValue();
}
@Exported
public ItemsErrorModel getAllValueItems() {
return getDescriptor().doFillValueItems(getParentJob(this), getName());
}
public String getParameterType() {
return type;
}
public void setParameterType(String type) {
if (isParameterTypeCorrect(type)) {
this.type = type;
} else {
this.type = PARAMETER_TYPE_BRANCH;
}
}
public String getBranch() {
return this.branch;
}
public void setBranch(String nameOfBranch) {
this.branch = nameOfBranch;
}
public SortMode getSortMode() {
return this.sortMode == null ? SortMode.NONE : this.sortMode;
}
public void setSortMode(SortMode sortMode) {
this.sortMode = sortMode;
}
public String getTagFilter() {
return this.tagFilter;
}
public void setTagFilter(String tagFilter) {
if (isEmpty(trim(tagFilter))) {
tagFilter = "*";
}
this.tagFilter = tagFilter;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getBranchFilter() {
return branchFilter;
}
public void setBranchFilter(String branchFilter) {
if (isEmpty(trim(branchFilter))) {
branchFilter = ".*";
}
this.branchFilter = branchFilter;
}
public String getListSize() {
return listSize == null ? DEFAULT_LIST_SIZE : listSize;
}
@DataBoundSetter
public void setListSize(String listSize) {
this.listSize = listSize;
}
public Boolean getRequiredParameter() {
return requiredParameter;
}
@DataBoundSetter
public void setRequiredParameter(Boolean requiredParameter) {
this.requiredParameter = requiredParameter;
}
public SelectedValue getSelectedValue() {
return selectedValue == null ? SelectedValue.TOP : selectedValue;
}
public Boolean getQuickFilterEnabled() {
return quickFilterEnabled;
}
@Override
public int compareTo(GitParameterDefinition pd) {
if (pd == null) {
return -1;
}
if (this == pd) {
return 0;
}
return uuid != null && pd.uuid != null && pd.uuid.equals(uuid) ? 0 : -1;
}
/* Set of values allowed for this parameter definition */
private transient Set<String> allowedValues = null;
private Map<String, String> generateParamList(JobWrapper jobWrapper, List<GitSCM> scms) throws Exception {
Map<String, String> paramList = new LinkedHashMap<>();
EnvVars environment = getEnvironment(jobWrapper);
Set<String> usedRepository = new HashSet<>();
outForLoops:
for (GitSCM git : scms) {
for (RemoteConfig repository : git.getRepositories()) {
GitClient gitClient = getGitClient(jobWrapper, null, git, environment);
for (URIish remoteURL : repository.getURIs()) {
String gitUrl = Util.replaceMacro(remoteURL.toPrivateASCIIString(), environment);
if (notMatchUseRepository(gitUrl) || usedRepository.contains(gitUrl)) {
continue;
}
if (isTagType(type)) {
Set<String> tagSet = getTag(gitClient, gitUrl);
sortAndPutToParam(tagSet, paramList);
}
if (isBranchType(type)) {
Set<String> branchSet = getBranch(gitClient, gitUrl, repository.getName());
sortAndPutToParam(branchSet, paramList);
}
if (isPullRequestType(type)) {
Set<String> pullRequestSet = getPullRequest(gitClient, gitUrl);
sortAndPutToParam(pullRequestSet, paramList);
}
if (isRevisionType(type)) {
synchronized (GitParameterDefinition.class) {
getRevision(jobWrapper, git, paramList, environment, repository, remoteURL);
}
}
if (isBlank(useRepository)) {
break outForLoops;
}
usedRepository.add(gitUrl);
}
}
}
return paramList;
}
public ItemsErrorModel generateContents(JobWrapper jobWrapper, List<GitSCM> scms) {
try {
Map<String, String> paramList = generateParamList(jobWrapper, scms);
allowedValues = paramList.keySet(); // Save the allowed values for later use
return convertMapToListBox(paramList);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, getCustomJobName() + " " + Messages.GitParameterDefinition_unexpectedError(), e);
return ItemsErrorModel.create(
getDefaultValue(),
GitParameterDefinition_returnDefaultValue(),
GitParameterDefinition_error(),
e.getMessage(),
GitParameterDefinition_lookAtLog(),
GitParameterDefinition_checkConfiguration());
}
}
private ItemsErrorModel convertMapToListBox(Map<String, String> paramList) {
ItemsErrorModel items = new ItemsErrorModel();
for (Map.Entry<String, String> entry : paramList.entrySet()) {
items.add(entry.getValue(), entry.getKey());
}
return items;
}
private boolean notMatchUseRepository(String gitUrl) {
if (isBlank(useRepository)) {
return false;
}
Pattern repositoryNamePattern;
try {
repositoryNamePattern = Pattern.compile(useRepository);
} catch (Exception e) {
LOGGER.log(
Level.INFO,
Messages.GitParameterDefinition_invalidUseRepositoryPattern(useRepository),
e.getMessage());
return false;
}
return !repositoryNamePattern.matcher(gitUrl).find();
}
private Set<String> getTag(GitClient gitClient, String gitUrl) throws InterruptedException {
Set<String> tagSet = new HashSet<>();
try {
Map<String, ObjectId> tags = gitClient.getRemoteReferences(gitUrl, tagFilter, false, true);
for (String tagName : tags.keySet()) {
tagSet.add(tagName.replaceFirst(REFS_TAGS_PATTERN, ""));
}
} catch (GitException e) {
LOGGER.log(Level.WARNING, getCustomJobName() + " " + Messages.GitParameterDefinition_getTag(), e);
}
return tagSet;
}
private Set<String> getBranch(GitClient gitClient, String gitUrl, String remoteName) throws Exception {
Set<String> branchSet = new HashSet<>();
Pattern branchFilterPattern = compileBranchFilterPattern();
Map<String, ObjectId> branches = gitClient.getRemoteReferences(gitUrl, null, true, false);
Iterator<String> remoteBranchesName = branches.keySet().iterator();
while (remoteBranchesName.hasNext()) {
String branchName = strip(remoteBranchesName.next(), remoteName);
Matcher matcher = branchFilterPattern.matcher(branchName);
if (matcher.matches()) {
if (matcher.groupCount() == 1) {
branchSet.add(matcher.group(1));
} else {
branchSet.add(branchName);
}
}
}
return branchSet;
}
private Set<String> getPullRequest(GitClient gitClient, String gitUrl) throws Exception {
Set<String> pullRequestSet = new HashSet<>();
Map<String, ObjectId> remoteReferences = gitClient.getRemoteReferences(gitUrl, null, false, false);
for (String remoteReference : remoteReferences.keySet()) {
Matcher matcher = PULL_REQUEST_REFS_PATTERN.matcher(remoteReference);
if (matcher.find()) {
pullRequestSet.add(matcher.group(1));
}
}
return pullRequestSet;
}
private Pattern compileBranchFilterPattern() {
Pattern branchFilterPattern;
try {
branchFilterPattern = Pattern.compile(branchFilter);
} catch (Exception e) {
LOGGER.log(
Level.INFO,
getCustomJobName() + " " + Messages.GitParameterDefinition_branchFilterNotValid(),
e.getMessage());
branchFilterPattern = Pattern.compile(".*");
}
return branchFilterPattern;
}
// hudson.plugins.git.Branch.strip
private String strip(String name, String remote) {
return remote + "/" + name.substring(name.indexOf('/', 5) + 1);
}
/**
* Unfortunately, to get the revisions should do fetch
*/
private void getRevision(
JobWrapper jobWrapper,
GitSCM git,
Map<String, String> paramList,
EnvVars environment,
RemoteConfig repository,
URIish remoteURL)
throws IOException, InterruptedException {
boolean isRepoScm = RepoSCM.isRepoSCM(repository.getName());
FilePathWrapper workspace = getWorkspace(jobWrapper, isRepoScm);
GitClient gitClient = getGitClient(jobWrapper, workspace, git, environment);
initWorkspace(workspace, gitClient, remoteURL);
FetchCommand fetch = gitClient.fetch_().prune().from(remoteURL, repository.getFetchRefSpecs());
fetch.execute();
RevisionInfoFactory revisionInfoFactory = new RevisionInfoFactory(gitClient, branch);
List<RevisionInfo> revisions = revisionInfoFactory.getRevisions();
for (RevisionInfo revision : revisions) {
paramList.put(revision.getSha1(), revision.getRevisionInfo());
}
workspace.delete();
}
private void sortAndPutToParam(Set<String> setElement, Map<String, String> paramList) {
List<String> sorted = sort(setElement);
for (String element : sorted) {
paramList.put(element, element);
}
}
private ArrayList<String> sort(Set<String> toSort) {
ArrayList<String> sorted;
if (this.getSortMode().getIsSorting()) {
sorted = sortByName(toSort);
if (this.getSortMode().getIsDescending()) {
Collections.reverse(sorted);
}
} else {
sorted = new ArrayList<>(toSort);
}
return sorted;
}
private FilePathWrapper getWorkspace(JobWrapper jobWrapper, boolean isRepoScm)
throws IOException, InterruptedException {
FilePathWrapper someWorkspace = new FilePathWrapper(jobWrapper.getSomeWorkspace());
if (isRepoScm) {
FilePath repoDir = new FilePath(someWorkspace.getFilePath(), RepoSCM.getRepoMainfestsDir());
if (repoDir.exists()) {
someWorkspace = new FilePathWrapper(repoDir);
} else {
someWorkspace = getTemporaryWorkspace();
}
} else if (someWorkspace.getFilePath() == null) {
someWorkspace = getTemporaryWorkspace();
}
someWorkspace.getFilePath().mkdirs();
// Must by not null and exist
return someWorkspace;
}
private FilePathWrapper getTemporaryWorkspace() throws IOException {
Path temporaryWorkspacePath = Files.createTempDirectory(TEMPORARY_DIRECTORY_PREFIX);
FilePath filePath = new FilePath(temporaryWorkspacePath.toFile());
FilePathWrapper filePathWrapper = new FilePathWrapper(filePath);
filePathWrapper.setThatTemporary();
return filePathWrapper;
}
@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "Jenkins.get() is not null")
private EnvVars getEnvironment(JobWrapper jobWrapper) throws IOException, InterruptedException {
EnvVars environment =
jobWrapper.getEnvironment(Jenkins.get().toComputer().getNode(), TaskListener.NULL);
EnvVars buildEnvironment = jobWrapper.getSomeBuildEnvironments();
addEnvironmentIfNotExists(environment, buildEnvironment);
EnvVars jobDefautEnvironment = getJobDefaultEnvironment(jobWrapper);
addEnvironmentIfNotExists(environment, jobDefautEnvironment);
EnvVars.resolve(environment);
return environment;
}
private void addEnvironmentIfNotExists(EnvVars environment, EnvVars otherEnvironment) {
if (otherEnvironment == null) {
return;
}
for (Map.Entry<String, String> entry : otherEnvironment.entrySet()) {
String key = entry.getKey();
if (!environment.containsKey(key)) {
environment.put(key, entry.getValue());
}
}
}
private EnvVars getJobDefaultEnvironment(JobWrapper jobWrapper) {
EnvVars environment = new EnvVars();
ParametersDefinitionProperty property =
(ParametersDefinitionProperty) jobWrapper.getJob().getProperty(ParametersDefinitionProperty.class);
if (property != null) {
for (ParameterDefinition parameterDefinition : property.getParameterDefinitions()) {
if (parameterDefinition != null && isAcceptedParameterClass(parameterDefinition)) {
checkAndAddDefaultParameterValue(parameterDefinition, environment);
}
}
}
return environment;
}
private boolean isAcceptedParameterClass(ParameterDefinition parameterDefinition) {
return parameterDefinition instanceof StringParameterDefinition
|| parameterDefinition instanceof ChoiceParameterDefinition;
}
private void checkAndAddDefaultParameterValue(ParameterDefinition parameterDefinition, EnvVars environment) {
ParameterValue defaultParameterValue = parameterDefinition.getDefaultParameterValue();
if (defaultParameterValue != null && defaultParameterValue.getValue() instanceof String) {
environment.put(parameterDefinition.getName(), (String) defaultParameterValue.getValue());
}
}
private void initWorkspace(FilePathWrapper workspace, GitClient gitClient, URIish remoteURL)
throws IOException, InterruptedException {
if (isEmptyWorkspace(workspace.getFilePath())) {
gitClient.init();
gitClient.clone(remoteURL.toASCIIString(), DEFAULT_REMOTE, false, null);
LOGGER.log(Level.INFO, getCustomJobName() + " " + Messages.GitParameterDefinition_genContentsCloneDone());
}
}
private boolean isEmptyWorkspace(FilePath workspaceDir) throws IOException, InterruptedException {
return workspaceDir.list().size() == 0;
}
private GitClient getGitClient(
final JobWrapper jobWrapper, FilePathWrapper workspace, GitSCM git, EnvVars environment)
throws IOException, InterruptedException {
Run build = new Run(jobWrapper.getJob(), System.currentTimeMillis()) {};
return git.createClient(
TaskListener.NULL, environment, build, workspace != null ? workspace.getFilePath() : null);
}
public ArrayList<String> sortByName(Set<String> set) {
ArrayList<String> tags = new ArrayList<>(set);
if (getSortMode().getIsUsingSmartSort()) {
Collections.sort(tags, new SmartNumberStringComparer());
} else {
Collections.sort(tags);
}
return tags;
}
public String getDivUUID() {
StringBuilder randomSelectName = new StringBuilder();
randomSelectName.append(getName().replaceAll("\\W", "_")).append("-").append(uuid);
return randomSelectName.toString();
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public String getUseRepository() {
return useRepository;
}
public void setUseRepository(String useRepository) {
this.useRepository = isBlank(useRepository) ? null : useRepository;
}
public String getCustomJobName() {
Job job = getParentJob(this);
String fullName = job != null ? job.getFullName() : EMPTY_JOB_NAME;
return "[ " + fullName + " ] ";
}
@Override
public boolean isValid(ParameterValue value) {
if (allowAnyParameterValue) {
return true; // SECURITY-3419
}
if (value.getValue() instanceof String strValue) {
// Fast path: check if value exists in cache
if (allowedValues != null && allowedValues.contains(strValue)) {
return true;
}
// Slow path: refresh cache from git and check again
// This handles two cases:
// 1. Cache is null (never populated)
// 2. Cache is stale (value not found, might be a newly created tag/branch)
if (Jenkins.getInstanceOrNull() == null) {
return false; // Automated tests only, not a running Jenkins instance
}
Job job = getParentJob(this);
if (job == null) {
return false; // Automated tests with a Jenkins instance
}
JobWrapper jobWrapper = JobWrapperFactory.createJobWrapper(job);
List<GitSCM> scms = getGitSCMs(jobWrapper, getUseRepository());
if (scms == null || scms.isEmpty()) {
return false;
}
try {
// Refresh the allowedValues cache from git
allowedValues = generateParamList(jobWrapper, scms).keySet();
return allowedValues.contains(strValue);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Allowed values not generated", e);
return false;
}
}
return false;
}
@Symbol("gitParameter")
@Extension
public static class DescriptorImpl extends ParameterDescriptor {
private boolean showNeedToCloneInformation = true;
public DescriptorImpl() {
load();
}
@Override
public String getDisplayName() {
return Messages.GitParameterDefinition_DisplayName();
}
public ItemsErrorModel doFillValueItems(@AncestorInPath Job job, @QueryParameter String param) {
JobWrapper jobWrapper = JobWrapperFactory.createJobWrapper(job);
ParametersDefinitionProperty prop = jobWrapper.getProperty(ParametersDefinitionProperty.class);
if (prop != null) {
ParameterDefinition def = prop.getParameterDefinition(param);
if (def instanceof GitParameterDefinition) {
GitParameterDefinition paramDef = (GitParameterDefinition) def;
String repositoryName = paramDef.getUseRepository();
List<GitSCM> scms = getGitSCMs(jobWrapper, repositoryName);
if (scms == null || scms.isEmpty()) {
String useRepositoryMessage = getUseRepositoryMessage(repositoryName);
return ItemsErrorModel.create(
paramDef.getDefaultValue(),
GitParameterDefinition_returnDefaultValue(),
GitParameterDefinition_noRepositoryConfigured(),
useRepositoryMessage,
GitParameterDefinition_checkConfiguration());
}
return paramDef.generateContents(jobWrapper, scms);
}
}
return ItemsErrorModel.EMPTY;
}
private String getUseRepositoryMessage(String repositoryName) {
return isNotBlank(repositoryName)
? Messages.GitParameterDefinition_useRepositoryMessage(repositoryName)
: StringUtils.EMPTY;
}
public FormValidation doCheckDefaultValue(
@QueryParameter String defaultValue, @QueryParameter Boolean requiredParameter) {
if (isTrue(requiredParameter)) {
return isBlank(defaultValue)
? ok()
: warning(Messages.GitParameterDefinition_defaultRequiredParameterWarning());
} else {
return isBlank(defaultValue) ? warning(Messages.GitParameterDefinition_requiredDefaultValue()) : ok();
}
}
public FormValidation doCheckBranchFilter(@QueryParameter String value) {
String errorMessage = Messages.GitParameterDefinition_invalidBranchPattern(value);
return validationRegularExpression(value, errorMessage);
}
public FormValidation doCheckUseRepository(@QueryParameter String value) {
String errorMessage = Messages.GitParameterDefinition_invalidUseRepositoryPattern(value);
return validationRegularExpression(value, errorMessage);
}
private FormValidation validationRegularExpression(String value, String errorMessage) {
try {
Pattern.compile(value); // Validate we've got a valid regex.
} catch (PatternSyntaxException e) {
LOGGER.log(Level.WARNING, errorMessage, e);
return error(errorMessage);
}
return ok();
}
@Override
public boolean configure(StaplerRequest2 req, JSONObject json) throws FormException {
showNeedToCloneInformation = json.getBoolean("showNeedToCloneInformation");
save();
return super.configure(req, json);
}
public boolean getShowNeedToCloneInformation() {
return showNeedToCloneInformation;
}
}
}