-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActiveGitBranchesParameterDefinition.java
More file actions
758 lines (648 loc) · 29.1 KB
/
Copy pathActiveGitBranchesParameterDefinition.java
File metadata and controls
758 lines (648 loc) · 29.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
package io.jenkins.plugins.activegitbranches;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import hudson.EnvVars;
import hudson.util.LogTaskListener;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.RepositoryCallback;
import hudson.model.TaskListener;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.eclipse.jgit.transport.URIish;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Active Git Branches Parameter Definition.
*
* This parameter plugin dynamically fetches Git branches from a remote repository,
* sorts them by commit date (descending), and limits the display to the top N branches.
*/
public class ActiveGitBranchesParameterDefinition extends ParameterDefinition {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(ActiveGitBranchesParameterDefinition.class.getName());
private final String repositoryUrl;
private String credentialsId;
private final int maxBranchCount;
private String branchFilter;
private String alwaysIncludeBranches;
private String defaultValue;
private boolean useQuickFetch = true;
@DataBoundConstructor
public ActiveGitBranchesParameterDefinition(String name, String repositoryUrl, int maxBranchCount, String description) {
super(name, description);
this.repositoryUrl = repositoryUrl;
this.maxBranchCount = maxBranchCount > 0 ? maxBranchCount : 10;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public String getCredentialsId() {
return credentialsId;
}
@DataBoundSetter
public void setCredentialsId(String credentialsId) {
this.credentialsId = credentialsId;
}
public int getMaxBranchCount() {
return maxBranchCount;
}
public String getBranchFilter() {
return branchFilter;
}
@DataBoundSetter
public void setBranchFilter(String branchFilter) {
this.branchFilter = branchFilter;
}
public String getAlwaysIncludeBranches() {
return alwaysIncludeBranches;
}
@DataBoundSetter
public void setAlwaysIncludeBranches(String alwaysIncludeBranches) {
this.alwaysIncludeBranches = alwaysIncludeBranches;
}
public String getDefaultValue() {
return defaultValue;
}
@DataBoundSetter
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean isUseQuickFetch() {
return useQuickFetch;
}
@DataBoundSetter
public void setUseQuickFetch(boolean useQuickFetch) {
this.useQuickFetch = useQuickFetch;
}
@Override
public ParameterValue createValue(StaplerRequest req, JSONObject jo) {
String value = jo.getString("value");
return new ActiveGitBranchesParameterValue(getName(), value, getDescription());
}
@Override
public ParameterValue createValue(StaplerRequest req) {
String[] values = req.getParameterValues(getName());
if (values != null && values.length > 0) {
return new ActiveGitBranchesParameterValue(getName(), values[0], getDescription());
}
return getDefaultParameterValue();
}
@Override
public ParameterValue getDefaultParameterValue() {
List<BranchInfo> branches = fetchBranches();
String value = defaultValue;
if ((value == null || value.isEmpty()) && !branches.isEmpty()) {
value = branches.get(0).getName();
}
return new ActiveGitBranchesParameterValue(getName(), value != null ? value : "", getDescription());
}
/**
* Fetches branches from the remote Git repository.
* This method suppresses exceptions and returns an empty list on failure.
*/
public List<BranchInfo> fetchBranches() {
try {
return fetchBranchesInternal();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to fetch branches from repository: " + repositoryUrl, e);
return new ArrayList<>();
}
}
/**
* Fetches branches from the remote Git repository.
* Strategy:
* 1. Try workspace fetch + for-each-ref (lightweight fetch + time-sorted) - PREFERRED
* 2. If no workspace: use ls-remote (fast, alphabetical) or clone (slow, time-sorted)
*/
private List<BranchInfo> fetchBranchesInternal() throws IOException, InterruptedException {
if (repositoryUrl == null || repositoryUrl.isEmpty()) {
throw new IOException("Repository URL is not configured");
}
// First, always try workspace-based fetch (lightweight fetch + preserves time sorting)
List<BranchInfo> result = tryFetchFromWorkspace();
if (result != null) {
LOGGER.info("Fetched branches from workspace with time-based sorting");
return result;
}
// No workspace available, fall back based on useQuickFetch setting
if (useQuickFetch) {
// Fast but no time sorting
LOGGER.info("No workspace available, using ls-remote (alphabetical sort)");
return fetchBranchesQuick();
} else {
// Slow but preserves time sorting
LOGGER.info("No workspace available, using clone (time-based sort)");
return fetchBranchesWithFullClone();
}
}
/**
* Quick fetch using git ls-remote (no clone required).
* This is much faster but doesn't provide commit timestamps for sorting.
* Branches are sorted alphabetically instead.
*/
private List<BranchInfo> fetchBranchesQuick() throws IOException, InterruptedException {
final List<BranchInfo> branchInfos = new ArrayList<>();
StandardCredentials credentials = getCredentials();
File tempDir = createTempDirectory();
try {
TaskListener listener = new LogTaskListener(LOGGER, Level.INFO);
EnvVars env = new EnvVars();
GitClient git = Git.with(listener, env)
.in(tempDir)
.using("jgit")
.getClient();
if (credentials != null) {
git.addCredentials(repositoryUrl, credentials);
}
// Use ls-remote to get remote references without cloning
Map<String, org.eclipse.jgit.lib.ObjectId> remoteRefs = git.getRemoteReferences(
repositoryUrl, null, true, false);
for (Map.Entry<String, org.eclipse.jgit.lib.ObjectId> entry : remoteRefs.entrySet()) {
String refName = entry.getKey();
// Filter for branches (refs/heads/...)
if (refName.startsWith("refs/heads/")) {
String branchName = refName.substring("refs/heads/".length());
// Apply branch filter
boolean isAlwaysIncluded = matchesAlwaysInclude(branchName);
if (!isAlwaysIncluded && !matchesBranchFilter(branchName)) {
continue;
}
// Use 0 as commit time since ls-remote doesn't provide it
// Branches will be sorted alphabetically instead
branchInfos.add(new BranchInfo(branchName, 0L));
}
}
} finally {
deleteDirectory(tempDir);
}
// Sort alphabetically (since we don't have commit times)
branchInfos.sort((a, b) -> a.getName().compareToIgnoreCase(b.getName()));
return applyLimits(branchInfos);
}
/**
* Try to fetch branches from existing Job workspace.
* Uses git fetch + for-each-ref which is faster than cloning.
* Returns null if workspace is not available.
*/
private List<BranchInfo> tryFetchFromWorkspace() {
try {
// Get the current Job from Stapler request context
StaplerRequest request = Stapler.getCurrentRequest();
if (request == null) {
LOGGER.fine("No Stapler request context available");
return null;
}
Job<?, ?> job = request.findAncestorObject(Job.class);
if (job == null) {
LOGGER.fine("No Job found in request context");
return null;
}
// Get workspace
FilePath workspace = null;
if (job instanceof AbstractProject) {
workspace = ((AbstractProject<?, ?>) job).getSomeWorkspace();
}
if (workspace == null || !workspace.exists()) {
LOGGER.fine("Workspace not available for job: " + job.getFullName());
return null;
}
// Check if .git directory exists
FilePath gitDir = workspace.child(".git");
if (!gitDir.exists()) {
LOGGER.fine("No .git directory in workspace: " + workspace.getRemote());
return null;
}
LOGGER.info("Using existing workspace for branch fetch: " + workspace.getRemote());
return fetchBranchesFromWorkspace(workspace);
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to fetch from workspace, will fall back to clone", e);
return null;
}
}
/**
* Fetch branches from an existing workspace.
* Performs a lightweight fetch to update refs, then reads local refs.
* Returns null if no local refs found (caller should fall back to other methods).
*/
private List<BranchInfo> fetchBranchesFromWorkspace(FilePath workspace) throws IOException, InterruptedException {
File workspaceDir = new File(workspace.getRemote());
TaskListener listener = new LogTaskListener(LOGGER, Level.INFO);
EnvVars env = new EnvVars();
GitClient git = Git.with(listener, env)
.in(workspaceDir)
.using("jgit")
.getClient();
// Add credentials if available
StandardCredentials credentials = getCredentials();
if (credentials != null) {
git.addCredentials(repositoryUrl, credentials);
}
// Read cached local refs (instant, no network)
List<BranchInfo> localRefs = readLocalRefs(git);
// If we have cached refs, use them directly (fast path)
if (!localRefs.isEmpty()) {
LOGGER.info("Using cached local refs (" + localRefs.size() + " branches)");
return applyLimits(localRefs);
}
// No cached refs in workspace, return null to fall back to ls-remote
LOGGER.info("No cached refs in workspace, falling back to other method");
return null;
}
/**
* Read local refs from the repository without any network operation.
* Returns empty list if no refs found or repository is invalid.
*/
private List<BranchInfo> readLocalRefs(GitClient git) {
final List<BranchInfo> branchInfos = new ArrayList<>();
try {
git.withRepository(new RepositoryCallback<Void>() {
@Override
public Void invoke(org.eclipse.jgit.lib.Repository repo, hudson.remoting.VirtualChannel channel) throws IOException {
try (org.eclipse.jgit.revwalk.RevWalk walk = new org.eclipse.jgit.revwalk.RevWalk(repo)) {
List<org.eclipse.jgit.lib.Ref> allRefs = repo.getRefDatabase().getRefsByPrefix("refs/remotes/origin/");
for (org.eclipse.jgit.lib.Ref ref : allRefs) {
String branchName = ref.getName().substring("refs/remotes/origin/".length());
if (branchName.equals("HEAD")) continue;
boolean isAlwaysIncluded = matchesAlwaysInclude(branchName);
if (!isAlwaysIncluded && !matchesBranchFilter(branchName)) {
continue;
}
try {
org.eclipse.jgit.revwalk.RevCommit commit = walk.parseCommit(ref.getObjectId());
long commitTime = commit.getCommitTime() * 1000L;
branchInfos.add(new BranchInfo(branchName, commitTime));
} catch (Exception e) {
branchInfos.add(new BranchInfo(branchName, 0L));
}
}
}
return null;
}
});
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to read local refs", e);
return new ArrayList<>();
}
// Sort by commit date descending
branchInfos.sort((a, b) -> Long.compare(b.getCommitTime(), a.getCommitTime()));
return branchInfos;
}
/**
* Full clone to get commit timestamps (slowest but always works).
*/
private List<BranchInfo> fetchBranchesWithFullClone() throws IOException, InterruptedException {
final List<BranchInfo> branchInfos = new ArrayList<>();
StandardCredentials credentials = getCredentials();
File tempDir = createTempDirectory();
try {
TaskListener listener = new LogTaskListener(LOGGER, Level.INFO);
EnvVars env = new EnvVars();
GitClient git = Git.with(listener, env)
.in(tempDir)
.using("jgit")
.getClient();
if (credentials != null) {
git.addCredentials(repositoryUrl, credentials);
}
// Clone the repository (shallow for performance)
git.clone_()
.url(repositoryUrl)
.repositoryName("origin")
.shallow(true)
.execute();
// Access the repository to iterate branches and get commit dates
git.withRepository(new RepositoryCallback<Void>() {
@Override
public Void invoke(org.eclipse.jgit.lib.Repository repo, hudson.remoting.VirtualChannel channel) throws IOException, InterruptedException {
try (org.eclipse.jgit.revwalk.RevWalk walk = new org.eclipse.jgit.revwalk.RevWalk(repo)) {
List<org.eclipse.jgit.lib.Ref> allRefs = repo.getRefDatabase().getRefs();
for (org.eclipse.jgit.lib.Ref ref : allRefs) {
String refName = ref.getName();
// Filter for remote branches (refs/remotes/origin/...)
if (refName.startsWith("refs/remotes/origin/")) {
String branchName = refName.substring("refs/remotes/origin/".length());
// Skip HEAD
if (branchName.equals("HEAD")) continue;
// Apply branch filter
boolean isAlwaysIncluded = matchesAlwaysInclude(branchName);
if (!isAlwaysIncluded && !matchesBranchFilter(branchName)) {
continue;
}
try {
org.eclipse.jgit.revwalk.RevCommit commit = walk.parseCommit(ref.getObjectId());
long commitTime = commit.getCommitTime() * 1000L;
branchInfos.add(new BranchInfo(branchName, commitTime));
} catch (Exception e) {
// If we can't parse commit, treat as old
branchInfos.add(new BranchInfo(branchName, 0L));
}
}
}
}
return null;
}
});
} finally {
deleteDirectory(tempDir);
}
// Sort by commit date descending
branchInfos.sort((a, b) -> Long.compare(b.getCommitTime(), a.getCommitTime()));
return applyLimits(branchInfos);
}
/**
* Apply maxBranchCount limit while respecting alwaysIncludeBranches.
*/
private List<BranchInfo> applyLimits(List<BranchInfo> branchInfos) {
if (branchInfos.size() <= maxBranchCount) {
return branchInfos;
}
if (alwaysIncludeBranches == null || alwaysIncludeBranches.trim().isEmpty()) {
return new ArrayList<>(branchInfos.subList(0, maxBranchCount));
}
List<BranchInfo> mandatory = new ArrayList<>();
List<BranchInfo> others = new ArrayList<>();
for (BranchInfo info : branchInfos) {
if (matchesAlwaysInclude(info.getName())) {
mandatory.add(info);
} else {
others.add(info);
}
}
List<BranchInfo> result = new ArrayList<>(mandatory);
// Fill remaining slots with others
int slotsLeft = maxBranchCount - mandatory.size();
if (slotsLeft > 0) {
for (int i = 0; i < slotsLeft && i < others.size(); i++) {
result.add(others.get(i));
}
}
return result;
}
private boolean matchesAlwaysInclude(String branchName) {
if (alwaysIncludeBranches == null || alwaysIncludeBranches.trim().isEmpty()) {
return false;
}
try {
Pattern pattern = Pattern.compile(alwaysIncludeBranches);
return pattern.matcher(branchName).matches();
} catch (PatternSyntaxException e) {
return false;
}
}
private StandardCredentials getCredentials() {
if (credentialsId == null || credentialsId.isEmpty()) {
return null;
}
return CredentialsMatchers.firstOrNull(
com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
StandardCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
URIRequirementBuilder.fromUri(repositoryUrl).build()
),
CredentialsMatchers.withId(credentialsId)
);
}
private boolean matchesBranchFilter(String branchName) {
if (branchFilter == null || branchFilter.trim().isEmpty()) {
return true;
}
try {
Pattern pattern = Pattern.compile(branchFilter);
return pattern.matcher(branchName).matches();
} catch (PatternSyntaxException e) {
LOGGER.warning("Invalid branch filter regex: " + branchFilter);
return true;
}
}
private File createTempDirectory() throws IOException {
File tempDir = File.createTempFile("jenkins-git-branches-", "");
tempDir.delete();
tempDir.mkdirs();
return tempDir;
}
private void deleteDirectory(File directory) {
if (directory != null && directory.exists()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
file.delete();
}
}
}
directory.delete();
}
}
/**
* Branch information holder.
*/
public static class BranchInfo {
private final String name;
private final long commitTime;
public BranchInfo(String name, long commitTime) {
this.name = name;
this.commitTime = commitTime;
}
public String getName() {
return name;
}
public long getCommitTime() {
return commitTime;
}
}
@Symbol("activeGitBranches")
@Extension
public static class DescriptorImpl extends ParameterDescriptor {
@NonNull
@Override
public String getDisplayName() {
return "Active Git Branches Parameter";
}
/**
* Validates the repository URL.
*/
public FormValidation doCheckRepositoryUrl(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.error("Repository URL is required");
}
if (!value.startsWith("http://") && !value.startsWith("https://") &&
!value.startsWith("git@") && !value.startsWith("ssh://")) {
return FormValidation.warning("URL should start with http://, https://, git@ or ssh://");
}
return FormValidation.ok();
}
/**
* Validates the max branch count.
*/
public FormValidation doCheckMaxBranchCount(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.error("Max branch count is required");
}
try {
int count = Integer.parseInt(value);
if (count <= 0) {
return FormValidation.error("Max branch count must be greater than 0");
}
if (count > 100) {
return FormValidation.warning("Large branch counts may cause performance issues");
}
} catch (NumberFormatException e) {
return FormValidation.error("Please enter a valid number");
}
return FormValidation.ok();
}
/**
* Validates the branch filter regex.
*/
public FormValidation doCheckBranchFilter(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.ok();
}
try {
Pattern.compile(value);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regex pattern: " + e.getMessage());
}
return FormValidation.ok();
}
/**
* Validates the always include branches regex.
*/
public FormValidation doCheckAlwaysIncludeBranches(@QueryParameter String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.ok();
}
try {
Pattern.compile(value);
} catch (PatternSyntaxException e) {
return FormValidation.error("Invalid regex pattern: " + e.getMessage());
}
return FormValidation.ok();
}
/**
* Fills the credentials dropdown.
*/
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item,
@QueryParameter String credentialsId,
@QueryParameter String repositoryUrl) {
StandardListBoxModel result = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(credentialsId);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ) &&
!item.hasPermission(com.cloudbees.plugins.credentials.CredentialsProvider.USE_ITEM)) {
return result.includeCurrentValue(credentialsId);
}
}
result.includeEmptyValue();
result.includeMatchingAs(
item instanceof hudson.model.Queue.Task
? ((hudson.model.Queue.Task) item).getDefaultAuthentication()
: ACL.SYSTEM,
item,
StandardCredentials.class,
URIRequirementBuilder.fromUri(repositoryUrl).build(),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernameCredentials.class)
)
);
return result;
}
/**
* Fills the branch dropdown for the parameter.
*/
public ListBoxModel doFillDefaultValueItems(@QueryParameter String repositoryUrl,
@QueryParameter String credentialsId,
@QueryParameter int maxBranchCount,
@QueryParameter String branchFilter,
@QueryParameter String alwaysIncludeBranches) {
ListBoxModel items = new ListBoxModel();
if (repositoryUrl == null || repositoryUrl.trim().isEmpty()) {
items.add("-- Configure repository URL first --", "");
return items;
}
// Create a temporary parameter definition to fetch branches
ActiveGitBranchesParameterDefinition tempDef =
new ActiveGitBranchesParameterDefinition("temp", repositoryUrl,
maxBranchCount > 0 ? maxBranchCount : 10, null);
tempDef.setCredentialsId(credentialsId);
tempDef.setBranchFilter(branchFilter);
tempDef.setAlwaysIncludeBranches(alwaysIncludeBranches);
try {
List<BranchInfo> branches = tempDef.fetchBranches();
if (branches.isEmpty()) {
items.add("-- No branches found --", "");
} else {
for (BranchInfo branch : branches) {
items.add(branch.getName(), branch.getName());
}
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to fetch branches", e);
items.add("-- Error fetching branches --", "");
}
return items;
}
/**
* Test connection to the repository.
*/
public FormValidation doTestConnection(@QueryParameter String repositoryUrl,
@QueryParameter String credentialsId,
@QueryParameter int maxBranchCount,
@QueryParameter String branchFilter,
@QueryParameter String alwaysIncludeBranches) {
if (repositoryUrl == null || repositoryUrl.trim().isEmpty()) {
return FormValidation.error("Repository URL is required");
}
ActiveGitBranchesParameterDefinition tempDef =
new ActiveGitBranchesParameterDefinition("temp", repositoryUrl,
maxBranchCount > 0 ? maxBranchCount : 10, null);
tempDef.setCredentialsId(credentialsId);
tempDef.setBranchFilter(branchFilter);
tempDef.setAlwaysIncludeBranches(alwaysIncludeBranches);
try {
List<BranchInfo> branches = tempDef.fetchBranchesInternal();
if (branches.isEmpty()) {
return FormValidation.warning("Connection successful, but no branches found matching the filter");
}
return FormValidation.ok("Success! Found " + branches.size() + " branches. " +
"Latest: " + branches.get(0).getName());
} catch (Exception e) {
return FormValidation.error("Failed to connect: " + e.getMessage());
}
}
}
}