diff --git a/.mvn_exec_spotless b/.mvn_exec_spotless
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/pom.xml b/pom.xml
index 20b8658367..0ab3a1247a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -36,10 +36,10 @@
rsandell
Robert Sandell
rsandell@cloudbees.com
+ http://rsandell.com
developer
- http://rsandell.com
mramonleon
@@ -54,10 +54,10 @@
Olivier Lamy
olamy@apache.org
https://about.me/olamy
- Australia/Brisbane
developer
+ Australia/Brisbane
@@ -95,67 +95,82 @@
+
+ io.jenkins
+ configuration-as-code
+ true
+
org.jenkins-ci.plugins
- structs
+ credentials
org.jenkins-ci.plugins
- git-client
+ credentials-binding
org.jenkins-ci.plugins
- credentials
+ git-client
org.jenkins-ci.plugins
- ssh-credentials
+ mailer
org.jenkins-ci.plugins
- scm-api
+ matrix-project
+ true
+
org.jenkins-ci.plugins
- script-security
+ parameterized-trigger
+ 2.43.1
+ true
- org.jenkins-ci.plugins.workflow
- workflow-step-api
+ org.jenkins-ci.plugins
+ promoted-builds
+ 3.11
+ true
- org.jenkins-ci.plugins.workflow
- workflow-scm-step
+ org.jenkins-ci.plugins
+ scm-api
- org.jenkins-ci.plugins.workflow
- workflow-cps
- tests
- test
+ org.jenkins-ci.plugins
+ script-security
org.jenkins-ci.plugins
- matrix-project
- true
+ ssh-credentials
org.jenkins-ci.plugins
- mailer
+ structs
-
org.jenkins-ci.plugins
- junit
- test
+ token-macro
+ true
- junit
- junit
+ org.jenkins-ci.plugins.workflow
+ workflow-scm-step
+
+
+ org.jenkins-ci.plugins.workflow
+ workflow-step-api
+
+
+ io.jenkins.configuration-as-code
+ test-harness
test
- org.mockito
- mockito-core
+ io.jenkins.plugins
+ pipeline-groovy-lib
test
@@ -164,17 +179,10 @@
3.14.1
test
-
-
- org.jenkins-ci.plugins
- credentials-binding
-
-
- org.jenkins-ci.plugins
- parameterized-trigger
- 2.43.1
- true
+ org.jenkins-ci.main
+ jenkins-test-harness
+ test
@@ -186,22 +194,15 @@
test
true
-
org.jenkins-ci.plugins
- token-macro
- true
+ git-tag-message
+ 1.7.1
+ test
org.jenkins-ci.plugins
- promoted-builds
- 3.11
- true
-
-
- org.jenkins-ci.plugins.workflow
- workflow-step-api
- tests
+ junit
test
@@ -212,12 +213,13 @@
org.jenkins-ci.plugins.workflow
- workflow-job
+ workflow-basic-steps
test
org.jenkins-ci.plugins.workflow
- workflow-basic-steps
+ workflow-cps
+ tests
test
@@ -227,34 +229,23 @@
org.jenkins-ci.plugins.workflow
- workflow-multibranch
- test
-
-
- io.jenkins.plugins
- pipeline-groovy-lib
+ workflow-job
test
- org.jenkins-ci.plugins
- git-tag-message
- 1.7.1
+ org.jenkins-ci.plugins.workflow
+ workflow-multibranch
test
-
-
- io.jenkins
- configuration-as-code
- true
-
- io.jenkins.configuration-as-code
- test-harness
+ org.jenkins-ci.plugins.workflow
+ workflow-step-api
+ tests
test
- org.jenkins-ci.main
- jenkins-test-harness
+ org.mockito
+ mockito-core
test
diff --git a/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java b/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java
index 346b121d6e..4540174e03 100644
--- a/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java
+++ b/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java
@@ -5,18 +5,6 @@
import hudson.Util;
import hudson.model.PersistentDescriptor;
import hudson.util.HttpResponses;
-import jenkins.model.GlobalConfiguration;
-import jenkins.model.GlobalConfigurationCategory;
-import jenkins.model.Jenkins;
-import net.jcip.annotations.GuardedBy;
-import net.sf.json.JSONObject;
-import org.jenkinsci.Symbol;
-import org.kohsuke.accmod.Restricted;
-import org.kohsuke.accmod.restrictions.NoExternalUse;
-import org.kohsuke.stapler.HttpResponse;
-import org.kohsuke.stapler.StaplerRequest;
-import org.kohsuke.stapler.interceptor.RequirePOST;
-
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -29,7 +17,17 @@
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
-
+import jenkins.model.GlobalConfiguration;
+import jenkins.model.GlobalConfigurationCategory;
+import jenkins.model.Jenkins;
+import net.jcip.annotations.GuardedBy;
+import net.sf.json.JSONObject;
+import org.jenkinsci.Symbol;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
+import org.kohsuke.stapler.HttpResponse;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.interceptor.RequirePOST;
@Extension
@Restricted(NoExternalUse.class)
@@ -75,7 +73,8 @@ public JSONObject generateApiToken(@NonNull String name) {
String plainTextApiToken = Util.toHexString(random);
assert plainTextApiToken.length() == 32;
- String apiTokenValueHashed = Util.toHexString(hashedBytes(plainTextApiToken.getBytes(StandardCharsets.US_ASCII)));
+ String apiTokenValueHashed =
+ Util.toHexString(hashedBytes(plainTextApiToken.getBytes(StandardCharsets.US_ASCII)));
HashedApiToken apiToken = new HashedApiToken(name, apiTokenValueHashed);
synchronized (this) {
@@ -172,7 +171,8 @@ private boolean match(byte[] hashedBytes) {
try {
hashFromHex = Util.fromHexString(hash);
} catch (NumberFormatException e) {
- LOGGER.log(Level.INFO, "The API token with name=[{0}] is not in hex-format and so cannot be used", name);
+ LOGGER.log(
+ Level.INFO, "The API token with name=[{0}] is not in hex-format and so cannot be used", name);
return false;
}
diff --git a/src/main/java/hudson/plugins/git/BranchSpec.java b/src/main/java/hudson/plugins/git/BranchSpec.java
index e083a75bc0..af1048089e 100644
--- a/src/main/java/hudson/plugins/git/BranchSpec.java
+++ b/src/main/java/hudson/plugins/git/BranchSpec.java
@@ -1,11 +1,10 @@
package hudson.plugins.git;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,11 +13,10 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
+import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
-import edu.umd.cs.findbugs.annotations.NonNull;
-
/**
* A specification of branches to build. Rather like a refspec.
*
@@ -43,12 +41,13 @@ public String getName() {
}
public void setName(String name) {
- if(name == null)
+ if (name == null) {
throw new IllegalArgumentException();
- else if(name.length() == 0)
+ } else if (name.length() == 0) {
this.name = "**";
- else
+ } else {
this.name = name.trim();
+ }
}
@DataBoundConstructor
@@ -56,6 +55,7 @@ public BranchSpec(String name) {
setName(name);
}
+ @Override
public String toString() {
return name;
}
@@ -97,7 +97,8 @@ public boolean matchesRepositoryBranch(String repositoryName, String branchName)
}
Pattern pattern = getPattern(new EnvVars(), repositoryName);
String branchWithoutRefs = cutRefs(branchName);
- return pattern.matcher(branchWithoutRefs).matches() || pattern.matcher(join(repositoryName, branchWithoutRefs)).matches();
+ return pattern.matcher(branchWithoutRefs).matches()
+ || pattern.matcher(join(repositoryName, branchWithoutRefs)).matches();
}
/**
@@ -113,15 +114,16 @@ public List filterMatching(Collection branches) {
public List filterMatching(Collection branches, EnvVars env) {
List items = new ArrayList<>();
-
- for(String b : branches) {
- if(matches(b, env))
+
+ for (String b : branches) {
+ if (matches(b, env)) {
items.add(b);
+ }
}
-
+
return items;
}
-
+
public List filterMatchingBranches(Collection branches) {
EnvVars env = new EnvVars();
return filterMatchingBranches(branches, env);
@@ -129,12 +131,13 @@ public List filterMatchingBranches(Collection branches) {
public List filterMatchingBranches(Collection branches, EnvVars env) {
List items = new ArrayList<>();
-
- for(Branch b : branches) {
- if(matches(b.getName(), env))
+
+ for (Branch b : branches) {
+ if (matches(b.getName(), env)) {
items.add(b);
+ }
}
-
+
return items;
}
@@ -172,7 +175,6 @@ private Pattern getPattern(EnvVars env, String repositoryName) {
// for legacy reasons (sic) we do support various branch spec format to declare remotes / branches
builder.append("(refs/heads/");
-
// if an unqualified branch was given, consider all remotes (with various possible syntaxes)
// so it will match branches from any remote repositories as the user probably intended
if (!expandedName.contains("**") && !expandedName.contains("/")) {
@@ -190,12 +192,12 @@ private String convertWildcardStringToRegex(String expandedName) {
// was the last token a wildcard?
boolean foundWildcard = false;
-
+
// split the string at the wildcards
StringTokenizer tokenizer = new StringTokenizer(expandedName, "*", true);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
-
+
// is this token is a wildcard?
if (token.equals("*")) {
// yes, was the previous token a wildcard?
@@ -204,13 +206,11 @@ private String convertWildcardStringToRegex(String expandedName) {
// match over any number of characters
builder.append(".*");
foundWildcard = false;
- }
- else {
+ } else {
// no, set foundWildcard to true and go on
foundWildcard = true;
}
- }
- else {
+ } else {
// no, was the previous token a wildcard?
if (foundWildcard) {
// yes, we found "*" followed by a non-wildcard
@@ -222,7 +222,7 @@ private String convertWildcardStringToRegex(String expandedName) {
builder.append(Pattern.quote(token));
}
}
-
+
// if the string ended with a wildcard add it now
if (foundWildcard) {
builder.append("[^/]*");
diff --git a/src/main/java/hudson/plugins/git/ChangelogToBranchOptions.java b/src/main/java/hudson/plugins/git/ChangelogToBranchOptions.java
index 00ccb4db0b..1f6b317d50 100644
--- a/src/main/java/hudson/plugins/git/ChangelogToBranchOptions.java
+++ b/src/main/java/hudson/plugins/git/ChangelogToBranchOptions.java
@@ -1,19 +1,19 @@
package hudson.plugins.git;
-import java.io.Serializable;
-import org.jenkinsci.Symbol;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
+import java.io.Serializable;
+import org.jenkinsci.Symbol;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* Options for the {@link hudson.plugins.git.extensions.impl.ChangelogToBranch} extension.
*
* @author Dirk Reske (dirk.reske@t-systems.com)
*/
-public class ChangelogToBranchOptions extends AbstractDescribableImpl implements Serializable {
+public class ChangelogToBranchOptions extends AbstractDescribableImpl
+ implements Serializable {
private String compareRemote;
private String compareTarget;
diff --git a/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java b/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java
index dd8c63119b..91d727bd70 100644
--- a/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java
+++ b/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java
@@ -1,9 +1,9 @@
package hudson.plugins.git;
-import hudson.views.ListViewColumn;
import hudson.Extension;
import hudson.model.Item;
import hudson.scm.SCM;
+import hudson.views.ListViewColumn;
import hudson.views.ListViewColumnDescriptor;
import java.util.ArrayList;
import java.util.List;
@@ -19,16 +19,16 @@
public class GitBranchSpecifierColumn extends ListViewColumn {
@DataBoundConstructor
- public GitBranchSpecifierColumn() { }
+ public GitBranchSpecifierColumn() {}
- public List getBranchSpecifier( final Item item ) {
+ public List getBranchSpecifier(final Item item) {
List branchSpec = new ArrayList<>();
SCMTriggerItem s = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item);
- if(s != null) {
- for(SCM scm : s.getSCMs()) {
+ if (s != null) {
+ for (SCM scm : s.getSCMs()) {
if (scm instanceof GitSCM) {
- GitSCM gitScm = (GitSCM)scm;
- for(BranchSpec spec : gitScm.getBranches()) {
+ GitSCM gitScm = (GitSCM) scm;
+ for (BranchSpec spec : gitScm.getBranches()) {
branchSpec.add(spec.getName());
}
}
@@ -53,7 +53,5 @@ public String getDisplayName() {
public boolean shownByDefault() {
return false;
}
-
}
-
}
diff --git a/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java b/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java
index 82952f8081..61a2769132 100644
--- a/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java
+++ b/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java
@@ -29,17 +29,16 @@
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.util.BuildData;
+import java.io.IOException;
import org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;
-import java.io.IOException;
-
/**
* {@code GIT_BRANCH} token that expands to the branch(es) that was built.
*
* @author Kohsuke Kawaguchi
*/
-@Extension(optional=true)
+@Extension(optional = true)
public class GitBranchTokenMacro extends DataBoundTokenMacro {
/**
* If true, list up all the branches not just the first one.
@@ -59,24 +58,30 @@ public boolean acceptsMacroName(String macroName) {
}
@Override
- public String evaluate(AbstractBuild, ?> context, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException {
+ public String evaluate(AbstractBuild, ?> context, TaskListener listener, String macroName)
+ throws MacroEvaluationException, IOException, InterruptedException {
return evaluate(context, context.getWorkspace(), listener, macroName);
}
@Override
- public String evaluate(Run, ?> context, FilePath workspace, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException {
+ public String evaluate(Run, ?> context, FilePath workspace, TaskListener listener, String macroName)
+ throws MacroEvaluationException, IOException, InterruptedException {
BuildData data = context.getAction(BuildData.class);
if (data == null) {
- return ""; // shall we report an error more explicitly?
+ return ""; // shall we report an error more explicitly?
}
Revision lb = data.getLastBuiltRevision();
- if (lb==null || lb.getBranches().isEmpty()) return "";
+ if (lb == null || lb.getBranches().isEmpty()) {
+ return "";
+ }
if (all) {
StringBuilder buf = new StringBuilder();
for (Branch b : lb.getBranches()) {
- if (buf.length()>0) buf.append(',');
+ if (buf.length() > 0) {
+ buf.append(',');
+ }
buf.append(format(b));
}
return buf.toString();
@@ -87,7 +92,9 @@ public String evaluate(Run, ?> context, FilePath workspace, TaskListener liste
private String format(Branch b) {
String n = b.getName();
- if (fullName) return n;
- return n.substring(n.indexOf('/')+1); // trim off '/'
+ if (fullName) {
+ return n;
+ }
+ return n.substring(n.indexOf('/') + 1); // trim off '/'
}
}
diff --git a/src/main/java/hudson/plugins/git/GitChangeLogParser.java b/src/main/java/hudson/plugins/git/GitChangeLogParser.java
index 3f9ab90905..d518db91b0 100644
--- a/src/main/java/hudson/plugins/git/GitChangeLogParser.java
+++ b/src/main/java/hudson/plugins/git/GitChangeLogParser.java
@@ -1,19 +1,13 @@
package hudson.plugins.git;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.model.Run;
import hudson.scm.ChangeLogParser;
import hudson.scm.RepositoryBrowser;
-import org.jenkinsci.plugins.gitclient.CliGitAPIImpl;
-import org.jenkinsci.plugins.gitclient.GitClient;
-
-import org.apache.commons.io.LineIterator;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -24,6 +18,9 @@
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
+import org.apache.commons.io.LineIterator;
+import org.jenkinsci.plugins.gitclient.CliGitAPIImpl;
+import org.jenkinsci.plugins.gitclient.GitClient;
/**
* Parse the git log
@@ -68,11 +65,13 @@ public GitChangeLogParser(GitClient git, boolean authorOrCommitter) {
* That keeps change summary truncation compatible with git client plugin 2.x and git plugin 3.x for users of
* command line git.
*/
- this.showEntireCommitSummaryInChanges = GitChangeSet.isShowEntireCommitSummaryInChanges() || !(git instanceof CliGitAPIImpl);
+ this.showEntireCommitSummaryInChanges =
+ GitChangeSet.isShowEntireCommitSummaryInChanges() || !(git instanceof CliGitAPIImpl);
}
-
+
public List parse(@NonNull InputStream changelog) throws IOException {
- try (Reader r = new InputStreamReader(changelog, StandardCharsets.UTF_8); LineIterator it = new LineIterator(r)) {
+ try (Reader r = new InputStreamReader(changelog, StandardCharsets.UTF_8);
+ LineIterator it = new LineIterator(r)) {
return parse(it);
}
}
@@ -81,8 +80,8 @@ public List parse(@NonNull List changelog) {
return parse(changelog.iterator());
}
- @Override public GitChangeSetList parse(Run build, RepositoryBrowser> browser, File changelogFile)
- throws IOException {
+ @Override
+ public GitChangeSetList parse(Run build, RepositoryBrowser> browser, File changelogFile) throws IOException {
// Parse the log file into GitChangeSet items - each one is a commit
try (Stream lineStream = Files.lines(changelogFile.toPath(), StandardCharsets.UTF_8)) {
return new GitChangeSetList(build, browser, parse(lineStream.iterator()));
@@ -103,8 +102,9 @@ private List parse(Iterator changelog) {
lines = new ArrayList<>();
}
- if (lines != null && lines.size()[0-9]+)?\t(.*)$");
- private static final Pattern AUTHOR_ENTRY = Pattern.compile("^"
- + PREFIX_AUTHOR + IDENTITY + "$");
- private static final Pattern COMMITTER_ENTRY = Pattern.compile("^"
- + PREFIX_COMMITTER + IDENTITY + "$");
+ private static final Pattern FILE_LOG_ENTRY =
+ Pattern.compile("^:[0-9]{6} [0-9]{6} ([0-9a-f]{40}) ([0-9a-f]{40}) ([ACDMRTUX])(?>[0-9]+)?\t(.*)$");
+ private static final Pattern AUTHOR_ENTRY = Pattern.compile("^" + PREFIX_AUTHOR + IDENTITY + "$");
+ private static final Pattern COMMITTER_ENTRY = Pattern.compile("^" + PREFIX_COMMITTER + IDENTITY + "$");
private static final Pattern RENAME_SPLIT = Pattern.compile("^(.*?)\t(.*)$");
private static final String NULL_HASH = "0000000000000000000000000000000000000000";
@@ -60,7 +57,7 @@ public class GitChangeSet extends ChangeLogSet.Entry {
private static final String ISO_8601_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ssX";
static final int TRUNCATE_LIMIT = 72;
- private final DateTimeFormatter [] dateFormatters;
+ private final DateTimeFormatter[] dateFormatters;
public static final Logger LOGGER = Logger.getLogger(GitChangeSet.class.getName());
@@ -84,6 +81,7 @@ public class GitChangeSet extends ChangeLogSet.Entry {
* just one branch, in which case it's safe to attribute the commit to that branch.
*/
private String committer;
+
private String committerEmail;
private String committerTime;
private String author;
@@ -170,7 +168,7 @@ public GitChangeSet(List lines, boolean authorOrCommitter, boolean retai
static boolean isShowEntireCommitSummaryInChanges() {
try {
return new DescriptorImpl().isShowEntireCommitSummaryInChanges();
- }catch (Throwable t){
+ } catch (Throwable t) {
return false;
}
}
@@ -180,21 +178,26 @@ private void parseCommit(List lines) {
StringBuilder message = new StringBuilder();
for (String line : lines) {
- if( line.length() < 1)
+ if (line.length() < 1) {
continue;
+ }
if (line.startsWith("commit ")) {
String[] split = line.split(" ");
- if (split.length > 1) this.id = split[1];
- else throw new IllegalArgumentException("Commit has no ID" + lines);
+ if (split.length > 1) {
+ this.id = split[1];
+ } else {
+ throw new IllegalArgumentException("Commit has no ID" + lines);
+ }
} else if (line.startsWith("tree ")) {
} else if (line.startsWith("parent ")) {
String[] split = line.split(" ");
// parent may be null for initial commit or changelog computed from a shallow clone
- if (split.length > 1) this.parentCommit = split[1];
+ if (split.length > 1) {
+ this.parentCommit = split[1];
+ }
} else if (line.startsWith(PREFIX_COMMITTER)) {
Matcher committerMatcher = COMMITTER_ENTRY.matcher(line);
- if (committerMatcher.matches()
- && committerMatcher.groupCount() >= 3) {
+ if (committerMatcher.matches() && committerMatcher.groupCount() >= 3) {
this.committer = committerMatcher.group(1).trim();
this.committerEmail = committerMatcher.group(2);
this.committerTime = isoDateFormat(committerMatcher.group(3));
@@ -217,8 +220,11 @@ private void parseCommit(List lines) {
String dst = null;
String path = fileMatcher.group(4);
char editMode = mode.charAt(0);
- if (editMode == 'M' || editMode == 'A' || editMode == 'D'
- || editMode == 'R' || editMode == 'C') {
+ if (editMode == 'M'
+ || editMode == 'A'
+ || editMode == 'D'
+ || editMode == 'R'
+ || editMode == 'C') {
src = parseHash(fileMatcher.group(1));
dst = parseHash(fileMatcher.group(2));
}
@@ -240,8 +246,7 @@ else if (editMode == 'C') {
String newPath = copySplitMatcher.group(2);
this.paths.add(new Path(src, dst, 'A', newPath, this));
}
- }
- else {
+ } else {
this.paths.add(new Path(src, dst, editMode, path, this));
}
}
@@ -255,16 +260,18 @@ else if (editMode == 'C') {
} else {
this.title = this.comment.substring(0, endOfFirstLine).trim();
}
- if(!showEntireCommitSummaryInChanges){
+ if (!showEntireCommitSummaryInChanges) {
this.title = splitString(this.title, TRUNCATE_LIMIT);
}
}
/* Package protected for testing */
static String splitString(String msg, int lineSize) {
- if (msg == null) return "";
+ if (msg == null) {
+ return "";
+ }
if (msg.matches(".*[\r\n].*")) {
- String [] msgArray = msg.split("[\r\n]");
+ String[] msgArray = msg.split("[\r\n]");
msg = msgArray[0];
}
if (msg.length() <= lineSize || !msg.contains(" ")) {
@@ -285,7 +292,7 @@ private String isoDateFormat(String s) {
int spaceIndex = s.indexOf(' ');
if (spaceIndex > 0) {
date = s.substring(0, spaceIndex);
- timezone = s.substring(spaceIndex+1);
+ timezone = s.substring(spaceIndex + 1);
}
if (NumberUtils.isDigits(date)) {
// legacy mode
@@ -328,7 +335,7 @@ public long getTimestamp() {
for (DateTimeFormatter dateFormatter : dateFormatters) {
try {
ZonedDateTime dateTime = ZonedDateTime.parse(date, dateFormatter);
- return dateTime.toEpochSecond()* 1000L;
+ return dateTime.toEpochSecond() * 1000L;
} catch (DateTimeParseException | IllegalArgumentException e) {
}
}
@@ -350,8 +357,7 @@ public void setParent(ChangeLogSet parent) {
super.setParent(parent);
}
- public @CheckForNull
- String getParentCommit() {
+ public @CheckForNull String getParentCommit() {
return parentCommit;
}
@@ -434,8 +440,11 @@ private User getUser(String idOrFullName, Boolean create) {
* @param useExistingAccountWithSameEmail true if users should be searched for their email attribute
* @return {@link User}
*/
- public User findOrCreateUser(String csAuthor, String csAuthorEmail, boolean createAccountBasedOnEmail,
- boolean useExistingAccountWithSameEmail) {
+ public User findOrCreateUser(
+ String csAuthor,
+ String csAuthorEmail,
+ boolean createAccountBasedOnEmail,
+ boolean useExistingAccountWithSameEmail) {
User user;
if (csAuthor == null) {
return User.getUnknown();
@@ -456,7 +465,7 @@ public User findOrCreateUser(String csAuthor, String csAuthorEmail, boolean crea
user = getUser(csAuthorEmail, !useExistingAccountWithSameEmail);
boolean setUserDetails = true;
if (user == null && useExistingAccountWithSameEmail && hasMailerPlugin()) {
- for(User existingUser : User.getAll()) {
+ for (User existingUser : User.getAll()) {
if (csAuthorEmail.equalsIgnoreCase(getMail(existingUser))) {
user = existingUser;
setUserDetails = false;
@@ -469,8 +478,9 @@ public User findOrCreateUser(String csAuthor, String csAuthorEmail, boolean crea
}
if (user != null && setUserDetails) {
user.setFullName(csAuthor);
- if (hasMailerPlugin())
+ if (hasMailerPlugin()) {
setMail(user, csAuthorEmail);
+ }
user.save();
}
} catch (AuthenticationException authException) {
@@ -578,13 +588,13 @@ public User getAuthor() {
if (authorOrCommitter) {
csAuthor = this.author;
csAuthorEmail = this.authorEmail;
- }
- else {
+ } else {
csAuthor = this.committer;
csAuthorEmail = this.committerEmail;
}
- return findOrCreateUser(csAuthor, csAuthorEmail, isCreateAccountBasedOnEmail(), isUseExistingAccountWithSameEmail());
+ return findOrCreateUser(
+ csAuthor, csAuthorEmail, isCreateAccountBasedOnEmail(), isUseExistingAccountWithSameEmail());
}
/**
@@ -622,12 +632,13 @@ public String getComment() {
/**
* Gets {@linkplain #getComment() the comment} fully marked up by {@link ChangeLogAnnotator}.
- @return annotated comment
+ * @return annotated comment
*/
public String getCommentAnnotated() {
MarkupText markup = new MarkupText(getComment());
- for (ChangeLogAnnotator a : ChangeLogAnnotator.all())
+ for (ChangeLogAnnotator a : ChangeLogAnnotator.all()) {
a.annotate(getParent().getRun(), this, markup);
+ }
return markup.toString(false);
}
@@ -636,7 +647,7 @@ public String getBranch() {
return null;
}
- @ExportedBean(defaultVisibility=999)
+ @ExportedBean(defaultVisibility = 999)
public static class Path implements AffectedFile {
private String src;
@@ -661,7 +672,8 @@ public String getDst() {
return dst;
}
- @Exported(name="file")
+ @Override
+ @Exported(name = "file")
public String getPath() {
return path;
}
@@ -670,15 +682,16 @@ public GitChangeSet getChangeSet() {
return changeSet;
}
+ @Override
@Exported
public EditType getEditType() {
switch (action) {
- case 'A':
- return EditType.ADD;
- case 'D':
- return EditType.DELETE;
- default:
- return EditType.EDIT;
+ case 'A':
+ return EditType.ADD;
+ case 'D':
+ return EditType.DELETE;
+ default:
+ return EditType.EDIT;
}
}
}
diff --git a/src/main/java/hudson/plugins/git/GitChangeSetList.java b/src/main/java/hudson/plugins/git/GitChangeSetList.java
index d013724c1b..94687b966c 100644
--- a/src/main/java/hudson/plugins/git/GitChangeSetList.java
+++ b/src/main/java/hudson/plugins/git/GitChangeSetList.java
@@ -3,11 +3,10 @@
import hudson.model.Run;
import hudson.scm.ChangeLogSet;
import hudson.scm.RepositoryBrowser;
-import org.kohsuke.stapler.export.Exported;
-
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import org.kohsuke.stapler.export.Exported;
/**
* List of changeset that went into a particular build.
@@ -18,16 +17,19 @@ public class GitChangeSetList extends ChangeLogSet {
/*package*/ GitChangeSetList(Run build, RepositoryBrowser> browser, List logs) {
super(build, browser);
- Collections.reverse(logs); // put new things first
+ Collections.reverse(logs); // put new things first
this.changeSets = Collections.unmodifiableList(logs);
- for (GitChangeSet log : logs)
+ for (GitChangeSet log : logs) {
log.setParent(this);
+ }
}
+ @Override
public boolean isEmptySet() {
return changeSets.isEmpty();
}
+ @Override
public Iterator iterator() {
return changeSets.iterator();
}
@@ -36,9 +38,9 @@ public List getLogs() {
return changeSets;
}
+ @Override
@Exported
public String getKind() {
return "git";
}
-
}
diff --git a/src/main/java/hudson/plugins/git/GitPublisher.java b/src/main/java/hudson/plugins/git/GitPublisher.java
index b61bdb3ef3..7773754f7f 100644
--- a/src/main/java/hudson/plugins/git/GitPublisher.java
+++ b/src/main/java/hudson/plugins/git/GitPublisher.java
@@ -21,6 +21,11 @@
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import hudson.util.FormValidation;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+import javax.servlet.ServletException;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.jenkinsci.plugins.gitclient.GitClient;
@@ -28,12 +33,6 @@
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
import org.kohsuke.stapler.*;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
public class GitPublisher extends Recorder implements Serializable {
private static final long serialVersionUID = 1L;
@@ -46,20 +45,21 @@ public class GitPublisher extends Recorder implements Serializable {
private boolean pushMerge;
private boolean pushOnlyIfSuccess;
private boolean forcePush;
-
+
private List tagsToPush;
// Pushes HEAD to these locations
private List branchesToPush;
// notes support
private List notesToPush;
-
+
@DataBoundConstructor
- public GitPublisher(List tagsToPush,
- List branchesToPush,
- List notesToPush,
- boolean pushOnlyIfSuccess,
- boolean pushMerge,
- boolean forcePush) {
+ public GitPublisher(
+ List tagsToPush,
+ List branchesToPush,
+ List notesToPush,
+ boolean pushOnlyIfSuccess,
+ boolean pushMerge,
+ boolean forcePush) {
this.tagsToPush = tagsToPush;
this.branchesToPush = branchesToPush;
this.notesToPush = notesToPush;
@@ -72,7 +72,7 @@ public GitPublisher(List tagsToPush,
public boolean isPushOnlyIfSuccess() {
return pushOnlyIfSuccess;
}
-
+
public boolean isPushMerge() {
return pushMerge;
}
@@ -101,7 +101,7 @@ public boolean isPushNotes() {
}
return !notesToPush.isEmpty();
}
-
+
public List getTagsToPush() {
if (tagsToPush == null) {
tagsToPush = new ArrayList<>();
@@ -117,7 +117,7 @@ public List getBranchesToPush() {
return branchesToPush;
}
-
+
public List getNotesToPush() {
if (notesToPush == null) {
notesToPush = new ArrayList<>();
@@ -125,31 +125,30 @@ public List getNotesToPush() {
return notesToPush;
}
-
-
+
+ @Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
- private String replaceAdditionalEnvironmentalVariables(String input, AbstractBuild, ?> build){
- if (build == null){
- return input;
- }
+ private String replaceAdditionalEnvironmentalVariables(String input, AbstractBuild, ?> build) {
+ if (build == null) {
+ return input;
+ }
String buildResult = "";
Result result = build.getResult();
if (result != null) {
buildResult = result.toString();
}
String buildDuration = build.getDurationString().replaceAll("and counting", "");
-
+
input = input.replaceAll("\\$BUILDRESULT", buildResult);
input = input.replaceAll("\\$BUILDDURATION", buildDuration);
return input;
}
-
+
@Override
- public boolean perform(AbstractBuild, ?> build,
- Launcher launcher, final BuildListener listener)
+ public boolean perform(AbstractBuild, ?> build, Launcher launcher, final BuildListener listener)
throws InterruptedException, IOException {
// during matrix build, the push back would happen at the very end only once for the whole matrix,
@@ -172,15 +171,16 @@ public boolean perform(AbstractBuild, ?> build,
// If pushOnlyIfSuccess is selected and the build is not a success, don't push.
if (pushOnlyIfSuccess && buildResult.isWorseThan(Result.SUCCESS)) {
- listener.getLogger().println("Build did not succeed and the project is configured to only push after a successful build, so no pushing will occur.");
+ listener.getLogger()
+ .println(
+ "Build did not succeed and the project is configured to only push after a successful build, so no pushing will occur.");
return true;
- }
- else {
+ } else {
EnvVars environment = build.getEnvironment(listener);
UnsupportedCommand cmd = new UnsupportedCommand();
cmd.gitPublisher(true);
- final GitClient git = gitSCM.createClient(listener, environment, build, build.getWorkspace(), cmd);
+ final GitClient git = gitSCM.createClient(listener, environment, build, build.getWorkspace(), cmd);
URIish remoteURI;
@@ -191,8 +191,9 @@ public boolean perform(AbstractBuild, ?> build,
// if PerBuildTag, then tag every build
// We delete the old tag generated by the SCM plugin
String buildnumber = "jenkins-" + projectName.replace(" ", "_") + "-" + buildNumber;
- if (git.tagExists(buildnumber))
+ if (git.tagExists(buildnumber)) {
git.deleteTag(buildnumber);
+ }
// And add the success / fail state into the tag.
buildnumber += "-" + buildResult.toString();
@@ -211,14 +212,19 @@ public boolean perform(AbstractBuild, ?> build,
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
- listener.getLogger().println("Pushing HEAD to branch " + mergeTarget + " of " + remote.getName() + " repository");
+ listener.getLogger()
+ .println("Pushing HEAD to branch " + mergeTarget + " of " + remote.getName()
+ + " repository");
remoteURI = remote.getURIs().get(0);
- PushCommand push = git.push().to(remoteURI).ref("HEAD:" + mergeTarget).force(forcePush);
+ PushCommand push = git.push()
+ .to(remoteURI)
+ .ref("HEAD:" + mergeTarget)
+ .force(forcePush);
push.execute();
} else {
- //listener.getLogger().println("Pushing result " + buildnumber + " to origin repository");
- //git.push(null);
+ // listener.getLogger().println("Pushing result " + buildnumber + " to origin repository");
+ // git.push(null);
}
} catch (FormException | GitException e) {
e.printStackTrace(listener.error("Failed to push merge to origin repository"));
@@ -228,22 +234,25 @@ public boolean perform(AbstractBuild, ?> build,
if (isPushTags()) {
for (final TagToPush t : tagsToPush) {
- if (t.getTagName() == null)
+ if (t.getTagName() == null) {
throw new AbortException("No tag to push defined");
+ }
- if (t.getTargetRepoName() == null)
+ if (t.getTargetRepoName() == null) {
throw new AbortException("No target repo to push to defined");
+ }
final String tagName = environment.expand(t.getTagName());
final String tagMessage = hudson.Util.fixNull(environment.expand(t.getTagMessage()));
final String targetRepo = environment.expand(t.getTargetRepoName());
try {
- // Lookup repository with unexpanded name as GitSCM stores them unexpanded
+ // Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(t.getTargetRepoName());
- if (remote == null)
+ if (remote == null) {
throw new AbortException("No repository found for target repo name " + targetRepo);
+ }
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
@@ -251,21 +260,21 @@ public boolean perform(AbstractBuild, ?> build,
boolean tagExists = git.tagExists(tagName.replace(' ', '_'));
if (t.isCreateTag() || t.isUpdateTag()) {
if (tagExists && !t.isUpdateTag()) {
- throw new AbortException("Tag " + tagName + " already exists and Create Tag is specified, so failing.");
+ throw new AbortException(
+ "Tag " + tagName + " already exists and Create Tag is specified, so failing.");
}
- if (tagMessage.length()==0) {
+ if (tagMessage.length() == 0) {
git.tag(tagName, "Jenkins Git plugin tagging with " + tagName);
} else {
git.tag(tagName, tagMessage);
}
- }
- else if (!tagExists) {
- throw new AbortException("Tag " + tagName + " does not exist and Create Tag is not specified, so failing.");
+ } else if (!tagExists) {
+ throw new AbortException(
+ "Tag " + tagName + " does not exist and Create Tag is not specified, so failing.");
}
- listener.getLogger().println("Pushing tag " + tagName + " to repo "
- + targetRepo);
+ listener.getLogger().println("Pushing tag " + tagName + " to repo " + targetRepo);
remoteURI = remote.getURIs().get(0);
PushCommand push = git.push().to(remoteURI).ref(tagName).force(forcePush);
@@ -276,24 +285,27 @@ else if (!tagExists) {
}
}
}
-
+
if (isPushBranches()) {
for (final BranchToPush b : branchesToPush) {
- if (b.getBranchName() == null)
+ if (b.getBranchName() == null) {
throw new AbortException("No branch to push defined");
+ }
- if (b.getTargetRepoName() == null)
+ if (b.getTargetRepoName() == null) {
throw new AbortException("No branch repo to push to defined");
+ }
final String branchName = environment.expand(b.getBranchName());
final String targetRepo = environment.expand(b.getTargetRepoName());
-
+
try {
- // Lookup repository with unexpanded name as GitSCM stores them unexpanded
+ // Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(b.getTargetRepoName());
- if (remote == null)
+ if (remote == null) {
throw new AbortException("No repository found for target repo name " + targetRepo);
+ }
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
@@ -301,17 +313,24 @@ else if (!tagExists) {
if (b.getRebaseBeforePush()) {
listener.getLogger().println("Fetch and rebase with " + branchName + " of " + targetRepo);
- git.fetch_().from(remoteURI, remote.getFetchRefSpecs()).execute();
+ git.fetch_()
+ .from(remoteURI, remote.getFetchRefSpecs())
+ .execute();
if (!git.revParse("HEAD").equals(git.revParse(targetRepo + "/" + branchName))) {
- git.rebase().setUpstream(targetRepo + "/" + branchName).execute();
+ git.rebase()
+ .setUpstream(targetRepo + "/" + branchName)
+ .execute();
} else {
- listener.getLogger().println("No rebase required. HEAD equals " + targetRepo + "/" + branchName);
+ listener.getLogger()
+ .println("No rebase required. HEAD equals " + targetRepo + "/" + branchName);
}
}
- listener.getLogger().println("Pushing HEAD to branch " + branchName + " at repo "
- + targetRepo);
- PushCommand push = git.push().to(remoteURI).ref("HEAD:" + branchName).force(forcePush);
+ listener.getLogger().println("Pushing HEAD to branch " + branchName + " at repo " + targetRepo);
+ PushCommand push = git.push()
+ .to(remoteURI)
+ .ref("HEAD:" + branchName)
+ .force(forcePush);
push.execute();
} catch (GitException e) {
e.printStackTrace(listener.error("Failed to push branch " + branchName + " to " + targetRepo));
@@ -319,11 +338,12 @@ else if (!tagExists) {
}
}
}
-
+
if (isPushNotes()) {
for (final NoteToPush b : notesToPush) {
- if (b.getnoteMsg() == null)
+ if (b.getnoteMsg() == null) {
throw new AbortException("No note to push defined");
+ }
b.setEmptyTargetRepoToOrigin();
String noteMsgTmp = environment.expand(b.getnoteMsg());
@@ -331,9 +351,9 @@ else if (!tagExists) {
final String noteNamespace = environment.expand(b.getnoteNamespace());
final String targetRepo = environment.expand(b.getTargetRepoName());
final boolean noteReplace = b.getnoteReplace();
-
+
try {
- // Lookup repository with unexpanded name as GitSCM stores them unexpanded
+ // Lookup repository with unexpanded name as GitSCM stores them unexpanded
RemoteConfig remote = gitSCM.getRepositoryByName(b.getTargetRepoName());
if (remote == null) {
@@ -344,23 +364,27 @@ else if (!tagExists) {
// expand environment variables in remote repository
remote = gitSCM.getParamExpandedRepo(environment, remote);
- listener.getLogger().println("Adding note to namespace \""+noteNamespace +"\":\n" + noteMsg + "\n******" );
+ listener.getLogger()
+ .println(
+ "Adding note to namespace \"" + noteNamespace + "\":\n" + noteMsg + "\n******");
- if ( noteReplace )
- git.addNote( noteMsg, noteNamespace );
- else
- git.appendNote( noteMsg, noteNamespace );
+ if (noteReplace) {
+ git.addNote(noteMsg, noteNamespace);
+ } else {
+ git.appendNote(noteMsg, noteNamespace);
+ }
remoteURI = remote.getURIs().get(0);
- PushCommand push = git.push().to(remoteURI).ref("refs/notes/*").force(forcePush);
+ PushCommand push =
+ git.push().to(remoteURI).ref("refs/notes/*").force(forcePush);
push.execute();
} catch (GitException e) {
- e.printStackTrace(listener.error("Failed to add note: \n" + noteMsg + "\n******"));
+ e.printStackTrace(listener.error("Failed to add note: \n" + noteMsg + "\n******"));
return false;
}
}
}
-
+
return true;
}
}
@@ -372,8 +396,9 @@ else if (!tagExists) {
*/
protected Object readResolve() {
// Default unspecified to v0
- if(configVersion == null)
+ if (configVersion == null) {
this.configVersion = 0L;
+ }
if (this.configVersion < 1L) {
if (tagsToPush == null) {
@@ -383,9 +408,10 @@ protected Object readResolve() {
return this;
}
-
- @Extension(ordinal=-1)
+
+ @Extension(ordinal = -1)
public static class DescriptorImpl extends BuildStepDescriptor {
+ @Override
public String getDisplayName() {
return "Git Publisher";
}
@@ -405,8 +431,8 @@ public String getHelpFile() {
* @throws IOException on input or output error
*/
public FormValidation doCheck(@AncestorInPath AbstractProject project, @QueryParameter String value)
- throws IOException {
- return FilePath.validateFileMask(project.getSomeWorkspace(),value);
+ throws IOException {
+ return FilePath.validateFileMask(project.getSomeWorkspace(), value);
}
public FormValidation doCheckTagName(@QueryParameter String value) {
@@ -416,40 +442,41 @@ public FormValidation doCheckTagName(@QueryParameter String value) {
public FormValidation doCheckBranchName(@QueryParameter String value) {
return checkFieldNotEmpty(value, Messages.GitPublisher_Check_BranchName());
}
-
+
public FormValidation doCheckNoteMsg(@QueryParameter String value) {
return checkFieldNotEmpty(value, Messages.GitPublisher_Check_Note());
}
-
- public FormValidation doCheckRemote(
- @AncestorInPath AbstractProject project, StaplerRequest req)
+
+ public FormValidation doCheckRemote(@AncestorInPath AbstractProject project, StaplerRequest req)
throws IOException, ServletException {
String remote = req.getParameter("value");
boolean isMerge = req.getParameter("isMerge") != null;
// Added isMerge because we don't want to allow empty remote names
// for tag/branch pushes.
- if (remote.length() == 0 && isMerge)
+ if (remote.length() == 0 && isMerge) {
return FormValidation.ok();
+ }
- FormValidation validation = checkFieldNotEmpty(remote,
- Messages.GitPublisher_Check_RemoteName());
- if (validation.kind != FormValidation.Kind.OK)
+ FormValidation validation = checkFieldNotEmpty(remote, Messages.GitPublisher_Check_RemoteName());
+ if (validation.kind != FormValidation.Kind.OK) {
return validation;
+ }
if (!(project.getScm() instanceof GitSCM)) {
- return FormValidation.warning("Project not currently configured to use Git; cannot check remote repository");
+ return FormValidation.warning(
+ "Project not currently configured to use Git; cannot check remote repository");
}
GitSCM scm = (GitSCM) project.getScm();
- if (scm.getRepositoryByName(remote) == null)
- return FormValidation
- .error("No remote repository configured with name '"
- + remote + "'");
+ if (scm.getRepositoryByName(remote) == null) {
+ return FormValidation.error("No remote repository configured with name '" + remote + "'");
+ }
return FormValidation.ok();
}
-
+
+ @Override
public boolean isApplicable(Class extends AbstractProject> jobType) {
return true;
}
@@ -466,15 +493,15 @@ private FormValidation checkFieldNotEmpty(String value, String field) {
}
}
- public static abstract class PushConfig extends AbstractDescribableImpl implements Serializable {
+ public abstract static class PushConfig extends AbstractDescribableImpl implements Serializable {
private static final long serialVersionUID = 1L;
-
+
private String targetRepoName;
public PushConfig(String targetRepoName) {
this.targetRepoName = Util.fixEmptyAndTrim(targetRepoName);
}
-
+
public String getTargetRepoName() {
return targetRepoName;
}
@@ -482,10 +509,10 @@ public String getTargetRepoName() {
public void setTargetRepoName(String targetRepoName) {
this.targetRepoName = targetRepoName;
}
-
- public void setEmptyTargetRepoToOrigin(){
- if (targetRepoName == null || targetRepoName.trim().length()==0){
- targetRepoName = "origin";
+
+ public void setEmptyTargetRepoToOrigin() {
+ if (targetRepoName == null || targetRepoName.trim().length() == 0) {
+ targetRepoName = "origin";
}
}
}
@@ -545,7 +572,8 @@ public boolean isUpdateTag() {
}
@DataBoundConstructor
- public TagToPush(String targetRepoName, String tagName, String tagMessage, boolean createTag, boolean updateTag) {
+ public TagToPush(
+ String targetRepoName, String tagName, String tagMessage, boolean createTag, boolean updateTag) {
super(targetRepoName);
this.tagName = Util.fixEmptyAndTrim(tagName);
this.tagMessage = tagMessage;
@@ -561,7 +589,6 @@ public String getDisplayName() {
}
}
}
-
public static final class NoteToPush extends PushConfig {
@@ -572,26 +599,26 @@ public static final class NoteToPush extends PushConfig {
public String getnoteMsg() {
return noteMsg;
}
-
+
public String getnoteNamespace() {
- return noteNamespace;
+ return noteNamespace;
}
-
+
public boolean getnoteReplace() {
- return noteReplace;
+ return noteReplace;
}
@DataBoundConstructor
- public NoteToPush( String targetRepoName, String noteMsg, String noteNamespace, boolean noteReplace ) {
- super(targetRepoName);
+ public NoteToPush(String targetRepoName, String noteMsg, String noteNamespace, boolean noteReplace) {
+ super(targetRepoName);
this.noteMsg = Util.fixEmptyAndTrim(noteMsg);
this.noteReplace = noteReplace;
-
- if ( noteNamespace != null && noteNamespace.trim().length()!=0)
- this.noteNamespace = Util.fixEmptyAndTrim(noteNamespace);
- else
- this.noteNamespace = "master";
-
+
+ if (noteNamespace != null && noteNamespace.trim().length() != 0) {
+ this.noteNamespace = Util.fixEmptyAndTrim(noteNamespace);
+ } else {
+ this.noteNamespace = "master";
+ }
}
@Extension
@@ -602,5 +629,4 @@ public String getDisplayName() {
}
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java
index 29bab615a3..318c505725 100644
--- a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java
+++ b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java
@@ -41,51 +41,50 @@
*/
public class GitRevisionBuildParameters extends AbstractBuildParameters {
- private boolean combineQueuedCommits = false;
+ private boolean combineQueuedCommits = false;
- @DataBoundConstructor
- public GitRevisionBuildParameters(boolean combineQueuedCommits) {
- this.combineQueuedCommits = combineQueuedCommits;
- }
+ @DataBoundConstructor
+ public GitRevisionBuildParameters(boolean combineQueuedCommits) {
+ this.combineQueuedCommits = combineQueuedCommits;
+ }
- public GitRevisionBuildParameters() {
- }
+ public GitRevisionBuildParameters() {}
- @Override
- public Action getAction(AbstractBuild,?> build, TaskListener listener) {
- BuildData data = build.getAction(BuildData.class);
- if (data == null && Jenkins.get().getPlugin("promoted-builds") != null) {
+ @Override
+ public Action getAction(AbstractBuild, ?> build, TaskListener listener) {
+ BuildData data = build.getAction(BuildData.class);
+ if (data == null && Jenkins.get().getPlugin("promoted-builds") != null) {
if (build instanceof hudson.plugins.promoted_builds.Promotion) {
// We are running as a build promotion, so have to retrieve the git scm from target job
- AbstractBuild,?> targetBuild = ((hudson.plugins.promoted_builds.Promotion) build).getTargetBuild();
+ AbstractBuild, ?> targetBuild = ((hudson.plugins.promoted_builds.Promotion) build).getTargetBuild();
if (targetBuild != null) {
data = targetBuild.getAction(BuildData.class);
}
}
}
if (data == null) {
- listener.getLogger().println("This project doesn't use Git as SCM. Can't pass the revision to downstream");
- return null;
- }
+ listener.getLogger().println("This project doesn't use Git as SCM. Can't pass the revision to downstream");
+ return null;
+ }
- Revision lastBuiltRevision = data.getLastBuiltRevision();
- if (lastBuiltRevision == null) {
- listener.getLogger().println("Missing build information. Can't pass the revision to downstream");
- return null;
- }
+ Revision lastBuiltRevision = data.getLastBuiltRevision();
+ if (lastBuiltRevision == null) {
+ listener.getLogger().println("Missing build information. Can't pass the revision to downstream");
+ return null;
+ }
- return new RevisionParameterAction(lastBuiltRevision, getCombineQueuedCommits());
- }
+ return new RevisionParameterAction(lastBuiltRevision, getCombineQueuedCommits());
+ }
- public boolean getCombineQueuedCommits() {
- return combineQueuedCommits;
- }
+ public boolean getCombineQueuedCommits() {
+ return combineQueuedCommits;
+ }
- @Extension(optional=true)
- public static class DescriptorImpl extends Descriptor {
- @Override
- public String getDisplayName() {
- return "Pass-through Git Commit that was built";
- }
- }
+ @Extension(optional = true)
+ public static class DescriptorImpl extends Descriptor {
+ @Override
+ public String getDisplayName() {
+ return "Pass-through Git Commit that was built";
+ }
+ }
}
diff --git a/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java b/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java
index 895e096948..a848820321 100644
--- a/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java
+++ b/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java
@@ -29,23 +29,22 @@
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.util.BuildData;
+import java.io.IOException;
import org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;
-import java.io.IOException;
-
/**
* {@code GIT_REVISION} token that expands to the SHA1 of the commit that was built.
*
* @author Kohsuke Kawaguchi
*/
-@Extension(optional=true)
+@Extension(optional = true)
public class GitRevisionTokenMacro extends DataBoundTokenMacro {
/**
* Number of chars to use
*/
@Parameter
- public int length=40;
+ public int length = 40;
@Override
public boolean acceptsMacroName(String macroName) {
@@ -53,21 +52,25 @@ public boolean acceptsMacroName(String macroName) {
}
@Override
- public String evaluate(Run,?> context, FilePath workspace, TaskListener listener, String macroName) throws MacroEvaluationException {
+ public String evaluate(Run, ?> context, FilePath workspace, TaskListener listener, String macroName)
+ throws MacroEvaluationException {
BuildData data = context.getAction(BuildData.class);
if (data == null) {
- return ""; // shall we report an error more explicitly?
+ return ""; // shall we report an error more explicitly?
}
Revision lb = data.getLastBuiltRevision();
- if (lb==null) return "";
+ if (lb == null) {
+ return "";
+ }
String s = lb.getSha1String();
- return s.substring(0,Math.min(length,s.length()));
+ return s.substring(0, Math.min(length, s.length()));
}
@Override
- public String evaluate(AbstractBuild, ?> context, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException {
+ public String evaluate(AbstractBuild, ?> context, TaskListener listener, String macroName)
+ throws MacroEvaluationException, IOException, InterruptedException {
return evaluate(context, context.getWorkspace(), listener, macroName);
}
}
diff --git a/src/main/java/hudson/plugins/git/GitSCM.java b/src/main/java/hudson/plugins/git/GitSCM.java
index 45dba933e6..1aabe2fc43 100644
--- a/src/main/java/hudson/plugins/git/GitSCM.java
+++ b/src/main/java/hudson/plugins/git/GitSCM.java
@@ -1,5 +1,9 @@
package hudson.plugins.git;
+import static hudson.init.InitMilestone.JOB_LOADED;
+import static hudson.init.InitMilestone.PLUGINS_STARTED;
+import static hudson.scm.PollingResult.*;
+
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
@@ -7,20 +11,22 @@
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.Util;
import hudson.init.Initializer;
import hudson.model.*;
import hudson.model.Descriptor.FormException;
+import hudson.plugins.git.browser.BitbucketWeb;
+import hudson.plugins.git.browser.GitLab;
import hudson.plugins.git.browser.GitRepositoryBrowser;
+import hudson.plugins.git.browser.GithubWeb;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import hudson.plugins.git.extensions.impl.AuthorInChangelog;
@@ -28,13 +34,14 @@
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.PathRestriction;
import hudson.plugins.git.extensions.impl.PreBuildMerge;
+import hudson.plugins.git.extensions.impl.RelativeTargetDirectory;
+import hudson.plugins.git.extensions.impl.ScmName;
import hudson.plugins.git.opt.PreBuildMergeOptions;
-import hudson.plugins.git.util.Build;
import hudson.plugins.git.util.*;
+import hudson.plugins.git.util.Build;
import hudson.remoting.Channel;
import hudson.scm.AbstractScmTagAction;
import hudson.scm.ChangeLogParser;
@@ -49,30 +56,7 @@
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 hudson.util.LogTaskListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
@@ -94,22 +78,33 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
-
-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 javax.servlet.ServletException;
+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.Symbol;
+import org.jenkinsci.plugins.gitclient.*;
+import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
+import org.kohsuke.stapler.DataBoundConstructor;
+import org.kohsuke.stapler.DataBoundSetter;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.export.Exported;
/**
* Git SCM.
@@ -123,6 +118,7 @@
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);
@@ -136,21 +132,29 @@ public class GitSCM extends GitSCMBackwardCompatibility {
* All the remote repositories that we know about.
*/
private List userRemoteConfigs;
+
private transient List remoteRepositories;
/**
* All the branches that we wish to care about building.
*/
private List branches;
+
private boolean doGenerateSubmoduleConfigurations = false;
+ @CheckForNull
+ private String commitMessage;
+
@CheckForNull
public String gitTool;
+
@CheckForNull
private GitRepositoryBrowser browser;
+
private Collection 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_TITLE = "GIT_COMMIT_TITLE";
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";
@@ -159,8 +163,8 @@ public class GitSCM extends GitSCMBackwardCompatibility {
/**
* All the configured extensions attached to this.
*/
- @SuppressFBWarnings(value="SE_BAD_FIELD", justification="Known non-serializable field")
- private DescribableList extensions;
+ @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Known non-serializable field")
+ private DescribableList extensions;
@Whitelisted
@Deprecated
@@ -169,8 +173,7 @@ public Collection getSubmoduleCfg() {
}
@DataBoundSetter
- public void setSubmoduleCfg(Collection submoduleCfg) {
- }
+ public void setSubmoduleCfg(Collection submoduleCfg) {}
public static List createRepoList(String url, String credentialsId) {
List repoList = new ArrayList<>();
@@ -188,7 +191,9 @@ public GitSCM(String repositoryUrl) {
this(
createRepoList(repositoryUrl, null),
Collections.singletonList(new BranchSpec("")),
- null, null, Collections.emptyList());
+ null,
+ null,
+ Collections.emptyList());
}
@Deprecated
@@ -227,7 +232,7 @@ public GitSCM(
this.configVersion = 2L;
this.gitTool = gitTool;
- this.extensions = new DescribableList<>(Saveable.NOOP,Util.fixNull(extensions));
+ this.extensions = new DescribableList<>(Saveable.NOOP, Util.fixNull(extensions));
getBuildChooser(); // set the gitSCM field.
}
@@ -239,6 +244,7 @@ public GitSCM(
*
* @since 2.0
*/
+ @Override
@Whitelisted
public DescribableList getExtensions() {
return extensions;
@@ -290,7 +296,6 @@ public Object readResolve() throws IOException {
}
}
-
if (configVersion < 1 && branches != null) {
// Migrate the branch specs from
// single * wildcard, to ** wildcard.
@@ -303,15 +308,17 @@ public Object readResolve() throws IOException {
if (remoteRepositories != null && userRemoteConfigs == null) {
userRemoteConfigs = new ArrayList<>();
- for(RemoteConfig cfg : remoteRepositories) {
+ for (RemoteConfig cfg : remoteRepositories) {
// converted as in config.jelly
String url = "";
- if (cfg.getURIs().size() > 0 && cfg.getURIs().get(0) != null)
+ 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)
+ 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));
}
@@ -328,12 +335,13 @@ public Object readResolve() throws IOException {
}
}
- if (extensions==null)
+ if (extensions == null) {
extensions = new DescribableList<>(Saveable.NOOP);
+ }
readBackExtensionsFromLegacy();
- if (choosingStrategy != null && getBuildChooser().getClass()==DefaultBuildChooser.class) {
+ if (choosingStrategy != null && getBuildChooser().getClass() == DefaultBuildChooser.class) {
for (BuildChooserDescriptor d : BuildChooser.all()) {
if (choosingStrategy.equals(d.getLegacyId())) {
try {
@@ -360,36 +368,33 @@ public void setBrowser(GitRepositoryBrowser browser) {
this.browser = browser;
}
- private static final String HOSTNAME_MATCH
- = "([\\w\\d[-.]]+)" // hostname
+ 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 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
- ),
+ "(?:\\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
- )
+ "(?: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() {
+ @Override
+ public RepositoryBrowser> guessBrowser() {
Set webUrls = new HashSet<>();
if (remoteRepositories != null) {
for (RemoteConfig config : remoteRepositories) {
@@ -459,14 +464,17 @@ public BuildChooser getBuildChooser() {
BuildChooser bc;
BuildChooserSetting bcs = getExtensions().get(BuildChooserSetting.class);
- if (bcs!=null) bc = bcs.getBuildChooser();
- else bc = new DefaultBuildChooser();
+ 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) {
+ if (buildChooser.getClass() == DefaultBuildChooser.class) {
getExtensions().remove(BuildChooserSetting.class);
} else {
getExtensions().replace(new BuildChooserSetting(buildChooser));
@@ -489,7 +497,8 @@ public String getParamLocalBranch(Run, ?> build) throws IOException, Interrupt
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));
+ return getParameterString(
+ localBranch == null ? null : localBranch.getLocalBranch(), build.getEnvironment(listener));
}
@Deprecated
@@ -507,7 +516,8 @@ public List getParamExpandedRepos(Run, ?> build) throws IOExcept
* @throws InterruptedException when interrupted
* @return can be empty but never null.
*/
- public List getParamExpandedRepos(Run, ?> build, TaskListener listener) throws IOException, InterruptedException {
+ public List getParamExpandedRepos(Run, ?> build, TaskListener listener)
+ throws IOException, InterruptedException {
List expandedRepos = new ArrayList<>();
EnvVars env = build.getEnvironment(listener);
@@ -527,7 +537,7 @@ public List getParamExpandedRepos(Run, ?> build, TaskListener li
*/
public RemoteConfig getParamExpandedRepo(EnvVars env, RemoteConfig remoteRepository) {
List refSpecs = getRefSpecs(remoteRepository, env);
- return newRemoteConfig(
+ return newRemoteConfig(
getParameterString(remoteRepository.getName(), env),
getParameterString(remoteRepository.getURIs().get(0).toPrivateString(), env),
refSpecs.toArray(new RefSpec[0]));
@@ -555,7 +565,8 @@ public List getUserRemoteConfigs() {
@Whitelisted
public List getRepositories() {
- // Handle null-value to ensure backwards-compatibility, ie project configuration missing the XML element
+ // Handle null-value to ensure backwards-compatibility, ie project configuration missing the XML
+ // element
if (remoteRepositories == null) {
return new ArrayList<>();
}
@@ -632,17 +643,16 @@ private String getSingleBranch(EnvVars env) {
String repository = null;
if (getRepositories().size() != 1) {
- for (RemoteConfig repo : getRepositories()) {
- if (branch.startsWith(repo.getName() + "/")) {
- repository = repo.getName();
- break;
- }
- }
+ for (RemoteConfig repo : getRepositories()) {
+ if (branch.startsWith(repo.getName() + "/")) {
+ repository = repo.getName();
+ break;
+ }
+ }
} else {
- repository = getRepositories().get(0).getName();
+ repository = getRepositories().get(0).getName();
}
-
// replace repository wildcard with repository name
if (branch.startsWith("*/") && repository != null) {
branch = repository + branch.substring(1);
@@ -666,7 +676,9 @@ private String getSingleBranch(EnvVars env) {
}
@Override
- public SCMRevisionState calcRevisionsFromBuild(Run, ?> abstractBuild, FilePath workspace, Launcher launcher, TaskListener taskListener) throws IOException, InterruptedException {
+ public SCMRevisionState calcRevisionsFromBuild(
+ Run, ?> abstractBuild, FilePath workspace, Launcher launcher, TaskListener taskListener)
+ throws IOException, InterruptedException {
return SCMRevisionState.NONE;
}
@@ -679,23 +691,33 @@ public boolean requiresWorkspaceForPolling() {
/* Package protected for test access */
boolean requiresWorkspaceForPolling(EnvVars environment) {
for (GitSCMExtension ext : getExtensions()) {
- if (ext.requiresWorkspaceForPolling()) return true;
+ 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 {
+ 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){
+ 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 {
+ 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());
@@ -712,13 +734,17 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
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 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();
+ 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);
@@ -729,12 +755,12 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
for (URIish urIish : remoteConfig.getURIs()) {
String gitRepo = urIish.toString();
Map heads = git.getHeadRev(gitRepo);
- if (heads==null || heads.isEmpty()) {
+ 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);
+ listener.getLogger().println("Found " + heads.size() + " remote heads on " + urIish);
Iterator> it = heads.entrySet().iterator();
while (it.hasNext()) {
@@ -747,7 +773,9 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
}
}
if (!match) {
- listener.getLogger().println("Ignoring " + head + " as it doesn't match any of the configured refspecs");
+ listener.getLogger()
+ .println(
+ "Ignoring " + head + " as it doesn't match any of the configured refspecs");
it.remove();
}
}
@@ -760,23 +788,34 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
// 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`
+ // 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;
+ 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());
+ 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());
+ listener.getLogger()
+ .println(
+ "[poll] Latest remote head revision on " + head + " is: " + sha1.getName());
return BUILD_NOW;
}
}
@@ -786,9 +825,11 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
}
final Node node = GitUtils.workspaceToNode(workspace);
- final EnvVars environment = project instanceof AbstractProject ? GitUtils.getPollEnvironment((AbstractProject) project, workspace, launcher, listener) : project.getEnvironment(node, listener);
+ final EnvVars environment = project instanceof AbstractProject
+ ? GitUtils.getPollEnvironment((AbstractProject) project, workspace, launcher, listener)
+ : project.getEnvironment(node, listener);
- FilePath workingDirectory = workingDirectory(project,workspace,environment,listener);
+ FilePath workingDirectory = workingDirectory(project, workspace, environment, listener);
// (Re)build if the working directory doesn't exist
if (workingDirectory == null || !workingDirectory.exists()) {
@@ -810,8 +851,14 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
listener.getLogger().println("Polling for changes in");
- Collection candidates = getBuildChooser().getCandidateRevisions(
- true, singleBranch, git, listener, buildData, new BuildChooserContextImpl(project, null, environment));
+ Collection candidates = getBuildChooser()
+ .getCandidateRevisions(
+ true,
+ singleBranch,
+ git,
+ listener,
+ buildData,
+ new BuildChooserContextImpl(project, null, environment));
for (Revision c : candidates) {
if (!isRevExcluded(git, c, listener, buildData)) {
@@ -838,13 +885,15 @@ private PollingResult compareRemoteRevisionWithImpl(Job, ?> project, Launcher
* @throws InterruptedException when interrupted
*/
@NonNull
- public GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run,?> build, FilePath workspace) throws IOException, InterruptedException {
+ 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);
+ return createClient(listener, environment, build, GitUtils.workspaceToNode(workspace), ws, null);
}
/**
@@ -861,23 +910,38 @@ public GitClient createClient(TaskListener listener, EnvVars environment, @NonNu
* @throws InterruptedException when interrupted
*/
@NonNull
- public GitClient createClient(TaskListener listener, EnvVars environment, @NonNull Run,?> build, FilePath workspace, UnsupportedCommand postBuildUnsupportedCommand) throws IOException, InterruptedException {
+ 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);
-
+ 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 {
+ 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 {
+ 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 */
@@ -899,13 +963,20 @@ private GitClient createClient(TaskListener listener, EnvVars environment, @NonN
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());
+ 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;
}
@@ -915,7 +986,7 @@ private GitClient createClient(TaskListener listener, EnvVars environment, @NonN
GitClient c = git.getClient();
for (GitSCMExtension ext : extensions) {
- c = ext.decorate(this,c);
+ c = ext.decorate(this, c);
}
for (UserRemoteConfig uc : getUserRemoteConfigs()) {
@@ -927,13 +998,15 @@ private GitClient createClient(TaskListener listener, EnvVars environment, @NonN
StandardUsernameCredentials credentials = lookupScanCredentials(build, url, ucCredentialsId);
if (credentials != null) {
c.addCredentials(url, credentials);
- if(!isHideCredentials()) {
+ 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
+ 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);
+ if (!isHideCredentials()) {
+ listener.getLogger()
+ .printf("Warning: CredentialId \"%s\" could not be found.%n", ucCredentialsId);
}
}
}
@@ -943,9 +1016,8 @@ private GitClient createClient(TaskListener listener, EnvVars environment, @NonN
return c;
}
- private static StandardUsernameCredentials lookupScanCredentials(@NonNull Run, ?> build,
- @CheckForNull String url,
- @CheckForNull String ucCredentialsId) {
+ private static StandardUsernameCredentials lookupScanCredentials(
+ @NonNull Run, ?> build, @CheckForNull String url, @CheckForNull String ucCredentialsId) {
if (Util.fixEmpty(ucCredentialsId) == null) {
return null;
} else {
@@ -979,10 +1051,9 @@ private BuildData fixNull(BuildData bd) {
* @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 {
+ private void fetchFrom(
+ GitClient git, @CheckForNull Run, ?> run, TaskListener listener, RemoteConfig remoteRepository)
+ throws InterruptedException, IOException {
boolean first = true;
for (URIish url : remoteRepository.getURIs()) {
@@ -1000,7 +1071,7 @@ private void fetchFrom(GitClient git,
}
fetch.execute();
} catch (GitException ex) {
- throw new GitException("Failed to fetch from "+url.toString(), ex);
+ throw new GitException("Failed to fetch from " + url.toString(), ex);
}
}
}
@@ -1013,9 +1084,11 @@ private RemoteConfig newRemoteConfig(String name, String refUrl, RefSpec... refS
repoConfig.setString("remote", name, "url", refUrl);
List str = new ArrayList<>();
- if(refSpec != null && refSpec.length > 0)
- for (RefSpec rs: refSpec)
+ if (refSpec != null && refSpec.length > 0) {
+ for (RefSpec rs : refSpec) {
str.add(rs.toString());
+ }
+ }
repoConfig.setStringList("remote", name, "fetch", str);
return RemoteConfig.getAllRemoteConfigs(repoConfig).get(0);
@@ -1042,7 +1115,7 @@ public String getGitExe(Node builtOn, TaskListener listener) {
*/
public String getGitExe(Node builtOn, EnvVars env, TaskListener listener) {
GitTool tool = GitUtils.resolveGitTool(gitTool, builtOn, env, listener);
- if(tool == null) {
+ if (tool == null) {
return null;
}
return tool.getGitExe();
@@ -1054,10 +1127,12 @@ public GitTool getGitTool(Node builtOn, EnvVars env, TaskListener listener) {
}
/*package*/ static class BuildChooserContextImpl implements BuildChooserContext, Serializable {
- @SuppressFBWarnings(value="SE_BAD_FIELD", justification="known non-serializable field")
+ @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "known non-serializable field")
final Job project;
- @SuppressFBWarnings(value="SE_BAD_FIELD", justification="known non-serializable field")
+
+ @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "known non-serializable field")
final Run build;
+
final EnvVars environment;
BuildChooserContextImpl(Job project, Run build, EnvVars environment) {
@@ -1066,18 +1141,24 @@ public GitTool getGitTool(Node builtOn, EnvVars env, TaskListener listener) {
this.environment = environment;
}
- public T actOnBuild(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException {
+ @Override
+ public T actOnBuild(@NonNull ContextCallable, T> callable)
+ throws IOException, InterruptedException {
return callable.invoke(build, FilePath.localChannel);
}
- public T actOnProject(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException {
+ @Override
+ public T actOnProject(@NonNull ContextCallable, T> callable)
+ throws IOException, InterruptedException {
return callable.invoke(project, FilePath.localChannel);
}
+ @Override
public Run, ?> getBuild() {
return build;
}
+ @Override
public EnvVars getEnvironment() {
return environment;
}
@@ -1087,19 +1168,25 @@ private Object writeReplace() {
if (currentChannel == null) {
return null;
}
- return currentChannel.export(BuildChooserContext.class,new BuildChooserContext() {
- public T actOnBuild(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException {
- return callable.invoke(build,Channel.current());
+ return currentChannel.export(BuildChooserContext.class, new BuildChooserContext() {
+ @Override
+ public T actOnBuild(@NonNull ContextCallable, T> callable)
+ throws IOException, InterruptedException {
+ return callable.invoke(build, Channel.current());
}
- public T actOnProject(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException {
- return callable.invoke(project,Channel.current());
+ @Override
+ public T actOnProject(@NonNull ContextCallable, T> callable)
+ throws IOException, InterruptedException {
+ return callable.invoke(project, Channel.current());
}
+ @Override
public Run, ?> getBuild() {
return build;
}
+ @Override
public EnvVars getEnvironment() {
return environment;
}
@@ -1117,11 +1204,13 @@ public EnvVars getEnvironment() {
* messed up (such as HEAD pointing to a random branch.) It is expected that this method brings it back
* to the predictable clean state by the time this method returns.
*/
- private @NonNull Build determineRevisionToBuild(final Run build,
- final @NonNull BuildData buildData,
- final EnvVars environment,
- final @NonNull GitClient git,
- final @NonNull TaskListener listener) throws IOException, InterruptedException {
+ private @NonNull Build determineRevisionToBuild(
+ final Run build,
+ final @NonNull BuildData buildData,
+ final EnvVars environment,
+ final @NonNull GitClient git,
+ final @NonNull TaskListener listener)
+ throws IOException, InterruptedException {
PrintStream log = listener.getLogger();
Collection candidates = Collections.emptyList();
final BuildChooserContext context = new BuildChooserContextImpl(build.getParent(), build, environment);
@@ -1132,7 +1221,7 @@ public EnvVars getEnvironment() {
}
// parameter forcing the commit ID to build
- if (candidates.isEmpty() ) {
+ if (candidates.isEmpty()) {
final RevisionParameterAction rpa = build.getAction(RevisionParameterAction.class);
if (rpa != null) {
// in case the checkout is due to a commit notification on a
@@ -1141,35 +1230,38 @@ public EnvVars getEnvironment() {
if (rpa.canOriginateFrom(this.getRepositories())) {
candidates = Collections.singleton(rpa.toRevision(git));
} else {
- log.println("skipping resolution of commit " + rpa.commit + ", since it originates from another repository");
+ log.println("skipping resolution of commit " + rpa.commit
+ + ", since it originates from another repository");
}
}
}
- if (candidates.isEmpty() ) {
- final String singleBranch = environment.expand( getSingleBranch(environment) );
+ if (candidates.isEmpty()) {
+ final String singleBranch = environment.expand(getSingleBranch(environment));
- candidates = getBuildChooser().getCandidateRevisions(
- false, singleBranch, git, listener, buildData, context);
+ candidates =
+ getBuildChooser().getCandidateRevisions(false, singleBranch, git, listener, buildData, context);
}
if (candidates.isEmpty()) {
// getBuildCandidates should make the last item the last build, so a re-build
// will build the last built thing.
- throw new AbortException("Couldn't find any revision to build. Verify the repository and branch configuration for this job.");
+ throw new AbortException(
+ "Couldn't find any revision to build. Verify the repository and branch configuration for this job.");
}
Revision marked = candidates.iterator().next();
Revision rev = marked;
// Modify the revision based on extensions
for (GitSCMExtension ext : extensions) {
- rev = ext.decorateRevisionToBuild(this,build,git,listener,marked,rev);
+ rev = ext.decorateRevisionToBuild(this, build, git, listener, marked, rev);
}
Build revToBuild = new Build(marked, rev, build.getNumber(), null);
buildData.saveBuild(revToBuild);
if (buildData.getBuildsByBranchName().size() >= 100) {
- log.println("JENKINS-19022: warning: possible memory leak due to Git plugin usage; see: https://plugins.jenkins.io/git/#remove-git-plugin-buildsbybranch-builddata-script");
+ log.println(
+ "JENKINS-19022: warning: possible memory leak due to Git plugin usage; see: https://plugins.jenkins.io/git/#remove-git-plugin-buildsbybranch-builddata-script");
}
boolean checkForMultipleRevisions = true;
BuildSingleRevisionOnly ext = extensions.get(BuildSingleRevisionOnly.class);
@@ -1185,9 +1277,12 @@ public EnvVars getEnvironment() {
AbstractProject project = (AbstractProject) job;
if (!project.isDisabled()) {
log.println("Scheduling another build to catch up with " + project.getFullDisplayName());
- if (!project.scheduleBuild(0, new SCMTrigger.SCMTriggerCause("This build was triggered by build "
- + build.getNumber() + " because more than one build candidate was found."))) {
- log.println("WARNING: multiple candidate revisions, but unable to schedule build of " + project.getFullDisplayName());
+ if (!project.scheduleBuild(
+ 0,
+ new SCMTrigger.SCMTriggerCause("This build was triggered by build " + build.getNumber()
+ + " because more than one build candidate was found."))) {
+ log.println("WARNING: multiple candidate revisions, but unable to schedule build of "
+ + project.getFullDisplayName());
}
}
}
@@ -1201,25 +1296,30 @@ public EnvVars getEnvironment() {
*
* By the end of this method, remote refs are updated to include all the commits found in the remote servers.
*/
- private void retrieveChanges(Run build, GitClient git, TaskListener listener) throws IOException, InterruptedException {
+ private void retrieveChanges(Run build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException {
final PrintStream log = listener.getLogger();
boolean removeSecondFetch = false;
List repos = getParamExpandedRepos(build, listener);
- if (repos.isEmpty()) return; // defensive check even though this is an invalid configuration
+ if (repos.isEmpty()) {
+ return; // defensive check even though this is an invalid configuration
+ }
if (git.hasGitRepo(false)) {
// It's an update
- if (repos.size() == 1)
+ if (repos.size() == 1) {
log.println("Fetching changes from the remote Git repository");
- else
+ } else {
log.println(MessageFormat.format("Fetching changes from {0} remote Git repositories", repos.size()));
+ }
} else {
log.println("Cloning the remote Git repository");
RemoteConfig rc = repos.get(0);
try {
- CloneCommand cmd = git.clone_().url(rc.getURIs().get(0).toPrivateString()).repositoryName(rc.getName());
+ CloneCommand cmd =
+ git.clone_().url(rc.getURIs().get(0).toPrivateString()).repositoryName(rc.getName());
for (GitSCMExtension ext : extensions) {
ext.decorateCloneCommand(this, build, git, listener, cmd);
}
@@ -1237,7 +1337,7 @@ private void retrieveChanges(Run build, GitClient git, TaskListener listener) th
GitHooksConfiguration.configure(git);
for (RemoteConfig remoteRepository : repos) {
- if (remoteRepository.equals(repos.get(0)) && removeSecondFetch){
+ if (remoteRepository.equals(repos.get(0)) && removeSecondFetch) {
log.println("Avoid second fetch");
continue;
}
@@ -1277,17 +1377,25 @@ private boolean determineSecondFetch(CloneOption option, @NonNull RemoteConfig r
}
@Override
- public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState baseline)
+ public void checkout(
+ Run, ?> build,
+ Launcher launcher,
+ FilePath workspace,
+ TaskListener listener,
+ File changelogFile,
+ SCMRevisionState baseline)
throws IOException, InterruptedException {
if (!ALLOW_LOCAL_CHECKOUT && !workspace.isRemote()) {
abortIfSourceIsLocal();
}
- if (VERBOSE)
- listener.getLogger().println("Using checkout strategy: " + getBuildChooser().getDisplayName());
+ if (VERBOSE) {
+ listener.getLogger()
+ .println("Using checkout strategy: " + getBuildChooser().getDisplayName());
+ }
- BuildData previousBuildData = getBuildData(build.getPreviousBuild()); // read only
+ BuildData previousBuildData = getBuildData(build.getPreviousBuild()); // read only
BuildData buildData = copyBuildData(build.getPreviousBuild());
if (VERBOSE && buildData.lastBuild != null) {
@@ -1298,8 +1406,12 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
GitClient git = createClient(listener, environment, build, workspace);
if (launcher instanceof Launcher.DecoratedLauncher) {
- // We cannot check for git instanceof CliGitAPIImpl vs. JGitAPIImpl here since (when running on an agent) we will actually have a RemoteGitImpl which is opaque.
- listener.getLogger().println("Warning: JENKINS-30600: special launcher " + launcher + " will be ignored (a typical symptom is the Git executable not being run inside a designated container)");
+ // We cannot check for git instanceof CliGitAPIImpl vs. JGitAPIImpl here since (when running on an agent) we
+ // will actually have a RemoteGitImpl which is opaque.
+ listener.getLogger()
+ .println(
+ "Warning: JENKINS-30600: special launcher " + launcher
+ + " will be ignored (a typical symptom is the Git executable not being run inside a designated container)");
}
for (GitSCMExtension ext : extensions) {
@@ -1313,14 +1425,14 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
// revision info for this build etc. The default assumption is that it's a duplicate.
boolean buildDataAlreadyPresent = false;
List actions = build.getActions(BuildData.class);
- for (BuildData d: actions) {
+ for (BuildData d : actions) {
if (d.similarTo(buildData)) {
buildDataAlreadyPresent = true;
break;
}
}
if (!actions.isEmpty()) {
- buildData.setIndex(actions.size()+1);
+ buildData.setIndex(actions.size() + 1);
}
// If the BuildData is not already attached to this build, add it to the build and mark that
@@ -1331,7 +1443,7 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
}
environment.put(GIT_COMMIT, revToBuild.revision.getSha1String());
- Branch localBranch = Iterables.getFirst(revToBuild.revision.getBranches(),null);
+ Branch localBranch = Iterables.getFirst(revToBuild.revision.getBranches(), null);
String localBranchName = getParamLocalBranch(build, listener);
if (localBranch != null && localBranch.getName() != null) { // null for a detached HEAD
String remoteBranchName = getBranchName(localBranch);
@@ -1341,22 +1453,25 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
if (lb != null) {
String lbn = lb.getLocalBranch();
if (lbn == null || lbn.equals("**")) {
- // local branch is configured with empty value or "**" so use remote branch name for checkout
- localBranchName = deriveLocalBranchName(remoteBranchName);
- }
- environment.put(GIT_LOCAL_BRANCH, localBranchName);
+ // local branch is configured with empty value or "**" so use remote branch name for checkout
+ localBranchName = deriveLocalBranchName(remoteBranchName);
+ }
+ environment.put(GIT_LOCAL_BRANCH, localBranchName);
}
}
listener.getLogger().println("Checking out " + revToBuild.revision);
- CheckoutCommand checkoutCommand = git.checkout().branch(localBranchName).ref(revToBuild.revision.getSha1String()).deleteBranchIfExist(true);
+ CheckoutCommand checkoutCommand = git.checkout()
+ .branch(localBranchName)
+ .ref(revToBuild.revision.getSha1String())
+ .deleteBranchIfExist(true);
for (GitSCMExtension ext : this.getExtensions()) {
ext.decorateCheckoutCommand(this, build, git, listener, checkoutCommand);
}
try {
- checkoutCommand.execute();
+ checkoutCommand.execute();
} catch (GitLockFailedException e) {
// Rethrow IOException so the retry will be able to catch it
throw new IOException("Could not checkout " + revToBuild.revision.getSha1String(), e);
@@ -1364,7 +1479,11 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
// Needs to be after the checkout so that revToBuild is in the workspace
try {
- printCommitMessageToLog(listener, git, revToBuild);
+ commitMessage = getCommitMessage(listener, git, revToBuild);
+ listener.getLogger().println("Commit message: \"" + commitMessage + "\"");
+ if (commitMessage != null && !commitMessage.isEmpty()) {
+ environment.put(GIT_COMMIT_TITLE, commitMessage);
+ }
} catch (IOException | ArithmeticException | GitException ge) {
// JENKINS-45729 reports a git exception when revToBuild cannot be found in the workspace.
// JENKINS-46628 reports a git exception when revToBuild cannot be found in the workspace.
@@ -1385,24 +1504,40 @@ public void checkout(Run, ?> build, Launcher launcher, FilePath workspace, Tas
}
if (changelogFile != null) {
- computeChangeLog(git, revToBuild.revision, listener, previousBuildData, new FilePath(changelogFile),
+ computeChangeLog(
+ git,
+ revToBuild.revision,
+ listener,
+ previousBuildData,
+ new FilePath(changelogFile),
new BuildChooserContextImpl(build.getParent(), build, environment));
}
}
for (GitSCMExtension ext : extensions) {
- ext.onCheckoutCompleted(this, build, git,listener);
+ ext.onCheckoutCompleted(this, build, git, listener);
+ }
+ }
+
+ private String getCommitMessage(TaskListener listener, GitClient git, final Build revToBuild) throws IOException {
+ try {
+ RevCommit commit = git.withRepository(new RevCommitRepositoryCallback(revToBuild));
+ return commit.getShortMessage();
+ } catch (InterruptedException | MissingObjectException e) {
+ throw new IOException("Could not get commit message", e);
}
}
/* Package protected for test access */
void abortIfSourceIsLocal() throws AbortException {
- for (UserRemoteConfig userRemoteConfig: getUserRemoteConfigs()) {
+ for (UserRemoteConfig userRemoteConfig : getUserRemoteConfigs()) {
String remoteUrl = userRemoteConfig.getUrl();
if (!isRemoteUrlValid(remoteUrl)) {
- throw new AbortException("Checkout of Git remote '" + remoteUrl + "' aborted because it references a local directory, " +
- "which may be insecure. You can allow local checkouts anyway by setting the system property '" +
- ALLOW_LOCAL_CHECKOUT_PROPERTY + "' to true.");
+ throw new AbortException(
+ "Checkout of Git remote '" + remoteUrl + "' aborted because it references a local directory, "
+ + "which may be insecure. You can allow local checkouts anyway by setting the system property '"
+ + ALLOW_LOCAL_CHECKOUT_PROPERTY
+ + "' to true.");
}
}
}
@@ -1475,7 +1610,14 @@ private void printCommitMessageToLog(TaskListener listener, GitClient git, final
* Information that captures what we did during the last build. We need this for changelog,
* or else we won't know where to stop.
*/
- private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener listener, BuildData previousBuildData, FilePath changelogFile, BuildChooserContext context) throws IOException, InterruptedException {
+ private void computeChangeLog(
+ GitClient git,
+ Revision revToBuild,
+ TaskListener listener,
+ BuildData previousBuildData,
+ FilePath changelogFile,
+ BuildChooserContext context)
+ throws IOException, InterruptedException {
boolean executed = false;
ChangelogCommand changelog = git.changelog();
changelog.includes(revToBuild.getSha1());
@@ -1488,7 +1630,8 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l
exclusion = true;
} else {
for (Branch b : revToBuild.getBranches()) {
- Build lastRevWas = getBuildChooser().prevBuildForChangelog(b.getName(), previousBuildData, git, context);
+ Build lastRevWas =
+ getBuildChooser().prevBuildForChangelog(b.getName(), previousBuildData, git, context);
if (lastRevWas != null && lastRevWas.revision != null && git.isCommitInRepo(lastRevWas.getSHA1())) {
changelog.excludes(lastRevWas.getSHA1());
exclusion = true;
@@ -1507,7 +1650,9 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l
} catch (GitException ge) {
ge.printStackTrace(listener.error("Unable to retrieve changeset"));
} finally {
- if (!executed) changelog.abort();
+ if (!executed) {
+ changelog.abort();
+ }
}
}
@@ -1520,30 +1665,30 @@ public void buildEnvVars(AbstractBuild, ?> build, Map env) {
@Override
public void buildEnvironment(Run, ?> build, java.util.Map env) {
Revision rev = fixNull(getBuildData(build)).getLastBuiltRevision();
- if (rev!=null) {
+ if (rev != null) {
Branch branch = Iterables.getFirst(rev.getBranches(), null);
- if (branch!=null && branch.getName()!=null) {
- String remoteBranchName = getBranchName(branch);
+ if (branch != null && branch.getName() != null) {
+ String remoteBranchName = getBranchName(branch);
env.put(GIT_BRANCH, remoteBranchName);
// TODO this is unmodular; should rather override LocalBranch.populateEnvironmentVariables
LocalBranch lb = getExtensions().get(LocalBranch.class);
if (lb != null) {
- // Set GIT_LOCAL_BRANCH variable from the LocalBranch extension
- String localBranchName = lb.getLocalBranch();
- if (localBranchName == null || localBranchName.equals("**")) {
- // local branch is configured with empty value or "**" so use remote branch name for checkout
- localBranchName = deriveLocalBranchName(remoteBranchName);
- }
- env.put(GIT_LOCAL_BRANCH, localBranchName);
+ // Set GIT_LOCAL_BRANCH variable from the LocalBranch extension
+ String localBranchName = lb.getLocalBranch();
+ if (localBranchName == null || localBranchName.equals("**")) {
+ // local branch is configured with empty value or "**" so use remote branch name for checkout
+ localBranchName = deriveLocalBranchName(remoteBranchName);
+ }
+ env.put(GIT_LOCAL_BRANCH, localBranchName);
}
RelativeTargetDirectory rtd = getExtensions().get(RelativeTargetDirectory.class);
if (rtd != null) {
- String localRelativeTargetDir = rtd.getRelativeTargetDir();
- if ( localRelativeTargetDir == null ){
- localRelativeTargetDir = "";
- }
- env.put(GIT_CHECKOUT_DIR, localRelativeTargetDir);
+ String localRelativeTargetDir = rtd.getRelativeTargetDir();
+ if (localRelativeTargetDir == null) {
+ localRelativeTargetDir = "";
+ }
+ env.put(GIT_CHECKOUT_DIR, localRelativeTargetDir);
}
String prevCommit = getLastBuiltCommitOfBranch(build, branch);
@@ -1561,26 +1706,31 @@ public void buildEnvironment(Run, ?> build, java.util.Map env)
if (sha1 != null && !sha1.isEmpty()) {
env.put(GIT_COMMIT, sha1);
}
+
+ if (commitMessage != null && !commitMessage.isEmpty()) {
+ env.put(GIT_COMMIT_TITLE, commitMessage);
+ }
}
/* Check all repository URLs are not empty */
/* JENKINS-38608 reports an unhelpful error message when a repository URL is empty */
/* Throws an IllegalArgumentException because that exception is thrown by env.put() on a null argument */
int repoCount = 1;
- for (UserRemoteConfig config:userRemoteConfigs) {
+ for (UserRemoteConfig config : userRemoteConfigs) {
if (config.getUrl() == null) {
- throw new IllegalArgumentException("Git repository URL " + repoCount + " is an empty string in job definition. Checkout requires a valid repository URL");
+ throw new IllegalArgumentException("Git repository URL " + repoCount
+ + " is an empty string in job definition. Checkout requires a valid repository URL");
}
repoCount++;
}
- if (userRemoteConfigs.size()>0) {
+ if (userRemoteConfigs.size() > 0) {
env.put(GIT_URL, userRemoteConfigs.get(0).getUrl());
}
- if (userRemoteConfigs.size()>1) {
- int count=1;
- for (UserRemoteConfig config:userRemoteConfigs) {
- env.put(GIT_URL+"_"+count, config.getUrl());
+ if (userRemoteConfigs.size() > 1) {
+ int count = 1;
+ for (UserRemoteConfig config : userRemoteConfigs) {
+ env.put(GIT_URL + "_" + count, config.getUrl());
count++;
}
}
@@ -1591,11 +1741,10 @@ public void buildEnvironment(Run, ?> build, java.util.Map env)
}
}
- private String getBranchName(Branch branch)
- {
+ private String getBranchName(Branch branch) {
String name = branch.getName();
- if(name.startsWith("refs/remotes/")) {
- //Restore expected previous behaviour
+ if (name.startsWith("refs/remotes/")) {
+ // Restore expected previous behaviour
name = name.substring("refs/remotes/".length());
}
return name;
@@ -1604,7 +1753,8 @@ private String getBranchName(Branch branch)
private String getLastBuiltCommitOfBranch(Run, ?> build, Branch branch) {
String prevCommit = null;
if (build.getPreviousBuiltBuild() != null) {
- final Build lastBuildOfBranch = fixNull(getBuildData(build.getPreviousBuiltBuild())).getLastBuildOfBranch(branch.getName());
+ final Build lastBuildOfBranch =
+ fixNull(getBuildData(build.getPreviousBuiltBuild())).getLastBuildOfBranch(branch.getName());
if (lastBuildOfBranch != null) {
Revision previousRev = lastBuildOfBranch.getRevision();
if (previousRev != null) {
@@ -1618,7 +1768,8 @@ private String getLastBuiltCommitOfBranch(Run, ?> build, Branch branch) {
private String getLastSuccessfulBuiltCommitOfBranch(Run, ?> build, Branch branch) {
String prevCommit = null;
if (build.getPreviousSuccessfulBuild() != null) {
- final Build lastSuccessfulBuildOfBranch = fixNull(getBuildData(build.getPreviousSuccessfulBuild())).getLastBuildOfBranch(branch.getName());
+ final Build lastSuccessfulBuildOfBranch =
+ fixNull(getBuildData(build.getPreviousSuccessfulBuild())).getLastBuildOfBranch(branch.getName());
if (lastSuccessfulBuildOfBranch != null) {
Revision previousRev = lastSuccessfulBuildOfBranch.getRevision();
if (previousRev != null) {
@@ -1633,10 +1784,16 @@ private String getLastSuccessfulBuiltCommitOfBranch(Run, ?> build, Branch bran
@Override
public ChangeLogParser createChangeLogParser() {
try {
- GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(gitTool).getClient();
+ GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars())
+ .in(new File("."))
+ .using(gitTool)
+ .getClient();
return new GitChangeLogParser(gitClient, getExtensions().get(AuthorInChangelog.class) != null);
} catch (IOException | InterruptedException e) {
- LOGGER.log(Level.WARNING, "Git client using '" + gitTool + "' changelog parser failed, using deprecated changelog parser", e);
+ LOGGER.log(
+ Level.WARNING,
+ "Git client using '" + gitTool + "' changelog parser failed, using deprecated changelog parser",
+ e);
}
return new GitChangeLogParser(null, getExtensions().get(AuthorInChangelog.class) != null);
}
@@ -1650,7 +1807,7 @@ public static final class DescriptorImpl extends SCMDescriptor {
private String globalConfigEmail;
private boolean createAccountBasedOnEmail;
private boolean useExistingAccountWithSameEmail;
-// private GitClientType defaultClientType = GitClientType.GITCLI;
+ // private GitClientType defaultClientType = GitClientType.GITCLI;
private boolean showEntireCommitSummaryInChanges;
private boolean hideCredentials;
private boolean allowSecondFetch;
@@ -1687,7 +1844,9 @@ public boolean isShowEntireCommitSummaryInChanges() {
return showEntireCommitSummaryInChanges;
}
- public boolean isHideCredentials() { return hideCredentials; }
+ public boolean isHideCredentials() {
+ return hideCredentials;
+ }
public void setHideCredentials(boolean hideCredentials) {
this.hideCredentials = hideCredentials;
@@ -1697,11 +1856,13 @@ public void setShowEntireCommitSummaryInChanges(boolean showEntireCommitSummaryI
this.showEntireCommitSummaryInChanges = showEntireCommitSummaryInChanges;
}
+ @Override
public String getDisplayName() {
return "Git";
}
- @Override public boolean isApplicable(Job project) {
+ @Override
+ public boolean isApplicable(Job project) {
return true;
}
@@ -1710,7 +1871,11 @@ public List getExtensionDescriptors() {
}
public boolean showGitToolOptions() {
- return Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallations().length>1;
+ return Jenkins.get()
+ .getDescriptorByType(GitTool.DescriptorImpl.class)
+ .getInstallations()
+ .length
+ > 1;
}
/**
@@ -1718,7 +1883,9 @@ public boolean showGitToolOptions() {
* @return list of available git tools
*/
public List getGitTools() {
- GitTool[] gitToolInstallations = Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallations();
+ GitTool[] gitToolInstallations = Jenkins.get()
+ .getDescriptorByType(GitTool.DescriptorImpl.class)
+ .getInstallations();
return Arrays.asList(gitToolInstallations);
}
@@ -1789,19 +1956,29 @@ public void setUseExistingAccountWithSameEmail(boolean useExistingAccountWithSam
this.useExistingAccountWithSameEmail = useExistingAccountWithSameEmail;
}
- public boolean isAllowSecondFetch() { return allowSecondFetch; }
+ public boolean isAllowSecondFetch() {
+ return allowSecondFetch;
+ }
public void setAllowSecondFetch(boolean allowSecondFetch) {
this.allowSecondFetch = allowSecondFetch;
}
- public boolean isDisableGitToolChooser() { return disableGitToolChooser; }
+ public boolean isDisableGitToolChooser() {
+ return disableGitToolChooser;
+ }
- public void setDisableGitToolChooser(boolean disableGitToolChooser) { this.disableGitToolChooser = disableGitToolChooser; }
+ public void setDisableGitToolChooser(boolean disableGitToolChooser) {
+ this.disableGitToolChooser = disableGitToolChooser;
+ }
- public boolean isAddGitTagAction() { return addGitTagAction; }
+ public boolean isAddGitTagAction() {
+ return addGitTagAction;
+ }
- public void setAddGitTagAction(boolean addGitTagAction) { this.addGitTagAction = addGitTagAction; }
+ public void setAddGitTagAction(boolean addGitTagAction) {
+ this.addGitTagAction = addGitTagAction;
+ }
/**
* Old configuration of git executable - exposed so that we can
@@ -1812,9 +1989,8 @@ public String getOldGitExe() {
return gitExe;
}
- public static List createRepositoryConfigurations(String[] urls,
- String[] repoNames,
- String[] refs) throws IOException {
+ public static List createRepositoryConfigurations(
+ String[] urls, String[] repoNames, String[] refs) throws IOException {
List remoteRepositories;
Config repoConfig = new Config();
@@ -1837,7 +2013,8 @@ public static List createRepositoryConfigurations(String[] urls,
}
repoConfig.setString("remote", name, "url", url);
- repoConfig.setStringList("remote", name, "fetch", new ArrayList<>(Arrays.asList(refs[i].split("\\s+"))));
+ repoConfig.setStringList(
+ "remote", name, "fetch", new ArrayList<>(Arrays.asList(refs[i].split("\\s+"))));
}
try {
@@ -1848,9 +2025,8 @@ public static List createRepositoryConfigurations(String[] urls,
return remoteRepositories;
}
- public static PreBuildMergeOptions createMergeOptions(UserMergeOptions mergeOptionsBean,
- List remoteRepositories)
- throws FormException {
+ public static PreBuildMergeOptions createMergeOptions(
+ UserMergeOptions mergeOptionsBean, List remoteRepositories) throws FormException {
PreBuildMergeOptions mergeOptions = new PreBuildMergeOptions();
if (mergeOptionsBean != null) {
RemoteConfig mergeRemote = null;
@@ -1866,7 +2042,8 @@ public static PreBuildMergeOptions createMergeOptions(UserMergeOptions mergeOpti
}
}
if (mergeRemote == null) {
- throw new FormException("No remote repository configured with name '" + mergeRemoteName + "'", "git.mergeRemote");
+ throw new FormException(
+ "No remote repository configured with name '" + mergeRemoteName + "'", "git.mergeRemote");
}
mergeOptions.setMergeRemote(mergeRemote);
mergeOptions.setMergeTarget(mergeOptionsBean.getMergeTarget());
@@ -1877,8 +2054,7 @@ public static PreBuildMergeOptions createMergeOptions(UserMergeOptions mergeOpti
return mergeOptions;
}
- public FormValidation doGitRemoteNameCheck(StaplerRequest req)
- throws IOException, ServletException {
+ public FormValidation doGitRemoteNameCheck(StaplerRequest req) throws IOException, ServletException {
String mergeRemoteName = req.getParameter("value");
boolean isMerge = req.getParameter("isMerge") != null;
@@ -1889,10 +2065,13 @@ public FormValidation doGitRemoteNameCheck(StaplerRequest req)
String[] urls = req.getParameterValues("repo.url");
String[] names = req.getParameterValues("repo.name");
- if (urls != null && names != null)
- for (String name : GitUtils.fixupNames(names, urls))
- if (name.equals(mergeRemoteName))
+ if (urls != null && names != null) {
+ for (String name : GitUtils.fixupNames(names, urls)) {
+ if (name.equals(mergeRemoteName)) {
return FormValidation.ok();
+ }
+ }
+ }
return FormValidation.error("No remote repository configured with name '" + mergeRemoteName + "'");
}
@@ -1908,26 +2087,26 @@ public boolean configure(StaplerRequest req, JSONObject formData) throws FormExc
* Fill in the environment variables for launching git
* @param env base environment variables
*/
- public void populateEnvironmentVariables(Map env) {
+ public void populateEnvironmentVariables(Map env) {
String name = getGlobalConfigName();
- if (name!=null) {
+ if (name != null) {
env.put("GIT_COMMITTER_NAME", name);
env.put("GIT_AUTHOR_NAME", name);
}
String email = getGlobalConfigEmail();
- if (email!=null) {
+ if (email != null) {
env.put("GIT_COMMITTER_EMAIL", email);
env.put("GIT_AUTHOR_EMAIL", email);
}
}
-// public GitClientType getDefaultClientType() {
-// return defaultClientType;
-// }
-//
-// public void setDefaultClientType(String defaultClientType) {
-// this.defaultClientType = GitClientType.valueOf(defaultClientType);
-// }
+ // public GitClientType getDefaultClientType() {
+ // return defaultClientType;
+ // }
+ //
+ // public void setDefaultClientType(String defaultClientType) {
+ // this.defaultClientType = GitClientType.valueOf(defaultClientType);
+ // }
}
private static final long serialVersionUID = 1L;
@@ -1944,7 +2123,8 @@ public List getBranches() {
return branches;
}
- @Override public String getKey() {
+ @Override
+ public String getKey() {
ScmName scmName = getExtensions().get(ScmName.class);
if (scmName != null) {
return scmName.getName();
@@ -1970,8 +2150,8 @@ public PreBuildMergeOptions getMergeOptions() throws FormException {
}
private boolean isRelevantBuildData(BuildData bd) {
- for(UserRemoteConfig c : getUserRemoteConfigs()) {
- if(bd.hasBeenReferenced(c.getUrl())) {
+ for (UserRemoteConfig c : getUserRemoteConfigs()) {
+ if (bd.hasBeenReferenced(c.getUrl())) {
return true;
}
}
@@ -1999,12 +2179,12 @@ public BuildData copyBuildData(Run build) {
BuildData base = getBuildData(build);
ScmName sn = getExtensions().get(ScmName.class);
String scmName = sn == null ? null : sn.getName();
- if (base==null)
+ if (base == null) {
return new BuildData(scmName, getUserRemoteConfigs());
- else {
- BuildData buildData = base.clone();
- buildData.setScmName(scmName);
- return buildData;
+ } else {
+ BuildData buildData = base.clone();
+ buildData.setScmName(scmName);
+ return buildData;
}
}
@@ -2069,7 +2249,9 @@ public int size() {
* @throws IOException on input or output error
* @throws InterruptedException when interrupted
*/
- protected FilePath workingDirectory(Job,?> context, FilePath workspace, EnvVars environment, TaskListener listener) throws IOException, InterruptedException {
+ protected FilePath workingDirectory(
+ Job, ?> context, FilePath workspace, EnvVars environment, TaskListener listener)
+ throws IOException, InterruptedException {
// JENKINS-10880: workspace can be null
if (workspace == null) {
return null;
@@ -2077,7 +2259,9 @@ protected FilePath workingDirectory(Job,?> context, FilePath workspace, EnvVar
for (GitSCMExtension ext : extensions) {
FilePath r = ext.getWorkingDirectory(this, context, workspace, environment, listener);
- if (r!=null) return r;
+ if (r != null) {
+ return r;
+ }
}
return workspace;
}
@@ -2090,48 +2274,55 @@ protected FilePath workingDirectory(Job,?> context, FilePath workspace, EnvVar
* @param listener build log
* @return true if any exclusion files are matched, false otherwise.
*/
- private boolean isRevExcluded(GitClient git, Revision r, TaskListener listener, BuildData buildData) throws IOException, InterruptedException {
+ private boolean isRevExcluded(GitClient git, Revision r, TaskListener listener, BuildData buildData)
+ throws IOException, InterruptedException {
try {
List revShow;
if (buildData != null && buildData.lastBuild != null) {
if (getExtensions().get(PathRestriction.class) != null) {
- revShow = git.showRevision(buildData.lastBuild.revision.getSha1(), r.getSha1());
+ revShow = git.showRevision(buildData.lastBuild.revision.getSha1(), r.getSha1());
} else {
- revShow = git.showRevision(buildData.lastBuild.revision.getSha1(), r.getSha1(), false);
+ revShow = git.showRevision(buildData.lastBuild.revision.getSha1(), r.getSha1(), false);
}
} else {
- revShow = git.showRevision(r.getSha1());
+ revShow = git.showRevision(r.getSha1());
}
revShow.add("commit "); // sentinel value
- int start=0, idx=0;
+ int start = 0, idx = 0;
for (String line : revShow) {
- if (line.startsWith("commit ") && idx!=0) {
- boolean showEntireCommitSummary = GitChangeSet.isShowEntireCommitSummaryInChanges() || !(git instanceof CliGitAPIImpl);
- GitChangeSet change = new GitChangeSet(revShow.subList(start,idx), getExtensions().get(AuthorInChangelog.class)!=null, showEntireCommitSummary);
-
- Boolean excludeThisCommit=null;
+ if (line.startsWith("commit ") && idx != 0) {
+ boolean showEntireCommitSummary =
+ GitChangeSet.isShowEntireCommitSummaryInChanges() || !(git instanceof CliGitAPIImpl);
+ GitChangeSet change = new GitChangeSet(
+ revShow.subList(start, idx),
+ getExtensions().get(AuthorInChangelog.class) != null,
+ showEntireCommitSummary);
+
+ Boolean excludeThisCommit = null;
for (GitSCMExtension ext : extensions) {
excludeThisCommit = ext.isRevExcluded(this, git, change, listener, buildData);
- if (excludeThisCommit!=null)
+ if (excludeThisCommit != null) {
break;
+ }
+ }
+ if (excludeThisCommit == null || !excludeThisCommit) {
+ return false; // this sequence of commits have one commit that we want to build
}
- if (excludeThisCommit==null || !excludeThisCommit)
- return false; // this sequence of commits have one commit that we want to build
start = idx;
}
idx++;
}
- assert start==revShow.size()-1;
+ assert start == revShow.size() - 1;
// every commit got excluded
return true;
} catch (GitException e) {
e.printStackTrace(listener.error("Failed to determine if we want to exclude " + r.getSha1String()));
- return false; // for historical reason this is not considered a fatal error.
+ return false; // for historical reason this is not considered a fatal error.
}
}
@@ -2146,8 +2337,7 @@ private boolean isRevExcluded(GitClient git, Revision r, TaskListener listener,
* generation is no longer supported
*/
@DataBoundSetter
- public void setDoGenerateSubmoduleConfigurations(boolean ignoredValue) {
- }
+ public void setDoGenerateSubmoduleConfigurations(boolean ignoredValue) {}
/**
* Returns false, the constant value of doGenerateSubmoduleConfigurations.
@@ -2158,7 +2348,7 @@ public boolean getDoGenerateSubmoduleConfigurations() {
return doGenerateSubmoduleConfigurations;
}
- @Initializer(after=PLUGINS_STARTED)
+ @Initializer(after = PLUGINS_STARTED)
public static void onLoaded() {
Jenkins jenkins = Jenkins.get();
DescriptorImpl desc = jenkins.getDescriptorByType(DescriptorImpl.class);
@@ -2169,11 +2359,12 @@ public static void onLoaded() {
if (exe.equals(defaultGit)) {
return;
}
- System.err.println("[WARNING] you're using deprecated gitexe attribute to configure git plugin. Use Git installations");
+ System.err.println(
+ "[WARNING] you're using deprecated gitexe attribute to configure git plugin. Use Git installations");
}
}
- @Initializer(before=JOB_LOADED)
+ @Initializer(before = JOB_LOADED)
public static void configureXtream() {
Run.XSTREAM.registerConverter(new ObjectIdConverter());
Items.XSTREAM.registerConverter(new RemoteConfigConverter(Items.XSTREAM));
@@ -2186,11 +2377,11 @@ public static void configureXtream() {
* Set to true to enable more logging to build's {@link TaskListener}.
* Used by various classes in this package.
*/
- @SuppressFBWarnings(value="MS_SHOULD_BE_FINAL", justification="Not final so users can adjust log verbosity")
+ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Not final so users can adjust log verbosity")
public static boolean VERBOSE = Boolean.getBoolean(GitSCM.class.getName() + ".verbose");
/**
* To avoid pointlessly large changelog, we'll limit the number of changes up to this.
*/
- public static final int MAX_CHANGELOG = Integer.getInteger(GitSCM.class.getName()+".maxChangelog",1024);
+ public static final int MAX_CHANGELOG = Integer.getInteger(GitSCM.class.getName() + ".maxChangelog", 1024);
}
diff --git a/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java b/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java
index 89ba40779c..348e72cad1 100644
--- a/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java
+++ b/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java
@@ -11,11 +11,9 @@
import hudson.plugins.git.util.DefaultBuildChooser;
import hudson.scm.SCM;
import hudson.util.DescribableList;
-
import java.io.IOException;
import java.io.Serializable;
import java.util.Set;
-
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
/**
@@ -32,6 +30,7 @@ public abstract class GitSCMBackwardCompatibility extends SCM implements Seriali
// when writing back
@Deprecated
transient String source;
+
@Deprecated
transient String branch;
@@ -74,7 +73,6 @@ public abstract class GitSCMBackwardCompatibility extends SCM implements Seriali
@Deprecated
private transient Boolean skipTag;
-
/**
* @deprecated
* Moved to {@link SubmoduleOption}
@@ -201,13 +199,12 @@ public abstract class GitSCMBackwardCompatibility extends SCM implements Seriali
@Deprecated
private transient BuildChooser buildChooser;
-
@Whitelisted
abstract DescribableList getExtensions();
@Override
public DescriptorImpl getDescriptor() {
- return (DescriptorImpl)super.getDescriptor();
+ return (DescriptorImpl) super.getDescriptor();
}
void readBackExtensionsFromLegacy() {
@@ -216,7 +213,8 @@ void readBackExtensionsFromLegacy() {
addIfMissing(new UserExclusion(excludedUsers));
excludedUsers = null;
}
- if ((excludedRegions != null && !excludedRegions.isBlank()) || (includedRegions != null && !includedRegions.isBlank())) {
+ if ((excludedRegions != null && !excludedRegions.isBlank())
+ || (includedRegions != null && !includedRegions.isBlank())) {
addIfMissing(new PathRestriction(includedRegions, excludedRegions));
excludedRegions = includedRegions = null;
}
@@ -224,15 +222,17 @@ void readBackExtensionsFromLegacy() {
addIfMissing(new RelativeTargetDirectory(relativeTargetDir));
relativeTargetDir = null;
}
- if (skipTag!=null && !skipTag) {
+ if (skipTag != null && !skipTag) {
addIfMissing(new PerBuildTag());
skipTag = null;
}
if (disableSubmodules || recursiveSubmodules || trackingSubmodules) {
- addIfMissing(new SubmoduleOption(disableSubmodules, recursiveSubmodules, trackingSubmodules, null, null, false));
+ addIfMissing(new SubmoduleOption(
+ disableSubmodules, recursiveSubmodules, trackingSubmodules, null, null, false));
}
- if ((gitConfigName != null && !gitConfigName.isBlank()) || (gitConfigEmail != null && !gitConfigEmail.isBlank())) {
- addIfMissing(new UserIdentity(gitConfigName,gitConfigEmail));
+ if ((gitConfigName != null && !gitConfigName.isBlank())
+ || (gitConfigEmail != null && !gitConfigEmail.isBlank())) {
+ addIfMissing(new UserIdentity(gitConfigName, gitConfigEmail));
gitConfigName = gitConfigEmail = null;
}
if (pruneBranches) {
@@ -243,7 +243,7 @@ void readBackExtensionsFromLegacy() {
getExtensions().replace(new PreBuildMerge(new UserMergeOptions(mergeOptions)));
mergeOptions = null;
}
- if (userMergeOptions!=null) {
+ if (userMergeOptions != null) {
addIfMissing(new PreBuildMerge(userMergeOptions));
userMergeOptions = null;
}
@@ -262,75 +262,77 @@ void readBackExtensionsFromLegacy() {
if (scmName != null && !scmName.isBlank()) {
addIfMissing(new ScmName(scmName));
}
- if (localBranch!=null) {
+ if (localBranch != null) {
addIfMissing(new LocalBranch(localBranch));
}
- if (buildChooser!=null && buildChooser.getClass()!=DefaultBuildChooser.class) {
+ if (buildChooser != null && buildChooser.getClass() != DefaultBuildChooser.class) {
addIfMissing(new BuildChooserSetting(buildChooser));
}
if ((reference != null && !reference.isBlank()) || useShallowClone) {
- addIfMissing(new CloneOption(useShallowClone, reference,null));
+ addIfMissing(new CloneOption(useShallowClone, reference, null));
}
} catch (IOException e) {
throw new AssertionError(e); // since our extensions don't have any real Saveable
}
-
}
private void addIfMissing(GitSCMExtension ext) throws IOException {
- if (getExtensions().get(ext.getClass())==null)
+ if (getExtensions().get(ext.getClass()) == null) {
getExtensions().add(ext);
+ }
}
@Deprecated
public String getIncludedRegions() {
PathRestriction pr = getExtensions().get(PathRestriction.class);
- return pr!=null ? pr.getIncludedRegions() : null;
+ return pr != null ? pr.getIncludedRegions() : null;
}
@Deprecated
public String getExcludedRegions() {
PathRestriction pr = getExtensions().get(PathRestriction.class);
- return pr!=null ? pr.getExcludedRegions() : null;
+ return pr != null ? pr.getExcludedRegions() : null;
}
@Deprecated
- @SuppressFBWarnings(value="PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification="Not willing to change behavior of deprecated methods")
+ @SuppressFBWarnings(
+ value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS",
+ justification = "Not willing to change behavior of deprecated methods")
public String[] getExcludedRegionsNormalized() {
PathRestriction pr = getExtensions().get(PathRestriction.class);
- return pr!=null ? pr.getExcludedRegionsNormalized() : null;
+ return pr != null ? pr.getExcludedRegionsNormalized() : null;
}
@Deprecated
- @SuppressFBWarnings(value="PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification="Not willing to change behavior of deprecated methods")
+ @SuppressFBWarnings(
+ value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS",
+ justification = "Not willing to change behavior of deprecated methods")
public String[] getIncludedRegionsNormalized() {
PathRestriction pr = getExtensions().get(PathRestriction.class);
- return pr!=null ? pr.getIncludedRegionsNormalized() : null;
+ return pr != null ? pr.getIncludedRegionsNormalized() : null;
}
-
@Deprecated
public String getRelativeTargetDir() {
RelativeTargetDirectory rt = getExtensions().get(RelativeTargetDirectory.class);
- return rt!=null ? rt.getRelativeTargetDir() : null;
+ return rt != null ? rt.getRelativeTargetDir() : null;
}
-
@Deprecated
public String getExcludedUsers() {
UserExclusion ue = getExtensions().get(UserExclusion.class);
- return ue!=null ? ue.getExcludedUsers() : null;
+ return ue != null ? ue.getExcludedUsers() : null;
}
@Deprecated
public Set getExcludedUsersNormalized() {
UserExclusion ue = getExtensions().get(UserExclusion.class);
- return ue!=null ? ue.getExcludedUsersNormalized() : null;
+ return ue != null ? ue.getExcludedUsersNormalized() : null;
}
@Deprecated
public boolean getSkipTag() {
- return getExtensions().get(PerBuildTag.class)!=null;
+ return getExtensions().get(PerBuildTag.class) != null;
}
@Deprecated
@@ -354,38 +356,42 @@ public boolean getTrackingSubmodules() {
@Deprecated
public String getGitConfigName() {
UserIdentity ui = getExtensions().get(UserIdentity.class);
- return ui!=null ? ui.getName() : null;
+ return ui != null ? ui.getName() : null;
}
@Deprecated
public String getGitConfigEmail() {
UserIdentity ui = getExtensions().get(UserIdentity.class);
- return ui!=null ? ui.getEmail() : null;
+ return ui != null ? ui.getEmail() : null;
}
@Deprecated
public String getGitConfigNameToUse() {
String n = getGitConfigName();
- if (n==null) n = getDescriptor().getGlobalConfigName();
+ if (n == null) {
+ n = getDescriptor().getGlobalConfigName();
+ }
return n;
}
@Deprecated
public String getGitConfigEmailToUse() {
String n = getGitConfigEmail();
- if (n==null) n = getDescriptor().getGlobalConfigEmail();
+ if (n == null) {
+ n = getDescriptor().getGlobalConfigEmail();
+ }
return n;
}
@Deprecated
public boolean getPruneBranches() {
- return getExtensions().get(PruneStaleBranch.class)!=null;
+ return getExtensions().get(PruneStaleBranch.class) != null;
}
@Deprecated
public UserMergeOptions getUserMergeOptions() {
PreBuildMerge m = getExtensions().get(PreBuildMerge.class);
- return m!=null ? m.getOptions() : null;
+ return m != null ? m.getOptions() : null;
}
/**
@@ -395,7 +401,7 @@ public UserMergeOptions getUserMergeOptions() {
*/
@Deprecated
public boolean getClean() {
- return getExtensions().get(CleanCheckout.class)!=null;
+ return getExtensions().get(CleanCheckout.class) != null;
}
/**
@@ -405,7 +411,7 @@ public boolean getClean() {
*/
@Deprecated
public boolean getWipeOutWorkspace() {
- return getExtensions().get(WipeWorkspace.class)!=null;
+ return getExtensions().get(WipeWorkspace.class) != null;
}
/**
@@ -416,7 +422,7 @@ public boolean getWipeOutWorkspace() {
@Deprecated
public boolean getUseShallowClone() {
CloneOption m = getExtensions().get(CloneOption.class);
- return m!=null && m.isShallow();
+ return m != null && m.isShallow();
}
/**
@@ -427,7 +433,7 @@ public boolean getUseShallowClone() {
@Deprecated
public String getReference() {
CloneOption m = getExtensions().get(CloneOption.class);
- return m!=null ? m.getReference() : null;
+ return m != null ? m.getReference() : null;
}
/**
@@ -437,7 +443,7 @@ public String getReference() {
*/
@Deprecated
public boolean getRemotePoll() {
- return getExtensions().get(DisableRemotePoll.class)==null;
+ return getExtensions().get(DisableRemotePoll.class) == null;
}
/**
@@ -450,7 +456,7 @@ public boolean getRemotePoll() {
*/
@Deprecated
public boolean getAuthorOrCommitter() {
- return getExtensions().get(AuthorInChangelog.class)!=null;
+ return getExtensions().get(AuthorInChangelog.class) != null;
}
/**
@@ -460,7 +466,7 @@ public boolean getAuthorOrCommitter() {
*/
@Deprecated
public boolean isIgnoreNotifyCommit() {
- return getExtensions().get(IgnoreNotifyCommit.class)!=null;
+ return getExtensions().get(IgnoreNotifyCommit.class) != null;
}
/**
@@ -471,7 +477,7 @@ public boolean isIgnoreNotifyCommit() {
@Deprecated
public String getScmName() {
ScmName sn = getExtensions().get(ScmName.class);
- return sn!=null ? sn.getName() : null;
+ return sn != null ? sn.getName() : null;
}
/**
@@ -482,9 +488,8 @@ public String getScmName() {
@Deprecated
public String getLocalBranch() {
LocalBranch lb = getExtensions().get(LocalBranch.class);
- return lb!=null ? lb.getLocalBranch() : null;
+ return lb != null ? lb.getLocalBranch() : null;
}
-
private static final long serialVersionUID = 1L;
}
diff --git a/src/main/java/hudson/plugins/git/GitStatus.java b/src/main/java/hudson/plugins/git/GitStatus.java
index 3c5c40df4a..970f271695 100644
--- a/src/main/java/hudson/plugins/git/GitStatus.java
+++ b/src/main/java/hudson/plugins/git/GitStatus.java
@@ -1,5 +1,8 @@
package hudson.plugins.git;
+import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
@@ -19,15 +22,11 @@
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
-
-import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
-import static javax.servlet.http.HttpServletResponse.SC_OK;
import jenkins.model.Jenkins;
import jenkins.scm.api.SCMEvent;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.SystemProperties;
import org.apache.commons.lang.StringUtils;
-
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.kohsuke.stapler.*;
@@ -45,6 +44,7 @@ public String getDisplayName() {
return "Git";
}
+ @Override
public String getIconFileName() {
// TODO
return null;
@@ -61,9 +61,9 @@ static void setAllowNotifyCommitParameters(boolean allowed) {
allowNotifyCommitParameters = allowed;
}
- private String lastURL = ""; // Required query parameter
+ private String lastURL = ""; // Required query parameter
private String lastBranches = null; // Optional query parameter
- private String lastSHA1 = null; // Optional query parameter
+ private String lastSHA1 = null; // Optional query parameter
private List lastBuildParameters = null;
private static List lastStaticBuildParameters = null;
@@ -113,13 +113,18 @@ public String toString() {
return s.toString();
}
- public HttpResponse doNotifyCommit(HttpServletRequest request, @QueryParameter(required=true) String url,
- @QueryParameter() String branches, @QueryParameter() String sha1,
- @QueryParameter() String token) {
+ public HttpResponse doNotifyCommit(
+ HttpServletRequest request,
+ @QueryParameter(required = true) String url,
+ @QueryParameter() String branches,
+ @QueryParameter() String sha1,
+ @QueryParameter() String token) {
if (!"disabled".equalsIgnoreCase(NOTIFY_COMMIT_ACCESS_CONTROL)
&& !"disabled-for-polling".equalsIgnoreCase(NOTIFY_COMMIT_ACCESS_CONTROL)) {
if (token == null || token.isEmpty()) {
- return HttpResponses.errorWithoutStack(401, "An access token is required. Please refer to Git plugin documentation (https://plugins.jenkins.io/git/#plugin-content-push-notification-from-repository) for details.");
+ return HttpResponses.errorWithoutStack(
+ 401,
+ "An access token is required. Please refer to Git plugin documentation (https://plugins.jenkins.io/git/#plugin-content-push-notification-from-repository) for details.");
}
if (!ApiTokenPropertyConfiguration.get().isValidApiToken(token)) {
return HttpResponses.errorWithoutStack(403, "Invalid access token");
@@ -127,15 +132,19 @@ public HttpResponse doNotifyCommit(HttpServletRequest request, @QueryParameter(r
}
if ("disabled-for-polling".equalsIgnoreCase(NOTIFY_COMMIT_ACCESS_CONTROL) && sha1 != null && !sha1.isEmpty()) {
if (token == null || token.isEmpty()) {
- return HttpResponses.errorWithoutStack(401, "An access token is required when using the sha1 parameter. Please refer to Git plugin documentation (https://plugins.jenkins.io/git/#plugin-content-push-notification-from-repository) for details.");
- }
+ return HttpResponses.errorWithoutStack(
+ 401,
+ "An access token is required when using the sha1 parameter. Please refer to Git plugin documentation (https://plugins.jenkins.io/git/#plugin-content-push-notification-from-repository) for details.");
+ }
if (!ApiTokenPropertyConfiguration.get().isValidApiToken(token)) {
return HttpResponses.errorWithoutStack(403, "Invalid access token");
}
}
lastURL = url;
lastBranches = branches;
- if (sha1 != null && !sha1.isBlank() && !SHA1_PATTERN.matcher(sha1.trim()).matches()) {
+ if (sha1 != null
+ && !sha1.isBlank()
+ && !SHA1_PATTERN.matcher(sha1.trim()).matches()) {
return HttpResponses.error(SC_BAD_REQUEST, new IllegalArgumentException("Illegal SHA1"));
}
lastSHA1 = cleanupSha1(sha1);
@@ -153,9 +162,14 @@ public HttpResponse doNotifyCommit(HttpServletRequest request, @QueryParameter(r
if (allowNotifyCommitParameters || !safeParameters.isEmpty()) { // Allow SECURITY-275 bug
final Map parameterMap = request.getParameterMap();
for (Map.Entry entry : parameterMap.entrySet()) {
- if (!(entry.getKey().equals("url")) && !(entry.getKey().equals("branches")) && !(entry.getKey().equals("sha1")))
- if (entry.getValue()[0] != null && (allowNotifyCommitParameters || safeParameters.contains(entry.getKey())))
+ if (!(entry.getKey().equals("url"))
+ && !(entry.getKey().equals("branches"))
+ && !(entry.getKey().equals("sha1"))) {
+ if (entry.getValue()[0] != null
+ && (allowNotifyCommitParameters || safeParameters.contains(entry.getKey()))) {
buildParameters.add(new StringParameterValue(entry.getKey(), entry.getValue()[0]));
+ }
+ }
}
}
lastBuildParameters = buildParameters;
@@ -203,14 +217,20 @@ public HttpResponse doNotifyCommit(HttpServletRequest request, @QueryParameter(r
* @return true if left-hand side loosely matches right-hand side
*/
public static boolean looselyMatches(URIish lhs, URIish rhs) {
- return Objects.equals(lhs.getHost(),rhs.getHost())
- && Objects.equals(normalizePath(lhs.getPath()), normalizePath(rhs.getPath()));
+ return Objects.equals(lhs.getHost(), rhs.getHost())
+ && Objects.equals(normalizePath(lhs.getPath()), normalizePath(rhs.getPath()));
}
private static String normalizePath(String path) {
- if (path.startsWith("/")) path=path.substring(1);
- if (path.endsWith("/")) path=path.substring(0,path.length()-1);
- if (path.endsWith(".git")) path=path.substring(0,path.length()-4);
+ if (path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ if (path.endsWith("/")) {
+ path = path.substring(0, path.length() - 1);
+ }
+ if (path.endsWith(".git")) {
+ path = path.substring(0, path.length() - 4);
+ }
return path;
}
@@ -227,8 +247,7 @@ public static class ResponseContributor {
* @param rsp the response.
* @since 1.4.1
*/
- public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
- }
+ public void addHeaders(StaplerRequest req, StaplerResponse rsp) {}
/**
* Write the contributed body.
@@ -248,8 +267,7 @@ public void writeBody(StaplerRequest req, StaplerResponse rsp, PrintWriter w) {
* @param w the writer.
* @since 1.4.1
*/
- public void writeBody(PrintWriter w) {
- }
+ public void writeBody(PrintWriter w) {}
}
/**
@@ -257,7 +275,7 @@ public void writeBody(PrintWriter w) {
*
* @since 1.4.1
*/
- public static abstract class Listener implements ExtensionPoint {
+ public abstract static class Listener implements ExtensionPoint {
/**
* @deprecated implement {@link #onNotifyCommit(org.eclipse.jgit.transport.URIish, String, List, String...)}
@@ -297,7 +315,8 @@ public List onNotifyCommit(URIish uri, @Nullable String sha
* @deprecated use {@link #onNotifyCommit(String, URIish, String, List, String...)}
*/
@Deprecated
- public List onNotifyCommit(URIish uri, @Nullable String sha1, List buildParameters, String... branches) {
+ public List onNotifyCommit(
+ URIish uri, @Nullable String sha1, List buildParameters, String... branches) {
return onNotifyCommit(uri, sha1, branches);
}
@@ -316,15 +335,14 @@ public List onNotifyCommit(URIish uri, @Nullable String sha
* @return any response contributors for the response to the push request.
* @since 2.6.5
*/
- public List onNotifyCommit(@CheckForNull String origin,
- URIish uri,
- @Nullable String sha1,
- List buildParameters,
- String... branches) {
+ public List onNotifyCommit(
+ @CheckForNull String origin,
+ URIish uri,
+ @Nullable String sha1,
+ List buildParameters,
+ String... branches) {
return onNotifyCommit(uri, sha1, buildParameters, branches);
}
-
-
}
/**
@@ -340,11 +358,14 @@ public static class JenkinsAbstractProjectListener extends Listener {
* {@inheritDoc}
*/
@Override
- public List onNotifyCommit(String origin, URIish uri, String sha1, List buildParameters, String... branches) {
+ public List onNotifyCommit(
+ String origin, URIish uri, String sha1, List buildParameters, String... branches) {
sha1 = cleanupSha1(sha1);
if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "Received notification from {0} for uri = {1} ; sha1 = {2} ; branches = {3}",
- new Object[]{StringUtils.defaultIfBlank(origin, "?"), uri, sha1, Arrays.toString(branches)});
+ LOGGER.log(
+ Level.FINE,
+ "Received notification from {0} for uri = {1} ; sha1 = {2} ; branches = {3}",
+ new Object[] {StringUtils.defaultIfBlank(origin, "?"), uri, sha1, Arrays.toString(branches)});
}
GitStatus.clearLastStaticBuildParameters();
@@ -354,8 +375,7 @@ public List onNotifyCommit(String origin, URIish uri, Strin
// this is safe because when we actually schedule a build, it's a build that can
// happen at some random time anyway.
try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
- boolean scmFound = false,
- urlFound = false;
+ boolean scmFound = false, urlFound = false;
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
LOGGER.severe("Jenkins.getInstance() is null in GitStatus.onNotifyCommit");
@@ -366,7 +386,8 @@ public List onNotifyCommit(String origin, URIish uri, Strin
if (scmTriggerItem == null) {
continue;
}
- SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
+ SCMS:
+ for (SCM scm : scmTriggerItem.getSCMs()) {
if (!(scm instanceof GitSCM)) {
continue;
}
@@ -374,8 +395,7 @@ public List onNotifyCommit(String origin, URIish uri, Strin
scmFound = true;
for (RemoteConfig repository : git.getRepositories()) {
- boolean repositoryMatches = false,
- branchMatches = false;
+ boolean repositoryMatches = false, branchMatches = false;
URIish matchedURL = null;
for (URIish remoteURL : repository.getURIs()) {
if (looselyMatches(uri, remoteURL)) {
@@ -385,28 +405,34 @@ public List onNotifyCommit(String origin, URIish uri, Strin
}
}
- if (!repositoryMatches || git.getExtensions().get(IgnoreNotifyCommit.class)!=null) {
+ if (!repositoryMatches || git.getExtensions().get(IgnoreNotifyCommit.class) != null) {
continue;
}
SCMTrigger trigger = scmTriggerItem.getSCMTrigger();
if (trigger == null || trigger.isIgnorePostCommitHooks()) {
if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "no trigger, or post-commit hooks disabled, on {0}", project.getFullDisplayName());
+ LOGGER.log(
+ Level.FINE,
+ "no trigger, or post-commit hooks disabled, on {0}",
+ project.getFullDisplayName());
}
continue;
}
- boolean branchFound = false,
- parametrizedBranchSpec = false;
+ boolean branchFound = false, parametrizedBranchSpec = false;
if (branches.length == 0) {
branchFound = true;
} else {
- OUT: for (BranchSpec branchSpec : git.getBranches()) {
+ OUT:
+ for (BranchSpec branchSpec : git.getBranches()) {
if (branchSpec.getName().contains("$")) {
// If the branchspec is parametrized, always run the polling
if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "Branch Spec is parametrized for {0}", project.getFullDisplayName());
+ LOGGER.log(
+ Level.FINE,
+ "Branch Spec is parametrized for {0}",
+ project.getFullDisplayName());
}
branchFound = true;
parametrizedBranchSpec = true;
@@ -414,7 +440,12 @@ public List onNotifyCommit(String origin, URIish uri, Strin
for (String branch : branches) {
if (branchSpec.matchesRepositoryBranch(repository.getName(), branch)) {
if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "Branch Spec {0} matches modified branch {1} for {2}", new Object[]{branchSpec, branch, project.getFullDisplayName()});
+ LOGGER.log(
+ Level.FINE,
+ "Branch Spec {0} matches modified branch {1} for {2}",
+ new Object[] {
+ branchSpec, branch, project.getFullDisplayName()
+ });
}
branchFound = true;
break OUT;
@@ -423,21 +454,25 @@ public List onNotifyCommit(String origin, URIish uri, Strin
}
}
}
- if (!branchFound) continue;
+ if (!branchFound) {
+ continue;
+ }
urlFound = true;
if (!(project instanceof AbstractProject && ((AbstractProject) project).isDisabled())) {
- //JENKINS-30178 Add default parameters defined in the job
+ // JENKINS-30178 Add default parameters defined in the job
if (project instanceof Job) {
Set buildParametersNames = new HashSet<>();
if (allowNotifyCommitParameters || !safeParameters.isEmpty()) {
- for (ParameterValue parameterValue: allBuildParameters) {
- if (allowNotifyCommitParameters || safeParameters.contains(parameterValue.getName())) {
+ for (ParameterValue parameterValue : allBuildParameters) {
+ if (allowNotifyCommitParameters
+ || safeParameters.contains(parameterValue.getName())) {
buildParametersNames.add(parameterValue.getName());
}
}
}
- List jobParametersValues = getDefaultParametersValues((Job) project);
+ List jobParametersValues =
+ getDefaultParametersValues((Job) project);
for (ParameterValue defaultParameterValue : jobParametersValues) {
if (!buildParametersNames.contains(defaultParameterValue.getName())) {
allBuildParameters.add(defaultParameterValue);
@@ -449,10 +484,14 @@ public List onNotifyCommit(String origin, URIish uri, Strin
* NOTE: This is SCHEDULING THE BUILD, not triggering polling of the repo.
* If no SHA1 or the branch spec is parameterized, it will only poll.
*/
- LOGGER.log(Level.INFO, "Scheduling {0} to build commit {1}", new Object[]{project.getFullDisplayName(), sha1});
- scmTriggerItem.scheduleBuild2(scmTriggerItem.getQuietPeriod(),
+ LOGGER.log(Level.INFO, "Scheduling {0} to build commit {1}", new Object[] {
+ project.getFullDisplayName(), sha1
+ });
+ scmTriggerItem.scheduleBuild2(
+ scmTriggerItem.getQuietPeriod(),
new CauseAction(new CommitHookCause(sha1)),
- new RevisionParameterAction(sha1, matchedURL), new ParametersAction(allBuildParameters));
+ new RevisionParameterAction(sha1, matchedURL),
+ new ParametersAction(allBuildParameters));
result.add(new ScheduledResponseContributor(project));
} else {
/* Poll the repository for changes
@@ -460,23 +499,26 @@ public List onNotifyCommit(String origin, URIish uri, Strin
* If the polling detects changes, it will schedule the build
*/
if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "Triggering the polling of {0}", project.getFullDisplayName());
+ LOGGER.log(
+ Level.FINE,
+ "Triggering the polling of {0}",
+ project.getFullDisplayName());
}
trigger.run();
result.add(new PollingScheduledResponseContributor(project));
- break SCMS; // no need to trigger the same project twice, so do not consider other GitSCMs in it
+ break SCMS; // no need to trigger the same project twice, so do not consider other
+ // GitSCMs in it
}
}
break;
}
-
}
}
if (!scmFound) {
result.add(new MessageResponseContributor("No git jobs found"));
} else if (!urlFound) {
- result.add(new MessageResponseContributor(
- "No git jobs using repository: " + uri.toString() + " and branches: " + String.join(",", branches)));
+ result.add(new MessageResponseContributor("No git jobs using repository: " + uri.toString()
+ + " and branches: " + String.join(",", branches)));
}
lastStaticBuildParameters = allBuildParameters;
@@ -488,12 +530,12 @@ public List onNotifyCommit(String origin, URIish uri, Strin
* Get the default parameters values from a job
*
*/
- private ArrayList getDefaultParametersValues(Job,?> job) {
+ private ArrayList getDefaultParametersValues(Job, ?> job) {
ArrayList defValues;
ParametersDefinitionProperty paramDefProp = job.getProperty(ParametersDefinitionProperty.class);
if (paramDefProp != null) {
- List parameterDefinition = paramDefProp.getParameterDefinitions();
+ List parameterDefinition = paramDefProp.getParameterDefinitions();
defValues = new ArrayList<>(parameterDefinition.size());
} else {
@@ -503,7 +545,7 @@ private ArrayList getDefaultParametersValues(Job,?> job) {
/* Scan for all parameter with an associated default values */
for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
- ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
+ ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if (defaultValue != null) {
defValues.add(defaultValue);
@@ -632,7 +674,8 @@ public String getShortDescription() {
}
}
- public static final Pattern SHA1_PATTERN = Pattern.compile("[a-fA-F0-9]++"); // we should have {40} but some compact sha1
+ public static final Pattern SHA1_PATTERN =
+ Pattern.compile("[a-fA-F0-9]++"); // we should have {40} but some compact sha1
public static final Pattern CLEANER_SHA1_PATTERN = Pattern.compile("[^a-fA-F0-9]");
@@ -640,8 +683,8 @@ public String getShortDescription() {
* @param sha1 the String to cleanup
* @return the String with all non hexa characters removed
*/
- private static String cleanupSha1(String sha1){
- return sha1 == null?null:CLEANER_SHA1_PATTERN.matcher(sha1.trim()).replaceAll("");
+ private static String cleanupSha1(String sha1) {
+ return sha1 == null ? null : CLEANER_SHA1_PATTERN.matcher(sha1.trim()).replaceAll("");
}
private static final Logger LOGGER = Logger.getLogger(GitStatus.class.getName());
@@ -664,8 +707,10 @@ private static String cleanupSha1(String sha1){
* "hudson.model.ParametersAction.keepUndefinedParameters" if it
* is set to true.
*/
- public static final boolean ALLOW_NOTIFY_COMMIT_PARAMETERS = Boolean.valueOf(System.getProperty(GitStatus.class.getName() + ".allowNotifyCommitParameters", "false"))
+ public static final boolean ALLOW_NOTIFY_COMMIT_PARAMETERS = Boolean.valueOf(
+ System.getProperty(GitStatus.class.getName() + ".allowNotifyCommitParameters", "false"))
|| Boolean.valueOf(System.getProperty("hudson.model.ParametersAction.keepUndefinedParameters", "false"));
+
private static boolean allowNotifyCommitParameters = ALLOW_NOTIFY_COMMIT_PARAMETERS;
/* Package protected for test.
@@ -683,8 +728,10 @@ private static Set csvToSet(String csvLine) {
@NonNull
private static String getSafeParameters() {
- String globalSafeParameters = System.getProperty("hudson.model.ParametersAction.safeParameters", "").trim();
- String gitStatusSafeParameters = System.getProperty(GitStatus.class.getName() + ".safeParameters", "").trim();
+ String globalSafeParameters = System.getProperty("hudson.model.ParametersAction.safeParameters", "")
+ .trim();
+ String gitStatusSafeParameters = System.getProperty(GitStatus.class.getName() + ".safeParameters", "")
+ .trim();
if (globalSafeParameters.isEmpty()) {
return gitStatusSafeParameters;
}
@@ -711,5 +758,6 @@ private static String getSafeParameters() {
* "hudson.model.ParametersAction.safeParameters" if set.
*/
public static final String SAFE_PARAMETERS = getSafeParameters();
+
private static Set safeParameters = csvToSet(SAFE_PARAMETERS);
}
diff --git a/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java b/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java
index 72ac266b44..429ef02329 100644
--- a/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java
+++ b/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java
@@ -2,12 +2,11 @@
import hudson.Extension;
import hudson.security.csrf.CrumbExclusion;
-
+import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
/**
* Make POST to /git/notifyCommit work with CSRF protection on.
diff --git a/src/main/java/hudson/plugins/git/GitTagAction.java b/src/main/java/hudson/plugins/git/GitTagAction.java
index d55d8a77bf..7831841554 100644
--- a/src/main/java/hudson/plugins/git/GitTagAction.java
+++ b/src/main/java/hudson/plugins/git/GitTagAction.java
@@ -8,6 +8,10 @@
import hudson.security.Permission;
import hudson.util.CopyOnWriteMap;
import hudson.util.MultipartFormDataParser;
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+import javax.servlet.ServletException;
import jenkins.model.*;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
@@ -17,11 +21,6 @@
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
-import javax.servlet.ServletException;
-import java.io.File;
-import java.io.IOException;
-import java.util.*;
-
/**
* @author Nicolas de Loof
*/
@@ -50,6 +49,7 @@ protected GitTagAction(Run build, FilePath workspace, Revision revision) {
}
}
+ @Override
public Descriptor getDescriptor() {
Jenkins jenkins = Jenkins.get();
return jenkins.getDescriptorOrDie(getClass());
@@ -58,15 +58,18 @@ public Descriptor getDescriptor() {
@Override
public boolean isTagged() {
for (List t : tags.values()) {
- if (!t.isEmpty()) return true;
+ if (!t.isEmpty()) {
+ return true;
+ }
}
return false;
}
@Override
public String getIconFileName() {
- if (!isTagged() && !getACL().hasPermission(getPermission()))
+ if (!isTagged() && !getACL().hasPermission(getPermission())) {
return null;
+ }
return "save.gif";
}
@@ -76,16 +79,19 @@ public String getDisplayName() {
for (List v : tags.values()) {
if (!v.isEmpty()) {
nonNullTag += v.size();
- if (nonNullTag > 1)
+ if (nonNullTag > 1) {
break;
+ }
}
}
- if (nonNullTag == 0)
+ if (nonNullTag == 0) {
return "No Tags";
- if (nonNullTag == 1)
+ }
+ if (nonNullTag == 1) {
return "One tag";
- else
+ } else {
return "Multiple tags";
+ }
}
/**
@@ -101,8 +107,9 @@ public List getTagInfo() {
List data = new ArrayList<>();
for (Map.Entry> e : tags.entrySet()) {
String module = e.getKey();
- for (String tag : e.getValue())
+ for (String tag : e.getValue()) {
data.add(new TagInfo(module, tag));
+ }
}
return data;
}
@@ -133,12 +140,17 @@ public String getTooltip() {
String tag = null;
for (List v : tags.values()) {
for (String s : v) {
- if (tag != null) return "Tagged"; // Multiple tags
+ if (tag != null) {
+ return "Tagged"; // Multiple tags
+ }
tag = s;
}
}
- if (tag != null) return "Tag: " + tag;
- else return null;
+ if (tag != null) {
+ return "Tag: " + tag;
+ } else {
+ return null;
+ }
}
/**
@@ -159,8 +171,9 @@ public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp) throw
int i = -1;
for (String e : tags.keySet()) {
i++;
- if (tags.size() > 1 && parser.get("tag" + i) == null)
+ if (tags.size() > 1 && parser.get("tag" + i) == null) {
continue; // when tags.size()==1, UI won't show the checkbox.
+ }
newTags.put(e, parser.get("name" + i));
}
@@ -188,7 +201,7 @@ void scheduleTagCreation(Map newTags, String comment) throws IOE
public final class TagWorkerThread extends TaskThread {
private final Map tagSet;
- public TagWorkerThread(Map tagSet,String ignoredComment) {
+ public TagWorkerThread(Map tagSet, String ignoredComment) {
super(GitTagAction.this, ListenerAndText.forMemory(null));
this.tagSet = tagSet;
}
@@ -197,26 +210,22 @@ public TagWorkerThread(Map tagSet,String ignoredComment) {
protected void perform(final TaskListener listener) throws Exception {
final EnvVars environment = getRun().getEnvironment(listener);
final FilePath workspace = new FilePath(new File(ws));
- final GitClient git = Git.with(listener, environment)
- .in(workspace)
- .getClient();
-
+ final GitClient git = Git.with(listener, environment).in(workspace).getClient();
for (Map.Entry entry : tagSet.entrySet()) {
try {
- String buildNum = "jenkins-"
- + getRun().getParent().getName().replace(" ", "_")
- + "-" + entry.getValue();
+ String buildNum =
+ "jenkins-" + getRun().getParent().getName().replace(" ", "_") + "-" + entry.getValue();
git.tag(entry.getValue(), "Jenkins Build #" + buildNum);
lastTagName = entry.getValue();
- for (Map.Entry e : tagSet.entrySet())
+ for (Map.Entry e : tagSet.entrySet()) {
GitTagAction.this.tags.get(e.getKey()).add(e.getValue());
+ }
getRun().save();
workerThread = null;
- }
- catch (GitException ex) {
+ } catch (GitException ex) {
lastTagException = ex;
ex.printStackTrace(listener.error("Error tagging repo '%s' : %s", entry.getKey(), ex.getMessage()));
// Failed. Try the next one
@@ -226,7 +235,6 @@ protected void perform(final TaskListener listener) throws Exception {
}
}
-
@Override
public Permission getPermission() {
return GitSCM.TAG;
diff --git a/src/main/java/hudson/plugins/git/ObjectIdConverter.java b/src/main/java/hudson/plugins/git/ObjectIdConverter.java
index 3b61acdd5c..40513f8f4b 100644
--- a/src/main/java/hudson/plugins/git/ObjectIdConverter.java
+++ b/src/main/java/hudson/plugins/git/ObjectIdConverter.java
@@ -26,47 +26,47 @@ public ObjectIdConverter() {
base64 = new Base64Encoder();
}
+ @Override
public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
return ObjectId.class == type;
}
- public void marshal(Object source, HierarchicalStreamWriter writer,
- MarshallingContext context) {
+ @Override
+ public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
writer.setValue(((ObjectId) source).name());
}
/**
* Is the current reader node a legacy node?
- *
+ *
* @param reader stream reader
* @param context usage context of reader
* @return true if legacy, false otherwise
*/
- protected boolean isLegacyNode(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
+ protected boolean isLegacyNode(HierarchicalStreamReader reader, UnmarshallingContext context) {
return reader.hasMoreChildren()
&& "byte-array".equals(((ExtendedHierarchicalStreamReader) reader).peekNextChild());
}
/**
* Legacy unmarshalling of object id
- *
+ *
* @param reader stream reader
* @param context usage context of reader
* @return object id
*/
- protected Object legacyUnmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
+ protected Object legacyUnmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
reader.moveDown();
ObjectId sha1 = ObjectId.fromRaw(base64.decode(reader.getValue()));
reader.moveUp();
return sha1;
}
- public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
- if (isLegacyNode(reader, context))
+ @Override
+ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+ if (isLegacyNode(reader, context)) {
return legacyUnmarshal(reader, context);
+ }
return ObjectId.fromString(reader.getValue());
}
}
diff --git a/src/main/java/hudson/plugins/git/RemoteConfigConverter.java b/src/main/java/hudson/plugins/git/RemoteConfigConverter.java
index 4aaccf5af0..7ed3592c20 100644
--- a/src/main/java/hudson/plugins/git/RemoteConfigConverter.java
+++ b/src/main/java/hudson/plugins/git/RemoteConfigConverter.java
@@ -11,9 +11,6 @@
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
-import org.eclipse.jgit.lib.Config;
-import org.eclipse.jgit.transport.RemoteConfig;
-
import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
@@ -21,6 +18,8 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.transport.RemoteConfig;
/**
* Remote config converter that handles unmarshaling legacy externalization of
@@ -31,8 +30,7 @@ public class RemoteConfigConverter implements Converter {
/**
* Remote config proxy
*/
- private static class RemoteConfigProxy extends Config implements
- Externalizable {
+ private static class RemoteConfigProxy extends Config implements Externalizable {
private static final String KEY_URL = "url";
@@ -65,24 +63,31 @@ public RemoteConfigProxy() {
receivepack = "git-receive-pack";
}
+ @Override
public String getString(String section, String subsection, String name) {
- if (KEY_UPLOADPACK.equals(name))
+ if (KEY_UPLOADPACK.equals(name)) {
return uploadpack;
- if (KEY_RECEIVEPACK.equals(name))
+ }
+ if (KEY_RECEIVEPACK.equals(name)) {
return receivepack;
- if (KEY_TAGOPT.equals(name))
+ }
+ if (KEY_TAGOPT.equals(name)) {
return tagopt;
+ }
return super.getString(section, subsection, name);
}
- public String[] getStringList(String section, String subsection,
- String name) {
- if (KEY_URL.equals(name))
+ @Override
+ public String[] getStringList(String section, String subsection, String name) {
+ if (KEY_URL.equals(name)) {
return uris;
- if (KEY_FETCH.equals(name))
+ }
+ if (KEY_FETCH.equals(name)) {
return fetch;
- if (KEY_PUSH.equals(name))
+ }
+ if (KEY_PUSH.equals(name)) {
return push;
+ }
return super.getStringList(section, subsection, name);
}
@@ -90,37 +95,41 @@ private void fromMap(Map> map) {
for (Entry> entry : map.entrySet()) {
String key = entry.getKey();
Collection values = entry.getValue();
- if (null != key)
+ if (null != key) {
switch (key) {
- case KEY_URL:
- uris = values.toArray(new String[0]);
- break;
- case KEY_FETCH:
- fetch = values.toArray(new String[0]);
- break;
- case KEY_PUSH:
- push = values.toArray(new String[0]);
- break;
- case KEY_UPLOADPACK:
- for (String value : values)
- uploadpack = value;
- break;
- case KEY_RECEIVEPACK:
- for (String value : values)
- receivepack = value;
- break;
- case KEY_TAGOPT:
- for (String value : values)
- tagopt = value;
- break;
- default:
- break;
+ case KEY_URL:
+ uris = values.toArray(new String[0]);
+ break;
+ case KEY_FETCH:
+ fetch = values.toArray(new String[0]);
+ break;
+ case KEY_PUSH:
+ push = values.toArray(new String[0]);
+ break;
+ case KEY_UPLOADPACK:
+ for (String value : values) {
+ uploadpack = value;
+ }
+ break;
+ case KEY_RECEIVEPACK:
+ for (String value : values) {
+ receivepack = value;
+ }
+ break;
+ case KEY_TAGOPT:
+ for (String value : values) {
+ tagopt = value;
+ }
+ break;
+ default:
+ break;
+ }
}
}
}
- public void readExternal(ObjectInput in) throws IOException,
- ClassNotFoundException {
+ @Override
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
final int items = in.readInt();
Map> map = new HashMap<>();
@@ -133,6 +142,7 @@ public void readExternal(ObjectInput in) throws IOException,
fromMap(map);
}
+ @Override
public void writeExternal(ObjectOutput out) throws IOException {
throw new IOException("writeExternal not supported");
}
@@ -151,49 +161,48 @@ public RemoteConfig toRemote() throws URISyntaxException {
/**
* Create remote config converter.
- *
+ *
* @param xStream XStream used for remote configuration conversion
*/
public RemoteConfigConverter(XStream xStream) {
mapper = xStream.getMapper();
@SuppressWarnings("deprecation")
- SerializableConverter tempConvertor = new SerializableConverter(mapper,
- xStream.getReflectionProvider());
+ SerializableConverter tempConvertor = new SerializableConverter(mapper, xStream.getReflectionProvider());
converter = tempConvertor;
}
+ @Override
public boolean canConvert(@SuppressWarnings("rawtypes") Class type) {
return RemoteConfig.class == type;
}
- public void marshal(Object source, HierarchicalStreamWriter writer,
- MarshallingContext context) {
+ @Override
+ public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
converter.marshal(source, writer, context);
}
/**
* Is the current reader node a legacy node?
- *
+ *
* @param reader stream reader
* @param context usage context of reader
* @return true if legacy, false otherwise
*/
- protected boolean isLegacyNode(HierarchicalStreamReader reader,
- final UnmarshallingContext context) {
+ protected boolean isLegacyNode(HierarchicalStreamReader reader, final UnmarshallingContext context) {
return reader.getNodeName().startsWith("org.spearce");
}
/**
* Legacy unmarshalling of remote config
- *
+ *
* @param reader stream reader
* @param context usage context of reader
* @return remote config
*/
- protected Object legacyUnmarshal(final HierarchicalStreamReader reader,
- final UnmarshallingContext context) {
+ protected Object legacyUnmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final RemoteConfigProxy proxy = new RemoteConfigProxy();
CustomObjectInputStream.StreamCallback callback = new CustomObjectInputStream.StreamCallback() {
+ @Override
public Object readFromStream() {
reader.moveDown();
@SuppressWarnings("rawtypes")
@@ -203,28 +212,30 @@ public Object readFromStream() {
return streamItem;
}
+ @Override
@SuppressWarnings("rawtypes")
public Map readFieldsFromStream() {
throw new UnsupportedOperationException();
}
+ @Override
public void defaultReadObject() {
throw new UnsupportedOperationException();
}
- public void registerValidation(ObjectInputValidation validation,
- int priority) throws NotActiveException {
+ @Override
+ public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException {
throw new NotActiveException();
}
+ @Override
public void close() {
throw new UnsupportedOperationException();
}
};
try {
@SuppressWarnings("deprecation")
- CustomObjectInputStream objectInput = CustomObjectInputStream
- .getInstance(context, callback);
+ CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback);
proxy.readExternal(objectInput);
objectInput.popCallback();
return proxy.toRemote();
@@ -233,10 +244,11 @@ public void close() {
}
}
- public Object unmarshal(final HierarchicalStreamReader reader,
- final UnmarshallingContext context) {
- if (isLegacyNode(reader, context))
+ @Override
+ public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
+ if (isLegacyNode(reader, context)) {
return legacyUnmarshal(reader, context);
+ }
return converter.unmarshal(reader, context);
}
}
diff --git a/src/main/java/hudson/plugins/git/RevisionParameterAction.java b/src/main/java/hudson/plugins/git/RevisionParameterAction.java
index 7af792adec..25c7806a49 100644
--- a/src/main/java/hudson/plugins/git/RevisionParameterAction.java
+++ b/src/main/java/hudson/plugins/git/RevisionParameterAction.java
@@ -29,17 +29,14 @@
import hudson.model.Queue;
import hudson.model.Queue.QueueAction;
import hudson.model.queue.FoldableAction;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.transport.RemoteConfig;
-import org.eclipse.jgit.transport.URIish;
-import org.jenkinsci.plugins.gitclient.GitClient;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
-
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.transport.RemoteConfig;
+import org.eclipse.jgit.transport.URIish;
+import org.jenkinsci.plugins.gitclient.GitClient;
/**
* Used as a build parameter to specify the revision to be built.
@@ -47,11 +44,12 @@
* @author Kohsuke Kawaguchi
* @author Chris Johnson
*/
-public class RevisionParameterAction extends InvisibleAction implements Serializable,QueueAction,FoldableAction {
+public class RevisionParameterAction extends InvisibleAction implements Serializable, QueueAction, FoldableAction {
/**
* SHA1, ref name, etc. that can be "git rev-parse"d into a specific commit.
*/
public final String commit;
+
public final boolean combineCommits;
public final Revision revision;
private final URIish repoURL;
@@ -74,17 +72,17 @@ public RevisionParameterAction(String commit, boolean combineCommits, URIish rep
this.revision = null;
this.repoURL = repoURL;
}
-
+
public RevisionParameterAction(Revision revision) {
this(revision, false);
- }
+ }
public RevisionParameterAction(Revision revision, boolean combineCommits) {
- this.revision = revision;
- this.commit = revision.getSha1String();
- this.combineCommits = combineCommits;
+ this.revision = revision;
+ this.commit = revision.getSha1String();
+ this.combineCommits = combineCommits;
this.repoURL = null;
- }
+ }
@Deprecated
public Revision toRevision(IGitAPI git) throws InterruptedException {
@@ -92,16 +90,15 @@ public Revision toRevision(IGitAPI git) throws InterruptedException {
}
public Revision toRevision(GitClient git) throws InterruptedException {
- if (revision != null) {
- return revision;
- }
+ if (revision != null) {
+ return revision;
+ }
ObjectId sha1 = git.revParse(commit);
Revision revision = new Revision(sha1);
// Here we do not have any local branches, containing the commit. So...
// we are to get all the remote branches, and show them to users, as
// they are local
- final List branches = normalizeBranches(git.getBranchesContaining(
- ObjectId.toString(sha1), true));
+ final List branches = normalizeBranches(git.getBranchesContaining(ObjectId.toString(sha1), true));
revision.getBranches().addAll(branches);
return revision;
}
@@ -155,32 +152,35 @@ private List normalizeBranches(List branches) {
@Override
public String toString() {
- return super.toString()+"[commit="+commit+"]";
+ return super.toString() + "[commit=" + commit + "]";
}
/**
- * Returns whether the new item should be scheduled.
+ * Returns whether the new item should be scheduled.
* An action should return true if the associated task is 'different enough' to warrant a separate execution.
* from {@link QueueAction}
- */
+ */
+ @Override
public boolean shouldSchedule(List actions) {
- /* Called in two cases
- 1. On the action attached to an existing queued item
+ /* Called in two cases
+ 1. On the action attached to an existing queued item
2. On the action attached to the new item to add.
- Behaviour
+ Behaviour
If actions contain a RevisionParameterAction with a matching commit to this one, we do not need to schedule
in all other cases we do.
*/
- List otherActions = Util.filter(actions,RevisionParameterAction.class);
- if(combineCommits) {
+ List otherActions = Util.filter(actions, RevisionParameterAction.class);
+ if (combineCommits) {
// we are combining commits so we never need to schedule another run.
// unless other job does not have a RevisionParameterAction (manual build)
- if(otherActions.size() != 0)
+ if (otherActions.size() != 0) {
return false;
+ }
} else {
- for (RevisionParameterAction action: otherActions) {
- if(this.commit.equals(action.commit))
+ for (RevisionParameterAction action : otherActions) {
+ if (this.commit.equals(action.commit)) {
return false;
+ }
}
}
// if we get to this point there were no matching actions so a new build is required
@@ -191,10 +191,11 @@ public boolean shouldSchedule(List actions) {
* Folds this Action into another action already associated with item
* from {@link FoldableAction}
*/
+ @Override
public void foldIntoExisting(Queue.Item item, Queue.Task owner, List otherActions) {
// only do this if we are asked to.
- if(combineCommits) {
- //because we cannot modify the commit in the existing action remove it and add self
+ if (combineCommits) {
+ // because we cannot modify the commit in the existing action remove it and add self
// or no CauseAction found, so add a copy of this one
item.replaceAction(this);
}
diff --git a/src/main/java/hudson/plugins/git/SubmoduleCombinator.java b/src/main/java/hudson/plugins/git/SubmoduleCombinator.java
index 58481a0a34..ca8760ca59 100644
--- a/src/main/java/hudson/plugins/git/SubmoduleCombinator.java
+++ b/src/main/java/hudson/plugins/git/SubmoduleCombinator.java
@@ -1,50 +1,48 @@
package hudson.plugins.git;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.model.TaskListener;
-import org.jenkinsci.plugins.gitclient.GitClient;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import org.jenkinsci.plugins.gitclient.GitClient;
/**
* Deprecated as inaccessible in git plugin 4.6.0. Class retained for
* binary compatibility.
- *
+ *
* @author nigelmagnay
* @deprecated
*/
@Deprecated
public class SubmoduleCombinator {
- @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification="Deprecated, retained for compatibility")
+ @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "Deprecated, retained for compatibility")
GitClient git;
- @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification="Deprecated, retained for compatibility")
+
+ @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "Deprecated, retained for compatibility")
TaskListener listener;
- @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification="Deprecated, retained for compatibility")
- long tid = new Date().getTime();
- @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification="Deprecated, retained for compatibility")
- long idx = 1;
-
- @SuppressFBWarnings(value="URF_UNREAD_FIELD", justification="Deprecated, retained for compatibility")
+ @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "Deprecated, retained for compatibility")
+ long tid = new Date().getTime();
+
+ @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "Deprecated, retained for compatibility")
+ long idx = 1;
+
+ @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "Deprecated, retained for compatibility")
Collection submoduleConfig;
-
+
public SubmoduleCombinator(GitClient git, TaskListener listener, Collection cfg) {
this.git = git;
this.listener = listener;
this.submoduleConfig = cfg;
}
- public void createSubmoduleCombinations() throws GitException, IOException, InterruptedException {
- }
+ public void createSubmoduleCombinations() throws GitException, IOException, InterruptedException {}
- protected void makeCombination(Map settings) throws InterruptedException {
- }
+ protected void makeCombination(Map settings) throws InterruptedException {}
public int difference(Map item, List entries) {
return 0;
diff --git a/src/main/java/hudson/plugins/git/SubmoduleConfig.java b/src/main/java/hudson/plugins/git/SubmoduleConfig.java
index ae830cda1a..93758a0dcb 100644
--- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java
+++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java
@@ -1,11 +1,9 @@
package hudson.plugins.git;
-import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
-import org.kohsuke.stapler.DataBoundConstructor;
-
-
import java.util.Collection;
import java.util.Collections;
+import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* Deprecated data class used in a submodule configuration experiment.
@@ -18,34 +16,30 @@
public class SubmoduleConfig implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private static final String[] EMPTY_ARRAY = new String[0];
- String submoduleName = null;
+ String submoduleName = null;
String[] branches = EMPTY_ARRAY;
public SubmoduleConfig() {
this(null, Collections.emptySet());
}
- public SubmoduleConfig(String submoduleName, String[] branches) {
- }
+ public SubmoduleConfig(String submoduleName, String[] branches) {}
@DataBoundConstructor
- public SubmoduleConfig(String submoduleName, Collection branches) {
- }
+ public SubmoduleConfig(String submoduleName, Collection branches) {}
@Whitelisted
public String getSubmoduleName() {
return submoduleName;
}
- public void setSubmoduleName(String submoduleName) {
- }
+ public void setSubmoduleName(String submoduleName) {}
public String[] getBranches() {
return EMPTY_ARRAY;
}
- public void setBranches(String[] branches) {
- }
+ public void setBranches(String[] branches) {}
public boolean revisionMatchesInterest(Revision r) {
return false;
diff --git a/src/main/java/hudson/plugins/git/UserMergeOptions.java b/src/main/java/hudson/plugins/git/UserMergeOptions.java
index e4ff9915a2..368147d7ca 100644
--- a/src/main/java/hudson/plugins/git/UserMergeOptions.java
+++ b/src/main/java/hudson/plugins/git/UserMergeOptions.java
@@ -5,16 +5,15 @@
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.plugins.git.opt.PreBuildMergeOptions;
-import org.jenkinsci.plugins.gitclient.MergeCommand;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.io.Serializable;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
+import org.jenkinsci.plugins.gitclient.MergeCommand;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jenkinsci.plugins.structs.describable.CustomDescribableModel;
+import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
/**
@@ -22,7 +21,7 @@
* merging (to the commit being built.)
*
*/
-public class UserMergeOptions extends AbstractDescribableImpl implements Serializable {
+public class UserMergeOptions extends AbstractDescribableImpl implements Serializable {
private String mergeRemote;
private final String mergeTarget;
@@ -46,7 +45,10 @@ public UserMergeOptions(String mergeRemote, String mergeTarget, String mergeStra
* @param mergeStrategy merge strategy
* @param fastForwardMode fast forward mode
*/
- public UserMergeOptions(String mergeRemote, String mergeTarget, String mergeStrategy,
+ public UserMergeOptions(
+ String mergeRemote,
+ String mergeTarget,
+ String mergeStrategy,
MergeCommand.GitPluginFastForwardMode fastForwardMode) {
this.mergeRemote = mergeRemote;
this.mergeTarget = mergeTarget;
@@ -64,7 +66,11 @@ public UserMergeOptions(String mergeTarget) {
* @param pbm pre-build merge options used to construct UserMergeOptions
*/
public UserMergeOptions(PreBuildMergeOptions pbm) {
- this(pbm.getRemoteBranchName(), pbm.getMergeTarget(), pbm.getMergeStrategy().toString(), pbm.getFastForwardMode());
+ this(
+ pbm.getRemoteBranchName(),
+ pbm.getMergeTarget(),
+ pbm.getMergeStrategy().toString(),
+ pbm.getFastForwardMode());
}
/**
@@ -101,21 +107,26 @@ public String getRef() {
}
public MergeCommand.Strategy getMergeStrategy() {
- for (MergeCommand.Strategy strategy: MergeCommand.Strategy.values())
- if (strategy.toString().equals(mergeStrategy))
+ for (MergeCommand.Strategy strategy : MergeCommand.Strategy.values()) {
+ if (strategy.toString().equals(mergeStrategy)) {
return strategy;
+ }
+ }
return MergeCommand.Strategy.DEFAULT;
}
@DataBoundSetter
public void setMergeStrategy(MergeCommand.Strategy mergeStrategy) {
- this.mergeStrategy = mergeStrategy.toString(); // not .name() as you might expect! TODO in Turkey this will be e.g. recursıve
+ this.mergeStrategy =
+ mergeStrategy.toString(); // not .name() as you might expect! TODO in Turkey this will be e.g. recursıve
}
public MergeCommand.GitPluginFastForwardMode getFastForwardMode() {
- for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values())
- if (ffMode.equals(fastForwardMode))
+ for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values()) {
+ if (ffMode.equals(fastForwardMode)) {
return ffMode;
+ }
+ }
return MergeCommand.GitPluginFastForwardMode.FF;
}
@@ -126,12 +137,11 @@ public void setFastForwardMode(MergeCommand.GitPluginFastForwardMode fastForward
@Override
public String toString() {
- return "UserMergeOptions{" +
- "mergeRemote='" + mergeRemote + '\'' +
- ", mergeTarget='" + mergeTarget + '\'' +
- ", mergeStrategy='" + getMergeStrategy().name() + '\'' +
- ", fastForwardMode='" + getFastForwardMode().name() + '\'' +
- '}';
+ return "UserMergeOptions{" + "mergeRemote='"
+ + mergeRemote + '\'' + ", mergeTarget='"
+ + mergeTarget + '\'' + ", mergeStrategy='"
+ + getMergeStrategy().name() + '\'' + ", fastForwardMode='"
+ + getFastForwardMode().name() + '\'' + '}';
}
@Override
@@ -173,7 +183,5 @@ public Map customInstantiate(Map arguments) {
}
return r;
}
-
}
-
}
diff --git a/src/main/java/hudson/plugins/git/UserRemoteConfig.java b/src/main/java/hudson/plugins/git/UserRemoteConfig.java
index a405d18db2..916cddd812 100644
--- a/src/main/java/hudson/plugins/git/UserRemoteConfig.java
+++ b/src/main/java/hudson/plugins/git/UserRemoteConfig.java
@@ -1,5 +1,8 @@
package hudson.plugins.git;
+import static hudson.Util.fixEmpty;
+import static hudson.Util.fixEmptyAndTrim;
+
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
@@ -12,6 +15,7 @@
import hudson.model.AbstractDescribableImpl;
import hudson.model.Computer;
import hudson.model.Descriptor;
+import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.Queue;
@@ -20,28 +24,23 @@
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.regex.Pattern;
import jenkins.model.Jenkins;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.RemoteConfig;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.GitURIRequirementsBuilder;
+import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.regex.Pattern;
-import java.util.Objects;
-import java.util.UUID;
-
-import static hudson.Util.fixEmpty;
-import static hudson.Util.fixEmptyAndTrim;
-import hudson.model.FreeStyleProject;
-import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.interceptor.RequirePOST;
@ExportedBean
@@ -91,16 +90,15 @@ public String toString() {
return getRefspec() + " => " + getUrl() + " (" + getName() + ")";
}
- private final static Pattern SCP_LIKE = Pattern.compile("(.*):(.*)");
+ private static final Pattern SCP_LIKE = Pattern.compile("(.*):(.*)");
@Extension
public static class DescriptorImpl extends Descriptor {
- public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project,
- @QueryParameter String url,
- @QueryParameter String credentialsId) {
- if (project == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) ||
- project != null && !project.hasPermission(Item.EXTENDED_READ)) {
+ public ListBoxModel doFillCredentialsIdItems(
+ @AncestorInPath Item project, @QueryParameter String url, @QueryParameter String credentialsId) {
+ if (project == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
+ || project != null && !project.hasPermission(Item.EXTENDED_READ)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
if (project == null) {
@@ -123,11 +121,10 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project,
.includeCurrentValue(credentialsId);
}
- public FormValidation doCheckCredentialsId(@AncestorInPath Item project,
- @QueryParameter String url,
- @QueryParameter String value) {
- if (project == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) ||
- project != null && !project.hasPermission(Item.EXTENDED_READ)) {
+ public FormValidation doCheckCredentialsId(
+ @AncestorInPath Item project, @QueryParameter String url, @QueryParameter String value) {
+ if (project == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
+ || project != null && !project.hasPermission(Item.EXTENDED_READ)) {
return FormValidation.ok();
}
@@ -148,12 +145,12 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item project,
{
return FormValidation.ok();
}
- for (ListBoxModel.Option o : CredentialsProvider
- .listCredentials(StandardUsernameCredentials.class, project, project instanceof Queue.Task
- ? Tasks.getAuthenticationOf((Queue.Task) project)
- : ACL.SYSTEM,
- GitURIRequirementsBuilder.fromUri(url).build(),
- GitClient.CREDENTIALS_MATCHER)) {
+ for (ListBoxModel.Option o : CredentialsProvider.listCredentials(
+ StandardUsernameCredentials.class,
+ project,
+ project instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) project) : ACL.SYSTEM,
+ GitURIRequirementsBuilder.fromUri(url).build(),
+ GitClient.CREDENTIALS_MATCHER)) {
if (Objects.equals(value, o.value)) {
// TODO check if this type of credential is acceptable to the Git client or does it merit warning
// NOTE: we would need to actually lookup the credential to do the check, which may require
@@ -167,24 +164,28 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item project,
}
@RequirePOST
- public FormValidation doCheckUrl(@AncestorInPath Item item,
- @QueryParameter String credentialsId,
- @QueryParameter String value) throws IOException, InterruptedException {
-
- // Normally this permission is hidden and implied by Item.CONFIGURE, so from a view-only form you will not be able to use this check.
- // (TODO under certain circumstances being granted only USE_OWN might suffice, though this presumes a fix of JENKINS-31870.)
- if (item == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) ||
- item != null && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
+ public FormValidation doCheckUrl(
+ @AncestorInPath Item item, @QueryParameter String credentialsId, @QueryParameter String value)
+ throws IOException, InterruptedException {
+
+ // Normally this permission is hidden and implied by Item.CONFIGURE, so from a view-only form you will not
+ // be able to use this check.
+ // (TODO under certain circumstances being granted only USE_OWN might suffice, though this presumes a fix of
+ // JENKINS-31870.)
+ if (item == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
+ || item != null && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return FormValidation.ok();
}
String url = Util.fixEmptyAndTrim(value);
- if (url == null)
+ if (url == null) {
return FormValidation.error(Messages.UserRemoteConfig_CheckUrl_UrlIsNull());
+ }
- if (url.indexOf('$') >= 0)
+ if (url.indexOf('$') >= 0) {
// set by variable, can't validate
return FormValidation.ok();
+ }
// get git executable on controller
EnvVars environment;
@@ -226,18 +227,18 @@ public FormValidation doCheckUrl(@AncestorInPath Item item,
* @return FormValidation.ok() or FormValidation.error()
* @throws IllegalArgumentException on unexpected argument error
*/
- public FormValidation doCheckRefspec(@QueryParameter String name,
- @QueryParameter String url,
- @QueryParameter String value) throws IllegalArgumentException {
+ public FormValidation doCheckRefspec(
+ @QueryParameter String name, @QueryParameter String url, @QueryParameter String value)
+ throws IllegalArgumentException {
String refSpec = Util.fixEmptyAndTrim(value);
- if(refSpec == null){
+ if (refSpec == null) {
// We fix empty field value with a default refspec, hence we send ok.
return FormValidation.ok();
}
- if(refSpec.contains("$")){
+ if (refSpec.contains("$")) {
// set by variable, can't validate
return FormValidation.ok();
}
@@ -247,7 +248,7 @@ public FormValidation doCheckRefspec(@QueryParameter String name,
repoConfig.setString("remote", name, "url", url);
repoConfig.setString("remote", name, "fetch", refSpec);
- //Attempt to fetch remote repositories using the repoConfig
+ // Attempt to fetch remote repositories using the repoConfig
try {
RemoteConfig.getAllRemoteConfigs(repoConfig);
} catch (Exception e) {
@@ -257,11 +258,17 @@ public FormValidation doCheckRefspec(@QueryParameter String name,
return FormValidation.ok();
}
- private static StandardCredentials lookupCredentials(@CheckForNull Item project, String credentialId, String uri) {
- return (credentialId == null) ? null : CredentialsMatchers.firstOrNull(
- CredentialsProvider.lookupCredentials(StandardCredentials.class, project, ACL.SYSTEM,
- GitURIRequirementsBuilder.fromUri(uri).build()),
- CredentialsMatchers.withId(credentialId));
+ private static StandardCredentials lookupCredentials(
+ @CheckForNull Item project, String credentialId, String uri) {
+ return (credentialId == null)
+ ? null
+ : CredentialsMatchers.firstOrNull(
+ CredentialsProvider.lookupCredentials(
+ StandardCredentials.class,
+ project,
+ ACL.SYSTEM,
+ GitURIRequirementsBuilder.fromUri(uri).build()),
+ CredentialsMatchers.withId(credentialId));
}
@Override
diff --git a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java
index d8c5678dff..d5a52ba3ba 100644
--- a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
@@ -11,20 +12,18 @@
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
import hudson.util.FormValidation.URLCheck;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
+import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* AssemblaWeb Git Browser URLs
@@ -89,6 +88,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("assembla")
public static class AssemblaWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "AssemblaWeb";
@@ -96,17 +96,17 @@ public String getDisplayName() {
@Override
public AssemblaWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(AssemblaWeb.class, jsonObject);
}
@RequirePOST
- public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
+ public FormValidation doCheckRepoUrl(
+ @AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
throws IOException, ServletException, URISyntaxException {
String cleanUrl = Util.fixEmptyAndTrim(repoUrl);
- if (initialChecksAndReturnOk(project, cleanUrl))
- {
+ if (initialChecksAndReturnOk(project, cleanUrl)) {
return FormValidation.ok();
}
// Connect to URL and check content only if we have permission
@@ -114,6 +114,7 @@ public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParamet
return FormValidation.error(Messages.invalidUrl());
}
return new URLCheck() {
+ @Override
protected FormValidation check() throws IOException, ServletException {
String v = cleanUrl;
if (!v.endsWith("/")) {
@@ -127,7 +128,8 @@ protected FormValidation check() throws IOException, ServletException {
return FormValidation.error("This is a valid URL but it does not look like Assembla");
}
} catch (IOException e) {
- return FormValidation.error("Exception reading from Assembla URL " + cleanUrl + " : " + handleIOException(v, e));
+ return FormValidation.error(
+ "Exception reading from Assembla URL " + cleanUrl + " : " + handleIOException(v, e));
}
}
}.check();
diff --git a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java
index 5717b46532..500c498d44 100644
--- a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java
+++ b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java
@@ -1,19 +1,18 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser URLs for on-premise Bitbucket Server installation.
*/
@@ -42,14 +41,15 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(GitChangeSet.Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
|| path.getChangeSet().getParentCommit() == null) {
return null;
}
return getDiffLinkRegardlessOfEditType(path);
}
-
private URL getDiffLinkRegardlessOfEditType(GitChangeSet.Path path) throws IOException {
final GitChangeSet changeSet = path.getChangeSet();
final String pathAsString = path.getPath();
@@ -70,8 +70,10 @@ public URL getFileLink(GitChangeSet.Path path) throws IOException {
return encodeURL(new URL(url, url.getPath() + "browse/" + pathAsString));
}
- @Extension @Symbol("bitbucketServer")
+ @Extension
+ @Symbol("bitbucketServer")
public static class BitbucketServerDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "bitbucketserver";
@@ -79,7 +81,7 @@ public String getDisplayName() {
@Override
public BitbucketServer newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(BitbucketServer.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java
index 8fcd25c478..738057404f 100644
--- a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java
@@ -1,19 +1,18 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser URLs
*/
@@ -42,14 +41,15 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(GitChangeSet.Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
|| path.getChangeSet().getParentCommit() == null) {
return null;
}
return getDiffLinkRegardlessOfEditType(path);
}
-
private URL getDiffLinkRegardlessOfEditType(GitChangeSet.Path path) throws IOException {
final GitChangeSet changeSet = path.getChangeSet();
final String pathAsString = path.getPath();
@@ -73,6 +73,7 @@ public URL getFileLink(GitChangeSet.Path path) throws IOException {
@Extension
@Symbol("bitbucket")
public static class BitbucketWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "bitbucketweb";
@@ -80,9 +81,8 @@ public String getDisplayName() {
@Override
public BitbucketWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(BitbucketWeb.class, jsonObject);
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/browser/CGit.java b/src/main/java/hudson/plugins/git/browser/CGit.java
index 75883ab580..2f0d7980a5 100644
--- a/src/main/java/hudson/plugins/git/browser/CGit.java
+++ b/src/main/java/hudson/plugins/git/browser/CGit.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -7,15 +8,13 @@
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import hudson.scm.browsers.QueryBuilder;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser URLs
*/
@@ -58,7 +57,8 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
public URL getDiffLink(Path path) throws IOException {
GitChangeSet changeSet = path.getChangeSet();
URL url = getUrl();
- return new URL(url, url.getPath() + "diff/" + path.getPath() + param(url).add("id=" + changeSet.getId()));
+ return new URL(
+ url, url.getPath() + "diff/" + path.getPath() + param(url).add("id=" + changeSet.getId()));
}
/**
@@ -74,15 +74,19 @@ public URL getFileLink(Path path) throws IOException {
GitChangeSet changeSet = path.getChangeSet();
URL url = getUrl();
if (path.getEditType() == EditType.DELETE) {
- return encodeURL(new URL(url, url.getPath() + "tree/" + path.getPath() + param(url).add("id=" + changeSet.getParentCommit())));
+ return encodeURL(new URL(
+ url,
+ url.getPath() + "tree/" + path.getPath() + param(url).add("id=" + changeSet.getParentCommit())));
} else {
- return encodeURL(new URL(url, url.getPath() + "tree/" + path.getPath() + param(url).add("id=" + changeSet.getId())));
+ return encodeURL(new URL(
+ url, url.getPath() + "tree/" + path.getPath() + param(url).add("id=" + changeSet.getId())));
}
}
@Extension
@Symbol("cgit")
public static class CGITDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "cgit";
@@ -90,7 +94,7 @@ public String getDisplayName() {
@Override
public CGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(CGit.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java
index 260381e904..586ddb0418 100644
--- a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java
+++ b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -8,119 +9,124 @@
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
import hudson.util.FormValidation.URLCheck;
+import java.io.IOException;
+import java.net.URL;
+import java.util.regex.Pattern;
+import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.net.URL;
-import java.util.regex.Pattern;
+import org.kohsuke.stapler.interceptor.RequirePOST;
public class FisheyeGitRepositoryBrowser extends GitRepositoryBrowser {
- private static final long serialVersionUID = 2881872624557203410L;
+ private static final long serialVersionUID = 2881872624557203410L;
- @DataBoundConstructor
- public FisheyeGitRepositoryBrowser(String repoUrl) {
+ @DataBoundConstructor
+ public FisheyeGitRepositoryBrowser(String repoUrl) {
super(repoUrl);
- }
-
- @Override
- public URL getDiffLink(Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT)
- return null; // no diff if this is not an edit change
- String r1 = path.getChangeSet().getParentCommit();
- String r2 = path.getChangeSet().getId();
- return new URL(getUrl(), getPath(path) + String.format("?r1=%s&r2=%s", r1, r2));
- }
-
- @Override
- public URL getFileLink(Path path) throws IOException {
- return encodeURL(new URL(getUrl(), getPath(path)));
- }
-
- private String getPath(Path path) {
- return trimHeadSlash(path.getPath());
- }
-
- /**
- * Pick up "FOOBAR" from "http://site/browse/FOOBAR/"
- */
- private String getProjectName() throws IOException {
- String p = getUrl().getPath();
- if (p.endsWith("/"))
- p = p.substring(0, p.length() - 1);
-
- int idx = p.lastIndexOf('/');
- return p.substring(idx + 1);
- }
-
- @Override
- public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
- return new URL(getUrl(), "../../changelog/" + getProjectName() + "?cs=" + changeSet.getId());
- }
-
- @Extension
- @Symbol("fisheye")
- public static class FisheyeGitRepositoryBrowserDescriptor extends Descriptor> {
-
- @NonNull
- public String getDisplayName() {
- return "FishEye";
- }
-
- @Override
- public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
- return req.bindJSON(FisheyeGitRepositoryBrowser.class, jsonObject);
- }
-
- /**
- * Performs on-the-fly validation of the URL.
- * @param value URL value to be checked
- * @return form validation result
- * @throws IOException on input or output error
- * @throws ServletException on servlet error
- */
- @RequirePOST
- public FormValidation doCheckRepoUrl(@QueryParameter(fixEmpty = true) String value) throws IOException,
- ServletException {
- if (value == null) // nothing entered yet
- return FormValidation.ok();
-
- if (!value.endsWith("/"))
- value += '/';
- if (!URL_PATTERN.matcher(value).matches())
- return FormValidation.errorWithMarkup("The URL should end like .../browse/foobar/
");
-
- // Connect to URL and check content only if we have admin permission
- if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER))
- return FormValidation.ok();
-
- final String finalValue = value;
- return new URLCheck() {
- @Override
- protected FormValidation check() throws IOException, ServletException {
- try {
- if (findText(open(new URL(finalValue)), "FishEye")) {
- return FormValidation.ok();
- } else {
- return FormValidation.error("This is a valid URL but it doesn't look like FishEye");
- }
- } catch (IOException e) {
- return handleIOException(finalValue, e);
- }
- }
- }.check();
- }
-
- private static final Pattern URL_PATTERN = Pattern.compile(".+/browse/[^/]+/");
-
- }
+ }
+
+ @Override
+ public URL getDiffLink(Path path) throws IOException {
+ if (path.getEditType() != EditType.EDIT) {
+ return null; // no diff if this is not an edit change
+ }
+ String r1 = path.getChangeSet().getParentCommit();
+ String r2 = path.getChangeSet().getId();
+ return new URL(getUrl(), getPath(path) + String.format("?r1=%s&r2=%s", r1, r2));
+ }
+
+ @Override
+ public URL getFileLink(Path path) throws IOException {
+ return encodeURL(new URL(getUrl(), getPath(path)));
+ }
+
+ private String getPath(Path path) {
+ return trimHeadSlash(path.getPath());
+ }
+
+ /**
+ * Pick up "FOOBAR" from "http://site/browse/FOOBAR/"
+ */
+ private String getProjectName() throws IOException {
+ String p = getUrl().getPath();
+ if (p.endsWith("/")) {
+ p = p.substring(0, p.length() - 1);
+ }
+
+ int idx = p.lastIndexOf('/');
+ return p.substring(idx + 1);
+ }
+
+ @Override
+ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
+ return new URL(getUrl(), "../../changelog/" + getProjectName() + "?cs=" + changeSet.getId());
+ }
+
+ @Extension
+ @Symbol("fisheye")
+ public static class FisheyeGitRepositoryBrowserDescriptor extends Descriptor> {
+
+ @Override
+ @NonNull
+ public String getDisplayName() {
+ return "FishEye";
+ }
+
+ @Override
+ public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject)
+ throws FormException {
+ assert req != null; // see inherited javadoc
+ return req.bindJSON(FisheyeGitRepositoryBrowser.class, jsonObject);
+ }
+
+ /**
+ * Performs on-the-fly validation of the URL.
+ * @param value URL value to be checked
+ * @return form validation result
+ * @throws IOException on input or output error
+ * @throws ServletException on servlet error
+ */
+ @RequirePOST
+ public FormValidation doCheckRepoUrl(@QueryParameter(fixEmpty = true) String value)
+ throws IOException, ServletException {
+ if (value == null) { // nothing entered yet
+ return FormValidation.ok();
+ }
+
+ if (!value.endsWith("/")) {
+ value += '/';
+ }
+ if (!URL_PATTERN.matcher(value).matches()) {
+ return FormValidation.errorWithMarkup("The URL should end like .../browse/foobar/
");
+ }
+
+ // Connect to URL and check content only if we have admin permission
+ if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
+ return FormValidation.ok();
+ }
+
+ final String finalValue = value;
+ return new URLCheck() {
+ @Override
+ protected FormValidation check() throws IOException, ServletException {
+ try {
+ if (findText(open(new URL(finalValue)), "FishEye")) {
+ return FormValidation.ok();
+ } else {
+ return FormValidation.error("This is a valid URL but it doesn't look like FishEye");
+ }
+ } catch (IOException e) {
+ return handleIOException(finalValue, e);
+ }
+ }
+ }.check();
+ }
+
+ private static final Pattern URL_PATTERN = Pattern.compile(".+/browse/[^/]+/");
+ }
}
diff --git a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java
index a6d312be5c..54c6e99fd1 100644
--- a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java
+++ b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
@@ -11,21 +12,19 @@
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
import hudson.util.FormValidation.URLCheck;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
+import org.kohsuke.stapler.interceptor.RequirePOST;
public class GitBlitRepositoryBrowser extends GitRepositoryBrowser {
@@ -42,8 +41,12 @@ public GitBlitRepositoryBrowser(String repoUrl, String projectName) {
@Override
public URL getDiffLink(Path path) throws IOException {
URL url = getUrl();
- return new URL(url,
- String.format(url.getPath() + "blobdiff?r=%s&h=%s&hb=%s", encodeString(projectName), path.getChangeSet().getId(),
+ return new URL(
+ url,
+ String.format(
+ url.getPath() + "blobdiff?r=%s&h=%s&hb=%s",
+ encodeString(projectName),
+ path.getChangeSet().getId(),
path.getChangeSet().getParentCommit()));
}
@@ -53,53 +56,60 @@ public URL getFileLink(Path path) throws IOException {
return null;
}
URL url = getUrl();
- return new URL(url,
- String.format(url.getPath() + "blob?r=%s&h=%s&f=%s", encodeString(projectName), path.getChangeSet().getId(),
+ return new URL(
+ url,
+ String.format(
+ url.getPath() + "blob?r=%s&h=%s&f=%s",
+ encodeString(projectName),
+ path.getChangeSet().getId(),
encodeString(path.getPath())));
}
@Override
public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
URL url = getUrl();
- return new URL(url, String.format(url.getPath() + "commit?r=%s&h=%s", encodeString(projectName), changeSet.getId()));
+ return new URL(
+ url, String.format(url.getPath() + "commit?r=%s&h=%s", encodeString(projectName), changeSet.getId()));
}
public String getProjectName() {
return projectName;
}
- private String encodeString(final String s) {
+ private String encodeString(final String s) {
return URLEncoder.encode(s, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
}
@Extension
@Symbol("gitblit")
public static class ViewGitWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitblit";
}
@Override
- public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject)
+ throws FormException {
+ assert req != null; // see inherited javadoc
return req.bindJSON(GitBlitRepositoryBrowser.class, jsonObject);
}
@RequirePOST
- public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
+ public FormValidation doCheckRepoUrl(
+ @AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
throws IOException, ServletException, URISyntaxException {
String cleanUrl = Util.fixEmptyAndTrim(repoUrl);
- if (initialChecksAndReturnOk(project, cleanUrl))
- {
+ if (initialChecksAndReturnOk(project, cleanUrl)) {
return FormValidation.ok();
}
- if (!validateUrl(cleanUrl))
- {
+ if (!validateUrl(cleanUrl)) {
return FormValidation.error(Messages.invalidUrl());
}
return new URLCheck() {
+ @Override
protected FormValidation check() throws IOException, ServletException {
String v = cleanUrl;
if (!v.endsWith("/")) {
diff --git a/src/main/java/hudson/plugins/git/browser/GitLab.java b/src/main/java/hudson/plugins/git/browser/GitLab.java
index 5c9d6ab48d..df948efe9e 100644
--- a/src/main/java/hudson/plugins/git/browser/GitLab.java
+++ b/src/main/java/hudson/plugins/git/browser/GitLab.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -7,20 +8,15 @@
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
+import java.io.IOException;
+import java.net.URL;
+import javax.servlet.ServletException;
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
-import org.kohsuke.stapler.StaplerRequest;
-
-import java.io.IOException;
-import java.net.URL;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-
import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
/**
* Git Browser for GitLab
@@ -136,6 +132,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("gitLab")
public static class GitLabDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitlab";
@@ -143,7 +140,7 @@ public String getDisplayName() {
@Override
public GitLab newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(GitLab.class, jsonObject);
}
@@ -170,11 +167,10 @@ public FormValidation doCheckVersion(@QueryParameter(fixEmpty = true) final Stri
}
private String calculatePrefix() {
- if(getVersionDouble() < 3) {
+ if (getVersionDouble() < 3) {
return "commits/";
} else {
return "commit/";
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/browser/GitList.java b/src/main/java/hudson/plugins/git/browser/GitList.java
index 5780129763..8721acc827 100644
--- a/src/main/java/hudson/plugins/git/browser/GitList.java
+++ b/src/main/java/hudson/plugins/git/browser/GitList.java
@@ -1,21 +1,19 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser URLs
*/
@@ -44,8 +42,10 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(Path path) throws IOException {
- if(path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
- || path.getChangeSet().getParentCommit() == null) {
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
+ || path.getChangeSet().getParentCommit() == null) {
return null;
}
return getDiffLinkRegardlessOfEditType(path);
@@ -59,7 +59,7 @@ public URL getDiffLink(Path path) throws IOException {
* @throws IOException on input or output error
*/
private URL getDiffLinkRegardlessOfEditType(Path path) throws IOException {
- //GitList diff indices begin at 1
+ // GitList diff indices begin at 1
return encodeURL(new URL(getChangeSetLink(path.getChangeSet()), "#" + (getIndexOfPath(path) + 1)));
}
@@ -85,6 +85,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("gitList")
public static class GitListDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitlist";
@@ -92,7 +93,7 @@ public String getDisplayName() {
@Override
public GitList newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(GitList.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java
index 814d8ce19d..564fa88a67 100644
--- a/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java
+++ b/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.EnvVars;
import hudson.model.Item;
import hudson.model.Job;
@@ -7,10 +8,6 @@
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.RepositoryBrowser;
-
-import org.kohsuke.stapler.Stapler;
-import org.kohsuke.stapler.StaplerRequest;
-
import java.io.IOException;
import java.net.IDN;
import java.net.InetAddress;
@@ -24,8 +21,8 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
-
-import edu.umd.cs.findbugs.annotations.CheckForNull;
+import org.kohsuke.stapler.Stapler;
+import org.kohsuke.stapler.StaplerRequest;
public abstract class GitRepositoryBrowser extends RepositoryBrowser {
@@ -33,8 +30,7 @@ public abstract class GitRepositoryBrowser extends RepositoryBrowser> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitweb";
@@ -92,9 +104,8 @@ public String getDisplayName() {
@Override
public GitWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(GitWeb.class, jsonObject);
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/browser/GithubWeb.java b/src/main/java/hudson/plugins/git/browser/GithubWeb.java
index 8f63633956..c2056534ce 100644
--- a/src/main/java/hudson/plugins/git/browser/GithubWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/GithubWeb.java
@@ -1,21 +1,19 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser URLs
*/
@@ -31,7 +29,7 @@ public GithubWeb(String repoUrl) {
@Override
public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
URL url = getUrl();
- return new URL(url, url.getPath()+"commit/" + changeSet.getId());
+ return new URL(url, url.getPath() + "commit/" + changeSet.getId());
}
/**
@@ -44,7 +42,9 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
|| path.getChangeSet().getParentCommit() == null) {
return null;
}
@@ -59,7 +59,7 @@ public URL getDiffLink(Path path) throws IOException {
* @throws IOException on input or output error
*/
private URL getDiffLinkRegardlessOfEditType(Path path) throws IOException {
- // Github seems to sort the output alphabetically by the path.
+ // Github seems to sort the output alphabetically by the path.
return new URL(getChangeSetLink(path.getChangeSet()), "#diff-" + getIndexOfPath(path));
}
@@ -91,16 +91,16 @@ private URL buildURL(String spec) throws IOException {
@Extension
@Symbol("github")
public static class GithubWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "githubweb";
}
@Override
- public GithubWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
- return req.bindJSON(GithubWeb.class, jsonObject);
- }
- }
-
+ public GithubWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
+ assert req != null; // see inherited javadoc
+ return req.bindJSON(GithubWeb.class, jsonObject);
+ }
+ }
}
diff --git a/src/main/java/hudson/plugins/git/browser/Gitiles.java b/src/main/java/hudson/plugins/git/browser/Gitiles.java
index c56349274d..3988e04109 100644
--- a/src/main/java/hudson/plugins/git/browser/Gitiles.java
+++ b/src/main/java/hudson/plugins/git/browser/Gitiles.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
@@ -10,22 +11,17 @@
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
import hudson.util.FormValidation.URLCheck;
-
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
import javax.servlet.ServletException;
-
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* @author Manolo Carrasco Moñino
@@ -59,10 +55,10 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
return new URL(url + "+/" + changeSet.getId() + "%5E%21");
}
-
@Extension
@Symbol("gitiles")
public static class ViewGitWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitiles";
@@ -70,26 +66,29 @@ public String getDisplayName() {
@Override
public Gitiles newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(Gitiles.class, jsonObject);
}
@RequirePOST
- public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
+ public FormValidation doCheckRepoUrl(
+ @AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
throws IOException, ServletException, URISyntaxException {
String cleanUrl = Util.fixEmptyAndTrim(repoUrl);
- if(initialChecksAndReturnOk(project, cleanUrl)){
+ if (initialChecksAndReturnOk(project, cleanUrl)) {
return FormValidation.ok();
}
if (!validateUrl(cleanUrl)) {
return FormValidation.error(Messages.invalidUrl());
}
return new URLCheck() {
+ @Override
protected FormValidation check() throws IOException, ServletException {
String v = cleanUrl;
- if (!v.endsWith("/"))
+ if (!v.endsWith("/")) {
v += '/';
+ }
try {
// gitiles has a line in main page indicating how to clone the project
diff --git a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java
index 8481dcb7f7..3b504e8846 100644
--- a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java
@@ -1,19 +1,18 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser for Gitorious
*/
@@ -33,9 +32,9 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
/**
* Creates a link to the commit diff.
- *
+ *
* {@code https://[Gitorious URL]/commit/a9182a07750c9a0dfd89a8461adf72ef5ef0885b/diffs?diffmode=sidebyside&fragment=1#[path to file]}
- *
+ *
* @param path file path used in diff link
* @return diff link
* @throws IOException on input or output error
@@ -43,13 +42,14 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
@Override
public URL getDiffLink(Path path) throws IOException {
final GitChangeSet changeSet = path.getChangeSet();
- return encodeURL(new URL(getUrl(), "commit/" + changeSet.getId() + "/diffs?diffmode=sidebyside&fragment=1#" + path.getPath()));
+ return encodeURL(new URL(
+ getUrl(), "commit/" + changeSet.getId() + "/diffs?diffmode=sidebyside&fragment=1#" + path.getPath()));
}
/**
* Creates a link to the file.
* {@code https://[Gitorious URL]/blobs/a9182a07750c9a0dfd89a8461adf72ef5ef0885b/pom.xml}
- *
+ *
* @param path file path used in diff link
* @return file link
* @throws IOException on input or output error
@@ -67,6 +67,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
public static class GitoriousWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gitoriousweb";
@@ -74,9 +75,8 @@ public String getDisplayName() {
@Override
public GitoriousWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(GitoriousWeb.class, jsonObject);
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/browser/GogsGit.java b/src/main/java/hudson/plugins/git/browser/GogsGit.java
index ac14059794..c00e37a57f 100644
--- a/src/main/java/hudson/plugins/git/browser/GogsGit.java
+++ b/src/main/java/hudson/plugins/git/browser/GogsGit.java
@@ -1,21 +1,19 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* @author Norbert Lange (nolange79@gmail.com)
*/
@@ -52,7 +50,9 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
|| path.getChangeSet().getParentCommit() == null) {
return null;
}
@@ -86,13 +86,15 @@ public URL getFileLink(Path path) throws IOException {
return getDiffLinkRegardlessOfEditType(path);
} else {
URL url = getUrl();
- return encodeURL(new URL(url, url.getPath() + "src/" + path.getChangeSet().getId() + "/" + path.getPath()));
+ return encodeURL(
+ new URL(url, url.getPath() + "src/" + path.getChangeSet().getId() + "/" + path.getPath()));
}
}
@Extension
@Symbol("gogs")
public static class GogsGitDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "gogs";
@@ -100,7 +102,7 @@ public String getDisplayName() {
@Override
public GogsGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(GogsGit.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/KilnGit.java b/src/main/java/hudson/plugins/git/browser/KilnGit.java
index b42d8eb140..615c0ed5d0 100644
--- a/src/main/java/hudson/plugins/git/browser/KilnGit.java
+++ b/src/main/java/hudson/plugins/git/browser/KilnGit.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -7,16 +8,13 @@
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import hudson.scm.browsers.QueryBuilder;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
-
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* @author Chris Klaiber (cklaiber@gmail.com)
*/
@@ -57,7 +55,9 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
*/
@Override
public URL getDiffLink(Path path) throws IOException {
- if (path.getEditType() != EditType.EDIT || path.getSrc() == null || path.getDst() == null
+ if (path.getEditType() != EditType.EDIT
+ || path.getSrc() == null
+ || path.getDst() == null
|| path.getChangeSet().getParentCommit() == null) {
return null;
}
@@ -97,13 +97,16 @@ public URL getFileLink(Path path) throws IOException {
} else {
GitChangeSet changeSet = path.getChangeSet();
URL url = getUrl();
- return encodeURL(new URL(url, url.getPath() + "FileHistory/" + path.getPath() + param(url).add("rev=" + changeSet.getId())));
+ return encodeURL(new URL(
+ url,
+ url.getPath() + "FileHistory/" + path.getPath() + param(url).add("rev=" + changeSet.getId())));
}
}
@Extension
@Symbol("kiln")
public static class KilnGitDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "Kiln";
@@ -111,7 +114,7 @@ public String getDisplayName() {
@Override
public KilnGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(KilnGit.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/Phabricator.java b/src/main/java/hudson/plugins/git/browser/Phabricator.java
index fc0fe43372..e507fb0101 100644
--- a/src/main/java/hudson/plugins/git/browser/Phabricator.java
+++ b/src/main/java/hudson/plugins/git/browser/Phabricator.java
@@ -1,19 +1,18 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser for Phabricator
*/
@@ -83,6 +82,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("phabricator")
public static class PhabricatorDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "phabricator";
@@ -90,7 +90,7 @@ public String getDisplayName() {
@Override
public Phabricator newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(Phabricator.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java
index 10ad08568d..f8ca9fb6f8 100644
--- a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java
@@ -1,23 +1,22 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Git Browser for Redmine.
- *
+ *
* @author mfriedenhagen
*/
public class RedmineWeb extends GitRepositoryBrowser {
@@ -37,13 +36,13 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
/**
* Creates a link to the file diff.
- *
+ *
* https://SERVER/PATH/projects/PROJECT/repository/revisions/a9182a07750c9a0dfd89a8461adf72ef5ef0885b/diff/pom.xml
- *
+ *
* Returns a diff link for {@link EditType#DELETE} and {@link EditType#EDIT}, for {@link EditType#ADD} returns an
* {@link #getFileLink}.
- *
- *
+ *
+ *
* @param path
* affected file path
* @return diff link
@@ -67,7 +66,7 @@ public URL getDiffLink(Path path) throws IOException {
* Creates a link to the file.
* https://SERVER/PATH/projects/PROJECT/repository/revisions/a9182a07750c9a0dfd89a8461adf72ef5ef0885b/entry/pom.xml
* For deleted files just returns a diff link, which will have /dev/null as target file.
- *
+ *
* @param path affected file path
* @return file link
* @throws IOException on input or output error
@@ -86,6 +85,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("redmine")
public static class RedmineWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "redmineweb";
@@ -93,9 +93,8 @@ public String getDisplayName() {
@Override
public RedmineWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(RedmineWeb.class, jsonObject);
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/browser/RhodeCode.java b/src/main/java/hudson/plugins/git/browser/RhodeCode.java
index 1e644c4cc8..ef0dcee41c 100644
--- a/src/main/java/hudson/plugins/git/browser/RhodeCode.java
+++ b/src/main/java/hudson/plugins/git/browser/RhodeCode.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -7,15 +8,13 @@
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import hudson.scm.browsers.QueryBuilder;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* RhodeCode Browser URLs
*/
@@ -58,7 +57,11 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
public URL getDiffLink(Path path) throws IOException {
GitChangeSet changeSet = path.getChangeSet();
URL url = getUrl();
- return new URL(url, url.getPath() + "diff/" + path.getPath() + param(url).add("diff2=" + changeSet.getParentCommit()).add("diff1=" + changeSet.getId()) + "&diff=diff+to+revision");
+ return new URL(
+ url,
+ url.getPath() + "diff/" + path.getPath()
+ + param(url).add("diff2=" + changeSet.getParentCommit()).add("diff1=" + changeSet.getId())
+ + "&diff=diff+to+revision");
}
/**
@@ -88,6 +91,7 @@ public URL getFileLink(Path path) throws IOException {
@Extension
@Symbol("rhodeCode")
public static class RhodeCodeDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "rhodecode";
@@ -95,7 +99,7 @@ public String getDisplayName() {
@Override
public RhodeCode newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(RhodeCode.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/Stash.java b/src/main/java/hudson/plugins/git/browser/Stash.java
index 3d1d4d429d..c12b9b9f7d 100644
--- a/src/main/java/hudson/plugins/git/browser/Stash.java
+++ b/src/main/java/hudson/plugins/git/browser/Stash.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.plugins.git.GitChangeSet;
@@ -7,14 +8,12 @@
import hudson.scm.EditType;
import hudson.scm.RepositoryBrowser;
import hudson.scm.browsers.QueryBuilder;
+import java.io.IOException;
+import java.net.URL;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.io.IOException;
-import java.net.URL;
-
/**
* Stash Browser URLs
*/
@@ -59,9 +58,17 @@ public URL getDiffLink(Path path) throws IOException {
URL url = getUrl();
if (path.getEditType() == EditType.DELETE) {
- return new URL(url, url.getPath() + "diff/" + path.getPath() + param(url).add("at=" + changeSet.getParentCommit()).add("until=" + changeSet.getId()));
+ return new URL(
+ url,
+ url.getPath() + "diff/" + path.getPath()
+ + param(url)
+ .add("at=" + changeSet.getParentCommit())
+ .add("until=" + changeSet.getId()));
} else {
- return new URL(url, url.getPath() + "diff/" + path.getPath() + param(url).add("at=" + changeSet.getId()).add("until=" + changeSet.getId()));
+ return new URL(
+ url,
+ url.getPath() + "diff/" + path.getPath()
+ + param(url).add("at=" + changeSet.getId()).add("until=" + changeSet.getId()));
}
}
@@ -79,15 +86,20 @@ public URL getFileLink(Path path) throws IOException {
URL url = getUrl();
if (path.getEditType() == EditType.DELETE) {
- return encodeURL(new URL(url, url.getPath() + "browse/" + path.getPath() + param(url).add("at=" + changeSet.getParentCommit())));
+ return encodeURL(new URL(
+ url,
+ url.getPath() + "browse/" + path.getPath() + param(url).add("at=" + changeSet.getParentCommit())));
} else {
- return encodeURL(new URL(url, url.getPath() + "browse/" + path.getPath() + param(url).add("at=" + changeSet.getId())));
+ return encodeURL(new URL(
+ url, url.getPath() + "browse/" + path.getPath() + param(url).add("at=" + changeSet.getId())));
}
}
@Extension
- // @Symbol("stash") // Intentionally not providing a symbol named 'stash', would collide with existing 'stash' Pipeline step
+ // @Symbol("stash") // Intentionally not providing a symbol named 'stash', would collide with existing 'stash'
+ // Pipeline step
public static class StashDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "stash";
@@ -95,7 +107,7 @@ public String getDisplayName() {
@Override
public Stash newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(Stash.class, jsonObject);
}
}
diff --git a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java
index a90e2115a3..530c2fffa6 100644
--- a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java
+++ b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractProject;
@@ -8,22 +9,20 @@
import hudson.plugins.git.GitSCM;
import hudson.scm.RepositoryBrowser;
import hudson.util.FormValidation;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.regex.Pattern;
+import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.eclipse.jgit.transport.RemoteConfig;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.regex.Pattern;
+import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Browser for Git repositories on Microsoft Team Foundation Server (TFS) 2013 and higher versions using the
@@ -38,13 +37,15 @@ public TFS2013GitRepositoryBrowser(String repoUrl) {
@Override
public URL getDiffLink(GitChangeSet.Path path) throws IOException {
- String spec = String.format("commit/%s#path=%s&_a=compare", path.getChangeSet().getId(), path.getPath());
+ String spec = String.format(
+ "commit/%s#path=%s&_a=compare", path.getChangeSet().getId(), path.getPath());
return new URL(getRepoUrl(path.getChangeSet()), spec);
}
@Override
public URL getFileLink(GitChangeSet.Path path) throws IOException {
- String spec = String.format("commit/%s#path=%s&_a=history", path.getChangeSet().getId(), path.getPath());
+ String spec = String.format(
+ "commit/%s#path=%s&_a=history", path.getChangeSet().getId(), path.getPath());
return encodeURL(new URL(getRepoUrl(path.getChangeSet()), spec));
}
@@ -55,12 +56,12 @@ public URL getChangeSetLink(GitChangeSet gitChangeSet) throws IOException {
/*default*/ URL getRepoUrl(GitChangeSet changeSet) throws IOException { // default visibility for tests
String result = getRepoUrl();
-
- if (result == null || result.isBlank())
- return normalizeToEndWithSlash(getUrlFromFirstConfiguredRepository(changeSet));
- else if (!result.contains("/"))
+ if (result == null || result.isBlank()) {
+ return normalizeToEndWithSlash(getUrlFromFirstConfiguredRepository(changeSet));
+ } else if (!result.contains("/")) {
return normalizeToEndWithSlash(getResultFromNamedRepository(changeSet));
+ }
return getUrl();
}
@@ -76,7 +77,8 @@ private URL getUrlFromFirstConfiguredRepository(GitChangeSet changeSet) throws M
}
private GitSCM getScmFromProject(GitChangeSet changeSet) {
- AbstractProject,?> build = (AbstractProject, ?>) changeSet.getParent().getRun().getParent();
+ AbstractProject, ?> build =
+ (AbstractProject, ?>) changeSet.getParent().getRun().getParent();
return (GitSCM) build.getScm();
}
@@ -85,15 +87,19 @@ private GitSCM getScmFromProject(GitChangeSet changeSet) {
@Symbol("teamFoundation")
public static class TFS2013GitRepositoryBrowserDescriptor extends Descriptor> {
- private static final String REPOSITORY_BROWSER_LABEL = "Microsoft Team Foundation Server/Visual Studio Team Services";
+ private static final String REPOSITORY_BROWSER_LABEL =
+ "Microsoft Team Foundation Server/Visual Studio Team Services";
+
+ @Override
@NonNull
public String getDisplayName() {
return REPOSITORY_BROWSER_LABEL;
}
@Override
- public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject)
+ throws FormException {
+ assert req != null; // see inherited javadoc
try {
req.getSubmittedForm();
} catch (ServletException e) {
@@ -111,29 +117,36 @@ public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSON
* @throws ServletException on servlet error
*/
@RequirePOST
- public FormValidation doCheckRepoUrl(@QueryParameter(fixEmpty = true) String value, @AncestorInPath AbstractProject project) throws IOException,
- ServletException {
+ public FormValidation doCheckRepoUrl(
+ @QueryParameter(fixEmpty = true) String value, @AncestorInPath AbstractProject project)
+ throws IOException, ServletException {
// Connect to URL and check content only if we have admin permission
- if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER))
+ if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
+ }
- if (value == null) // nothing entered yet
+ if (value == null) { // nothing entered yet
value = "origin";
+ }
if (!value.contains("/") && project != null) {
GitSCM scm = (GitSCM) project.getScm();
RemoteConfig remote = scm.getRepositoryByName(value);
- if (remote == null)
- return FormValidation.errorWithMarkup("There is no remote with the name " + Util.escape(value) + "
");
-
+ if (remote == null) {
+ return FormValidation.errorWithMarkup(
+ "There is no remote with the name " + Util.escape(value) + "
");
+ }
+
value = remote.getURIs().get(0).toString();
}
-
- if (!value.endsWith("/"))
+
+ if (!value.endsWith("/")) {
value += '/';
- if (!URL_PATTERN.matcher(value).matches())
+ }
+ if (!URL_PATTERN.matcher(value).matches()) {
return FormValidation.errorWithMarkup("The URL should end like .../_git/foobar/
");
+ }
final String finalValue = value;
return new FormValidation.URLCheck() {
@@ -143,7 +156,8 @@ protected FormValidation check() throws IOException, ServletException {
if (findText(open(new URL(finalValue)), "icrosoft")) {
return FormValidation.ok();
} else {
- return FormValidation.error("This is a valid URL but it doesn't look like a Microsoft server");
+ return FormValidation.error(
+ "This is a valid URL but it doesn't look like a Microsoft server");
}
} catch (IOException e) {
return handleIOException(finalValue, e);
diff --git a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java
index c5e0145763..5b79ccae46 100644
--- a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java
+++ b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.browser;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.Descriptor;
@@ -12,21 +13,19 @@
import hudson.scm.browsers.QueryBuilder;
import hudson.util.FormValidation;
import hudson.util.FormValidation.URLCheck;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import javax.servlet.ServletException;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
+import org.kohsuke.stapler.interceptor.RequirePOST;
public class ViewGitWeb extends GitRepositoryBrowser {
@@ -45,7 +44,7 @@ public URL getDiffLink(Path path) throws IOException {
if (path.getEditType() == EditType.EDIT) {
URL url = getUrl();
String spec = buildCommitDiffSpec(url, path);
- return new URL(url, url.getPath() + spec);
+ return new URL(url, url.getPath() + spec);
}
return null;
}
@@ -57,18 +56,30 @@ public URL getFileLink(Path path) throws IOException {
String spec = buildCommitDiffSpec(url, path);
return encodeURL(new URL(url, url.getPath() + spec));
}
- String spec = param(url).add("p=" + projectName).add("a=viewblob").add("h=" + path.getDst()).add("f=" + path.getPath()).toString();
+ String spec = param(url)
+ .add("p=" + projectName)
+ .add("a=viewblob")
+ .add("h=" + path.getDst())
+ .add("f=" + path.getPath())
+ .toString();
return encodeURL(new URL(url, url.getPath() + spec));
}
- private String buildCommitDiffSpec(URL url, Path path) {
- return param(url).add("p=" + projectName).add("a=commitdiff").add("h=" + path.getChangeSet().getId()) + "#" + URLEncoder.encode(path.getPath(), StandardCharsets.UTF_8);
- }
+ private String buildCommitDiffSpec(URL url, Path path) {
+ return param(url)
+ .add("p=" + projectName)
+ .add("a=commitdiff")
+ .add("h=" + path.getChangeSet().getId()) + "#"
+ + URLEncoder.encode(path.getPath(), StandardCharsets.UTF_8);
+ }
@Override
public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
URL url = getUrl();
- return new URL(url, url.getPath() + param(url).add("p=" + projectName).add("a=commit").add("h=" + changeSet.getId()));
+ return new URL(
+ url,
+ url.getPath()
+ + param(url).add("p=" + projectName).add("a=commit").add("h=" + changeSet.getId()));
}
private QueryBuilder param(URL url) {
@@ -82,6 +93,7 @@ public String getProjectName() {
@Extension
@Symbol("viewgit")
public static class ViewGitWebDescriptor extends Descriptor> {
+ @Override
@NonNull
public String getDisplayName() {
return "viewgit";
@@ -89,26 +101,30 @@ public String getDisplayName() {
@Override
public ViewGitWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException {
- assert req != null; //see inherited javadoc
+ assert req != null; // see inherited javadoc
return req.bindJSON(ViewGitWeb.class, jsonObject);
}
@RequirePOST
- public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
+ public FormValidation doCheckRepoUrl(
+ @AncestorInPath Item project, @QueryParameter(fixEmpty = true) final String repoUrl)
throws IOException, ServletException, URISyntaxException {
String cleanUrl = Util.fixEmptyAndTrim(repoUrl);
// Connect to URL and check content only if we have admin permission
- if (initialChecksAndReturnOk(project, cleanUrl))
+ if (initialChecksAndReturnOk(project, cleanUrl)) {
return FormValidation.ok();
+ }
if (!validateUrl(cleanUrl)) {
return FormValidation.error(Messages.invalidUrl());
}
return new URLCheck() {
+ @Override
protected FormValidation check() throws IOException, ServletException {
String v = cleanUrl;
- if (!v.endsWith("/"))
+ if (!v.endsWith("/")) {
v += '/';
+ }
try {
if (findText(open(new URL(v)), "ViewGit")) {
diff --git a/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java b/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java
index caa113847e..3360035aa3 100644
--- a/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java
+++ b/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java
@@ -10,10 +10,9 @@
import io.jenkins.plugins.casc.ConfiguratorException;
import io.jenkins.plugins.casc.model.CNode;
import io.jenkins.plugins.casc.model.Mapping;
-import org.apache.commons.lang.StringUtils;
-
import java.util.Collections;
import java.util.List;
+import org.apache.commons.lang.StringUtils;
@Extension(optional = true)
public class GitLabConfigurator extends BaseConfigurator {
@@ -58,5 +57,4 @@ public Class getTarget() {
public List> getConfigurators(ConfigurationContext context) {
return Collections.singletonList(this);
}
-
}
diff --git a/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java b/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java
index 64986d9d1e..6d5f7f2d28 100644
--- a/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java
+++ b/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java
@@ -15,5 +15,4 @@
* @author Kohsuke Kawaguchi
*/
@Restricted(NoExternalUse.class)
-public abstract class FakeGitSCMExtension extends GitSCMExtension {
-}
+public abstract class FakeGitSCMExtension extends GitSCMExtension {}
diff --git a/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java b/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java
index e1818caa37..2dfa2a180b 100644
--- a/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java
+++ b/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java
@@ -3,5 +3,4 @@
/**
* @author Nicolas De Loof
*/
-public class GitClientConflictException extends Exception {
-}
+public class GitClientConflictException extends Exception {}
diff --git a/src/main/java/hudson/plugins/git/extensions/GitClientType.java b/src/main/java/hudson/plugins/git/extensions/GitClientType.java
index 6a8b07dcaf..894fe18779 100644
--- a/src/main/java/hudson/plugins/git/extensions/GitClientType.java
+++ b/src/main/java/hudson/plugins/git/extensions/GitClientType.java
@@ -1,22 +1,28 @@
package hudson.plugins.git.extensions;
/**
-* @author Nicolas De Loof
-*/
+ * @author Nicolas De Loof
+ */
public enum GitClientType {
JGIT {
@Override
public GitClientType combine(GitClientType c) throws GitClientConflictException {
- if (c == GITCLI) throw new GitClientConflictException();
+ if (c == GITCLI) {
+ throw new GitClientConflictException();
+ }
return this;
}
- }, GITCLI {
+ },
+ GITCLI {
@Override
public GitClientType combine(GitClientType c) throws GitClientConflictException {
- if (c == JGIT) throw new GitClientConflictException();
+ if (c == JGIT) {
+ throw new GitClientConflictException();
+ }
return this;
}
- }, ANY {
+ },
+ ANY {
@Override
public GitClientType combine(GitClientType c) {
return c;
diff --git a/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java b/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java
index 98180eee62..e29b38f057 100644
--- a/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java
+++ b/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java
@@ -25,7 +25,6 @@
import java.io.File;
import java.io.IOException;
import java.util.Map;
-
import org.jenkinsci.plugins.gitclient.*;
/**
@@ -62,9 +61,13 @@ public boolean requiresWorkspaceForPolling() {
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- @SuppressFBWarnings(value="NP_BOOLEAN_RETURN_NULL", justification="null used to indicate other extensions should decide")
+ @SuppressFBWarnings(
+ value = "NP_BOOLEAN_RETURN_NULL",
+ justification = "null used to indicate other extensions should decide")
@CheckForNull
- public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) throws IOException, InterruptedException, GitException {
+ public Boolean isRevExcluded(
+ GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData)
+ throws IOException, InterruptedException, GitException {
return null;
}
@@ -81,7 +84,9 @@ public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, Tas
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public FilePath getWorkingDirectory(GitSCM scm, Job, ?> context, FilePath workspace, EnvVars environment, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public FilePath getWorkingDirectory(
+ GitSCM scm, Job, ?> context, FilePath workspace, EnvVars environment, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
if (context instanceof AbstractProject) {
return getWorkingDirectory(scm, (AbstractProject) context, workspace, environment, listener);
}
@@ -89,8 +94,18 @@ public FilePath getWorkingDirectory(GitSCM scm, Job, ?> context, FilePath work
}
@Deprecated
- public FilePath getWorkingDirectory(GitSCM scm, AbstractProject, ?> context, FilePath workspace, EnvVars environment, TaskListener listener) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "getWorkingDirectory", GitSCM.class, Job.class, FilePath.class, EnvVars.class, TaskListener.class)) {
+ public FilePath getWorkingDirectory(
+ GitSCM scm, AbstractProject, ?> context, FilePath workspace, EnvVars environment, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "getWorkingDirectory",
+ GitSCM.class,
+ Job.class,
+ FilePath.class,
+ EnvVars.class,
+ TaskListener.class)) {
return getWorkingDirectory(scm, (Job) context, workspace, environment, listener);
}
return null;
@@ -135,17 +150,30 @@ public FilePath getWorkingDirectory(GitSCM scm, AbstractProject, ?> context, F
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public Revision decorateRevisionToBuild(GitSCM scm, Run,?> build, GitClient git, TaskListener listener, Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
+ public Revision decorateRevisionToBuild(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, Revision marked, Revision rev)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
return decorateRevisionToBuild(scm, (AbstractBuild) build, git, (BuildListener) listener, marked, rev);
} else {
return rev;
}
}
-
+
@Deprecated
- public Revision decorateRevisionToBuild(GitSCM scm, AbstractBuild,?> build, GitClient git, BuildListener listener, Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "decorateRevisionToBuild", GitSCM.class, Run.class, GitClient.class, TaskListener.class, Revision.class, Revision.class)) {
+ public Revision decorateRevisionToBuild(
+ GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, Revision marked, Revision rev)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "decorateRevisionToBuild",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class,
+ Revision.class,
+ Revision.class)) {
return decorateRevisionToBuild(scm, (Run) build, git, listener, marked, rev);
} else {
return rev;
@@ -162,15 +190,24 @@ public Revision decorateRevisionToBuild(GitSCM scm, AbstractBuild,?> build, Gi
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void beforeCheckout(GitSCM scm, Run,?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void beforeCheckout(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
beforeCheckout(scm, (AbstractBuild) build, git, (BuildListener) listener);
}
}
@Deprecated
- public void beforeCheckout(GitSCM scm, AbstractBuild,?> build, GitClient git, BuildListener listener) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "beforeCheckout", GitSCM.class, Run.class, GitClient.class, TaskListener.class)) {
+ public void beforeCheckout(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "beforeCheckout",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class)) {
beforeCheckout(scm, (Run) build, git, listener);
}
}
@@ -191,15 +228,24 @@ public void beforeCheckout(GitSCM scm, AbstractBuild,?> build, GitClient git,
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
onCheckoutCompleted(scm, (AbstractBuild) build, git, (BuildListener) listener);
}
}
@Deprecated
- public void onCheckoutCompleted(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "onCheckoutCompleted", GitSCM.class, Run.class, GitClient.class, TaskListener.class)) {
+ public void onCheckoutCompleted(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "onCheckoutCompleted",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class)) {
onCheckoutCompleted(scm, (Run) build, git, listener);
}
}
@@ -214,8 +260,7 @@ public void onCheckoutCompleted(GitSCM scm, AbstractBuild, ?> build, GitClient
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void onClean(GitSCM scm, GitClient git) throws IOException, InterruptedException, GitException {
- }
+ public void onClean(GitSCM scm, GitClient git) throws IOException, InterruptedException, GitException {}
/**
* Called when {@link GitClient} is created to decorate its behaviour.
@@ -236,9 +281,7 @@ public GitClient decorate(GitSCM scm, GitClient git) throws IOException, Interru
* @param scm GitSCM object
* @param unsupportedCommand UnsupportedCommand object
*/
- public void determineSupportForJGit(GitSCM scm, @NonNull UnsupportedCommand unsupportedCommand) {
-
- }
+ public void determineSupportForJGit(GitSCM scm, @NonNull UnsupportedCommand unsupportedCommand) {}
/**
* Called before a {@link CloneCommand} is executed to allow extensions to alter its behaviour.
@@ -251,15 +294,27 @@ public void determineSupportForJGit(GitSCM scm, @NonNull UnsupportedCommand unsu
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void decorateCloneCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCloneCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
decorateCloneCommand(scm, (AbstractBuild) build, git, (BuildListener) listener, cmd);
}
}
@Deprecated
- public void decorateCloneCommand(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CloneCommand cmd) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "decorateCloneCommand", GitSCM.class, Run.class, GitClient.class, TaskListener.class, CloneCommand.class)) {
+ public void decorateCloneCommand(
+ GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CloneCommand cmd)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "decorateCloneCommand",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class,
+ CloneCommand.class)) {
decorateCloneCommand(scm, (Run) build, git, listener, cmd);
}
}
@@ -276,8 +331,8 @@ public void decorateCloneCommand(GitSCM scm, AbstractBuild, ?> build, GitClien
* @deprecated use {@link #decorateCheckoutCommand(GitSCM, Run, GitClient, TaskListener, CheckoutCommand)}
*/
@Deprecated
- public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd) throws IOException, InterruptedException, GitException {
- }
+ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd)
+ throws IOException, InterruptedException, GitException {}
/**
* Called before a {@link FetchCommand} is executed to allow extensions to alter its behaviour.
@@ -290,7 +345,8 @@ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listene
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void decorateFetchCommand(GitSCM scm, @CheckForNull Run,?> run, GitClient git, TaskListener listener, FetchCommand cmd)
+ public void decorateFetchCommand(
+ GitSCM scm, @CheckForNull Run, ?> run, GitClient git, TaskListener listener, FetchCommand cmd)
throws IOException, InterruptedException, GitException {
decorateFetchCommand(scm, git, listener, cmd);
}
@@ -306,15 +362,27 @@ public void decorateFetchCommand(GitSCM scm, @CheckForNull Run,?> run, GitClie
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void decorateMergeCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, MergeCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateMergeCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, MergeCommand cmd)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
decorateMergeCommand(scm, (AbstractBuild) build, git, (BuildListener) listener, cmd);
}
}
@Deprecated
- public void decorateMergeCommand(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, MergeCommand cmd) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "decorateMergeCommand", GitSCM.class, Run.class, GitClient.class, TaskListener.class, MergeCommand.class)) {
+ public void decorateMergeCommand(
+ GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, MergeCommand cmd)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "decorateMergeCommand",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class,
+ MergeCommand.class)) {
decorateMergeCommand(scm, (Run) build, git, listener, cmd);
}
}
@@ -330,15 +398,27 @@ public void decorateMergeCommand(GitSCM scm, AbstractBuild, ?> build, GitClien
* @throws InterruptedException when interrupted
* @throws GitException on git error
*/
- public void decorateCheckoutCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCheckoutCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
if (build instanceof AbstractBuild && listener instanceof BuildListener) {
decorateCheckoutCommand(scm, (AbstractBuild) build, git, (BuildListener) listener, cmd);
}
}
@Deprecated
- public void decorateCheckoutCommand(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
- if (Util.isOverridden(GitSCMExtension.class, getClass(), "decorateCheckoutCommand", GitSCM.class, Run.class, GitClient.class, TaskListener.class, CheckoutCommand.class)) {
+ public void decorateCheckoutCommand(
+ GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
+ if (Util.isOverridden(
+ GitSCMExtension.class,
+ getClass(),
+ "decorateCheckoutCommand",
+ GitSCM.class,
+ Run.class,
+ GitClient.class,
+ TaskListener.class,
+ CheckoutCommand.class)) {
decorateCheckoutCommand(scm, (Run) build, git, listener, cmd);
}
}
@@ -348,7 +428,7 @@ public void decorateCheckoutCommand(GitSCM scm, AbstractBuild, ?> build, GitCl
* @param scm GitSCM used as reference
* @param env environment variables to be added
*/
- public void populateEnvironmentVariables(GitSCM scm, Map env) {}
+ public void populateEnvironmentVariables(GitSCM scm, Map env) {}
/**
* Let extension declare required GitClient implementation. git-plugin will then detect conflicts, and fallback to
diff --git a/src/main/java/hudson/plugins/git/extensions/GitSCMExtensionDescriptor.java b/src/main/java/hudson/plugins/git/extensions/GitSCMExtensionDescriptor.java
index c3b7cfb4a0..33791e9252 100644
--- a/src/main/java/hudson/plugins/git/extensions/GitSCMExtensionDescriptor.java
+++ b/src/main/java/hudson/plugins/git/extensions/GitSCMExtensionDescriptor.java
@@ -13,7 +13,7 @@ public boolean isApplicable(Class extends GitSCM> type) {
return true;
}
- public static DescriptorExtensionList all() {
+ public static DescriptorExtensionList all() {
return Jenkins.get().getDescriptorList(GitSCMExtension.class);
}
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java
index 0b8d1b49a6..0e834eaef6 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java
@@ -15,8 +15,7 @@
public class AuthorInChangelog extends FakeGitSCMExtension {
@DataBoundConstructor
- public AuthorInChangelog() {
- }
+ public AuthorInChangelog() {}
/**
* {@inheritDoc}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/BuildChooserSetting.java b/src/main/java/hudson/plugins/git/extensions/impl/BuildChooserSetting.java
index cd7b59b26e..691d679f9a 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/BuildChooserSetting.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/BuildChooserSetting.java
@@ -7,9 +7,8 @@
import hudson.plugins.git.util.BuildChooser;
import hudson.plugins.git.util.BuildChooserDescriptor;
import hudson.plugins.git.util.DefaultBuildChooser;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.util.List;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* Holds {@link BuildChooser}.
@@ -25,8 +24,9 @@ public BuildChooserSetting(BuildChooser buildChooser) {
}
public BuildChooser getBuildChooser() {
- if (buildChooser==null)
+ if (buildChooser == null) {
buildChooser = new DefaultBuildChooser();
+ }
return buildChooser;
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java b/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java
index c83608b9a6..06d13c4ed7 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java
@@ -13,8 +13,7 @@
*/
public class BuildSingleRevisionOnly extends GitSCMExtension {
@DataBoundConstructor
- public BuildSingleRevisionOnly() {
- }
+ public BuildSingleRevisionOnly() {}
@Override
public boolean enableMultipleRevisionDetection() {
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java b/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java
index 06d7fc96af..eb50570a6f 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java
@@ -1,12 +1,11 @@
package hudson.plugins.git.extensions.impl;
-import org.jenkinsci.Symbol;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import hudson.Extension;
import hudson.plugins.git.ChangelogToBranchOptions;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
+import org.jenkinsci.Symbol;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* This extension activates the alternative changelog computation,
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java b/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java
index 7c3ab68049..de8198298c 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.extensions.impl;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
@@ -12,12 +13,11 @@
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import java.io.IOException;
import java.util.Objects;
+import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.CheckoutCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
-import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
-import edu.umd.cs.findbugs.annotations.NonNull;
/**
* Add options to the checkout command.
@@ -49,7 +49,9 @@ public boolean requiresWorkspaceForPolling() {
* {@inheritDoc}
*/
@Override
- public void decorateCheckoutCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCheckoutCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
cmd.timeout(timeout);
}
@@ -63,7 +65,9 @@ public void determineSupportForJGit(GitSCM scm, @NonNull UnsupportedCommand cmd)
*/
@Override
@Deprecated
- public void decorateCheckoutCommand(GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCheckoutCommand(
+ GitSCM scm, AbstractBuild, ?> build, GitClient git, BuildListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
cmd.timeout(timeout);
}
@@ -97,9 +101,7 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "CheckoutOption{" +
- "timeout=" + timeout +
- '}';
+ return "CheckoutOption{" + "timeout=" + timeout + '}';
}
@Extension
@@ -114,5 +116,4 @@ public String getDisplayName() {
return Messages.advanced_checkout_behaviours();
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java b/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java
index beac934486..32d6a449fa 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java
@@ -8,7 +8,6 @@
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import java.io.IOException;
import java.util.Objects;
-
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.FetchCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
@@ -24,8 +23,7 @@ public class CleanBeforeCheckout extends GitSCMExtension {
private boolean deleteUntrackedNestedRepositories;
@DataBoundConstructor
- public CleanBeforeCheckout() {
- }
+ public CleanBeforeCheckout() {}
public boolean isDeleteUntrackedNestedRepositories() {
return deleteUntrackedNestedRepositories;
@@ -41,7 +39,8 @@ public void setDeleteUntrackedNestedRepositories(boolean deleteUntrackedNestedRe
*/
@Override
@Deprecated
- public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd)
+ throws IOException, InterruptedException, GitException {
listener.getLogger().println("Cleaning workspace");
git.clean(deleteUntrackedNestedRepositories);
// TODO: revisit how to hand off to SubmoduleOption
@@ -78,9 +77,7 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "CleanBeforeCheckout{" +
- "deleteUntrackedNestedRepositories=" + deleteUntrackedNestedRepositories +
- '}';
+ return "CleanBeforeCheckout{" + "deleteUntrackedNestedRepositories=" + deleteUntrackedNestedRepositories + '}';
}
@Extension
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java b/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java
index aad2315994..01517cba82 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java
@@ -9,7 +9,6 @@
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import java.io.IOException;
import java.util.Objects;
-
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.kohsuke.stapler.DataBoundConstructor;
@@ -24,8 +23,7 @@ public class CleanCheckout extends GitSCMExtension {
private boolean deleteUntrackedNestedRepositories;
@DataBoundConstructor
- public CleanCheckout() {
- }
+ public CleanCheckout() {}
public boolean isDeleteUntrackedNestedRepositories() {
return deleteUntrackedNestedRepositories;
@@ -40,7 +38,8 @@ public void setDeleteUntrackedNestedRepositories(boolean deleteUntrackedNestedRe
* {@inheritDoc}
*/
@Override
- public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
listener.getLogger().println("Cleaning workspace");
git.clean(deleteUntrackedNestedRepositories);
// TODO: revisit how to hand off to SubmoduleOption
@@ -77,9 +76,7 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "CleanCheckout{" +
- "deleteUntrackedNestedRepositories=" + deleteUntrackedNestedRepositories +
- '}';
+ return "CleanCheckout{" + "deleteUntrackedNestedRepositories=" + deleteUntrackedNestedRepositories + '}';
}
@Extension
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java b/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java
index 0ff34dbe41..fd77710445 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java
@@ -1,5 +1,7 @@
package hudson.plugins.git.extensions.impl;
+import edu.umd.cs.findbugs.annotations.CheckForNull;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.Computer;
@@ -19,16 +21,14 @@
import java.util.Objects;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
+import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.CloneCommand;
import org.jenkinsci.plugins.gitclient.FetchCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
-import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* @author Kohsuke Kawaguchi
@@ -131,7 +131,9 @@ public Integer getDepth() {
* {@inheritDoc}
*/
@Override
- public void decorateCloneCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCloneCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd)
+ throws IOException, InterruptedException, GitException {
cmd.shallow(shallow);
if (shallow) {
int usedDepth = 1;
@@ -168,7 +170,7 @@ public void decorateCloneCommand(GitSCM scm, Run, ?> build, GitClient git, Tas
if (comp != null) {
env.putAll(comp.getEnvironment());
}
- for (NodeProperty nodeProperty: node.getNodeProperties()) {
+ for (NodeProperty nodeProperty : node.getNodeProperties()) {
nodeProperty.buildEnvVars(env, listener);
}
cmd.reference(env.expand(reference));
@@ -191,7 +193,8 @@ private static List getRefSpecs(RemoteConfig repo, EnvVars env) {
*/
@Override
@Deprecated // Deprecate because the super implementation is deprecated
- public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd)
+ throws IOException, InterruptedException, GitException {
cmd.shallow(shallow);
if (shallow) {
int usedDepth = 1;
@@ -225,7 +228,6 @@ public GitClientType getRequiredClient() {
return GitClientType.GITCLI;
}
-
/**
* {@inheritDoc}
*/
@@ -261,14 +263,13 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "CloneOption{" +
- "shallow=" + shallow +
- ", noTags=" + noTags +
- ", reference='" + reference + '\'' +
- ", timeout=" + timeout +
- ", depth=" + depth +
- ", honorRefspec=" + honorRefspec +
- '}';
+ return "CloneOption{" + "shallow="
+ + shallow + ", noTags="
+ + noTags + ", reference='"
+ + reference + '\'' + ", timeout="
+ + timeout + ", depth="
+ + depth + ", honorRefspec="
+ + honorRefspec + '}';
}
@Extension
@@ -282,5 +283,4 @@ public String getDisplayName() {
return Messages.Advanced_clone_behaviours();
}
}
-
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java b/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java
index a90c3d74c4..a0ddae0857 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java
@@ -13,8 +13,7 @@
public class DisableRemotePoll extends GitSCMExtension {
@DataBoundConstructor
- public DisableRemotePoll() {
- }
+ public DisableRemotePoll() {}
@Override
public boolean requiresWorkspaceForPolling() {
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java b/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java
index e122d14179..9f49b804b6 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.extensions.impl;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
@@ -10,12 +11,11 @@
import java.io.IOException;
import java.util.List;
import org.eclipse.jgit.transport.RemoteConfig;
+import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.CheckoutCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
-import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
-import edu.umd.cs.findbugs.annotations.NonNull;
/**
* git-lfs-pull after the checkout.
@@ -24,14 +24,15 @@
*/
public class GitLFSPull extends GitSCMExtension {
@DataBoundConstructor
- public GitLFSPull() {
- }
+ public GitLFSPull() {}
/**
* {@inheritDoc}
*/
@Override
- public void decorateCheckoutCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCheckoutCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
listener.getLogger().println("Enabling Git LFS pull");
List repos = scm.getParamExpandedRepos(build, listener);
// repos should never be empty, but check anyway
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java b/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java
index edcbd1f5f7..969d0b0934 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java
@@ -12,8 +12,7 @@
*/
public class IgnoreNotifyCommit extends FakeGitSCMExtension {
@DataBoundConstructor
- public IgnoreNotifyCommit() {
- }
+ public IgnoreNotifyCommit() {}
/**
* {@inheritDoc}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/LocalBranch.java b/src/main/java/hudson/plugins/git/extensions/impl/LocalBranch.java
index b099db234e..919e10d7fa 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/LocalBranch.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/LocalBranch.java
@@ -7,8 +7,8 @@
import hudson.plugins.git.extensions.FakeGitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import java.util.Objects;
-import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jenkinsci.Symbol;
+import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.DataBoundConstructor;
/**
@@ -17,7 +17,7 @@
* Configure this extension as null or as "**" to signify that
* the local branch name should be the same as the remote branch
* name sans the remote repository prefix (origin for example).
- *
+ *
* @author Kohsuke Kawaguchi
*/
public class LocalBranch extends FakeGitSCMExtension {
@@ -65,8 +65,10 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "LocalBranch{" +
- (localBranch == null || "**".equals(localBranch) ? "same-as-remote" : "localBranch='"+localBranch+"'")
+ return "LocalBranch{"
+ + (localBranch == null || "**".equals(localBranch)
+ ? "same-as-remote"
+ : "localBranch='" + localBranch + "'")
+ '}';
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java b/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java
index e725086c66..1819464ccf 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java
@@ -11,13 +11,12 @@
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import hudson.plugins.git.util.BuildData;
import hudson.util.FormValidation;
-import org.jenkinsci.plugins.gitclient.GitClient;
-import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.QueryParameter;
-
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import org.jenkinsci.plugins.gitclient.GitClient;
+import org.kohsuke.stapler.DataBoundConstructor;
+import org.kohsuke.stapler.QueryParameter;
/**
* {@link GitSCMExtension} that ignores commits with specific messages.
@@ -25,53 +24,63 @@
* @author Kanstantsin Shautsou
*/
public class MessageExclusion extends GitSCMExtension {
- /**
- * Java Pattern for matching messages to be ignored.
- */
- private String excludedMessage;
+ /**
+ * Java Pattern for matching messages to be ignored.
+ */
+ private String excludedMessage;
- private transient volatile Pattern excludedPattern;
+ private transient volatile Pattern excludedPattern;
- @DataBoundConstructor
- public MessageExclusion(String excludedMessage) { this.excludedMessage = excludedMessage; }
+ @DataBoundConstructor
+ public MessageExclusion(String excludedMessage) {
+ this.excludedMessage = excludedMessage;
+ }
- @Override
- public boolean requiresWorkspaceForPolling() { return true; }
+ @Override
+ public boolean requiresWorkspaceForPolling() {
+ return true;
+ }
- public String getExcludedMessage() { return excludedMessage; }
+ public String getExcludedMessage() {
+ return excludedMessage;
+ }
- @Override
- @SuppressFBWarnings(value="NP_BOOLEAN_RETURN_NULL", justification="null used to indicate other extensions should decide")
- @CheckForNull
- public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) throws IOException, InterruptedException, GitException {
- if (excludedPattern == null){
- excludedPattern = Pattern.compile(excludedMessage);
- }
- String msg = commit.getComment();
- if (excludedPattern.matcher(msg).matches()){
- listener.getLogger().println("Ignored commit " + commit.getId() + ": Found excluded message: " + msg);
- return true;
- }
+ @Override
+ @SuppressFBWarnings(
+ value = "NP_BOOLEAN_RETURN_NULL",
+ justification = "null used to indicate other extensions should decide")
+ @CheckForNull
+ public Boolean isRevExcluded(
+ GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData)
+ throws IOException, InterruptedException, GitException {
+ if (excludedPattern == null) {
+ excludedPattern = Pattern.compile(excludedMessage);
+ }
+ String msg = commit.getComment();
+ if (excludedPattern.matcher(msg).matches()) {
+ listener.getLogger().println("Ignored commit " + commit.getId() + ": Found excluded message: " + msg);
+ return true;
+ }
- return null;
- }
+ return null;
+ }
- @Extension
- // No @Symbol annotation because message exclusion is done using a trait in Pipeline
- public static class DescriptorImpl extends GitSCMExtensionDescriptor {
+ @Extension
+ // No @Symbol annotation because message exclusion is done using a trait in Pipeline
+ public static class DescriptorImpl extends GitSCMExtensionDescriptor {
- public FormValidation doCheckExcludedMessage(@QueryParameter String value) {
- try {
- Pattern.compile(value);
- } catch (PatternSyntaxException ex){
- return FormValidation.error(ex.getMessage());
- }
- return FormValidation.ok();
- }
+ public FormValidation doCheckExcludedMessage(@QueryParameter String value) {
+ try {
+ Pattern.compile(value);
+ } catch (PatternSyntaxException ex) {
+ return FormValidation.error(ex.getMessage());
+ }
+ return FormValidation.ok();
+ }
- @Override
- public String getDisplayName() {
- return "Polling ignores commits with certain messages";
- }
- }
+ @Override
+ public String getDisplayName() {
+ return "Polling ignores commits with certain messages";
+ }
+ }
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java b/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java
index 8ca160ca5a..adcf3e7ddc 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java
@@ -9,14 +9,13 @@
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import hudson.plugins.git.util.BuildData;
-import org.jenkinsci.plugins.gitclient.GitClient;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
+import org.jenkinsci.plugins.gitclient.GitClient;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* {@link GitSCMExtension} that ignores commits that only affects specific paths.
@@ -30,7 +29,7 @@ public class PathRestriction extends GitSCMExtension {
private final String excludedRegions;
// compiled cache
- private transient volatile List includedPatterns,excludedPatterns;
+ private transient volatile List includedPatterns, excludedPatterns;
@Override
public boolean requiresWorkspaceForPolling() {
@@ -67,14 +66,16 @@ private String[] normalize(String s) {
}
private List getIncludedPatterns() {
- if (includedPatterns==null)
+ if (includedPatterns == null) {
includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized());
+ }
return includedPatterns;
}
private List getExcludedPatterns() {
- if (excludedPatterns==null)
+ if (excludedPatterns == null) {
excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized());
+ }
return excludedPatterns;
}
@@ -93,11 +94,14 @@ private List getRegionsPatterns(String[] regions) {
}
@Override
- @SuppressFBWarnings(value="NP_BOOLEAN_RETURN_NULL", justification="null used to indicate other extensions should decide")
+ @SuppressFBWarnings(
+ value = "NP_BOOLEAN_RETURN_NULL",
+ justification = "null used to indicate other extensions should decide")
@CheckForNull
- public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) {
+ public Boolean isRevExcluded(
+ GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) {
Collection paths = commit.getAffectedPaths();
- if (paths.isEmpty()) {// nothing modified, so no need to compute any of this
+ if (paths.isEmpty()) { // nothing modified, so no need to compute any of this
return null;
}
@@ -133,14 +137,15 @@ public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, Tas
}
if (excluded.isEmpty() && !included.isEmpty() && includedPaths.isEmpty()) {
- listener.getLogger().println("Ignored commit " + commit.getCommitId()
- + ": No paths matched included region whitelist");
+ listener.getLogger()
+ .println("Ignored commit " + commit.getCommitId() + ": No paths matched included region whitelist");
return true;
} else if (includedPaths.size() == excludedPaths.size()) {
- // If every affected path is excluded, return true.
- listener.getLogger().println("Ignored commit " + commit.getCommitId()
- + ": Found only excluded paths: "
- + String.join(", ", excludedPaths));
+ // If every affected path is excluded, return true.
+ listener.getLogger()
+ .println("Ignored commit " + commit.getCommitId()
+ + ": Found only excluded paths: "
+ + String.join(", ", excludedPaths));
return true;
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java b/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java
index fc57243a00..ff22dc34cd 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java
@@ -7,12 +7,11 @@
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
-import org.jenkinsci.plugins.gitclient.GitClient;
+import java.io.IOException;
import org.jenkinsci.Symbol;
+import org.jenkinsci.plugins.gitclient.GitClient;
import org.kohsuke.stapler.DataBoundConstructor;
-import java.io.IOException;
-
/**
* Tags every build.
*
@@ -20,11 +19,11 @@
*/
public class PerBuildTag extends GitSCMExtension {
@DataBoundConstructor
- public PerBuildTag() {
- }
+ public PerBuildTag() {}
@Override
- public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
int buildNumber = build.getNumber();
String buildnumber = "jenkins-" + build.getParent().getName().replace(" ", "_") + "-" + buildNumber;
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java b/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java
index 859c7dce14..7f531b31b1 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java
@@ -1,11 +1,16 @@
package hudson.plugins.git.extensions.impl;
+import static hudson.model.Result.FAILURE;
+import static org.eclipse.jgit.lib.Constants.HEAD;
+
import hudson.AbortException;
import hudson.Extension;
+import hudson.model.Run;
+import hudson.model.TaskListener;
+import hudson.plugins.git.Branch;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.Revision;
-import hudson.plugins.git.Branch;
import hudson.plugins.git.UserMergeOptions;
import hudson.plugins.git.extensions.GitClientType;
import hudson.plugins.git.extensions.GitSCMExtension;
@@ -14,6 +19,9 @@
import hudson.plugins.git.util.BuildData;
import hudson.plugins.git.util.GitUtils;
import hudson.plugins.git.util.MergeRecord;
+import java.io.IOException;
+import java.util.List;
+import java.util.Objects;
import org.eclipse.jgit.lib.ObjectId;
import org.jenkinsci.plugins.gitclient.CheckoutCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
@@ -21,15 +29,6 @@
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.DataBoundConstructor;
-import java.io.IOException;
-import java.util.List;
-import java.util.Objects;
-
-import static hudson.model.Result.FAILURE;
-import hudson.model.Run;
-import hudson.model.TaskListener;
-import static org.eclipse.jgit.lib.Constants.HEAD;
-
/**
* Speculatively merge the selected commit with another branch before the build to answer the "what happens
* if I were to integrate this feature branch back to the master?" question.
@@ -44,7 +43,9 @@ public class PreBuildMerge extends GitSCMExtension {
@DataBoundConstructor
public PreBuildMerge(UserMergeOptions options) {
- if (options==null) throw new IllegalStateException();
+ if (options == null) {
+ throw new IllegalStateException();
+ }
this.options = options;
}
@@ -54,41 +55,54 @@ public UserMergeOptions getOptions() {
}
@Override
- public Revision decorateRevisionToBuild(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, Revision marked, Revision rev) throws IOException, InterruptedException {
+ public Revision decorateRevisionToBuild(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, Revision marked, Revision rev)
+ throws IOException, InterruptedException {
String remoteBranchRef = GitSCM.getParameterString(options.getRef(), build.getEnvironment(listener));
// if the branch we are merging is already at the commit being built, the entire merge becomes no-op
// so there's nothing to do
- if (rev.containsBranchName(remoteBranchRef))
+ if (rev.containsBranchName(remoteBranchRef)) {
return rev;
+ }
// Only merge if there's a branch to merge that isn't us..
- listener.getLogger().println("Merging " + rev + " to " + remoteBranchRef + ", " + GitSCM.getParameterString(options.toString(), build.getEnvironment(listener)));
+ listener.getLogger()
+ .println("Merging " + rev + " to " + remoteBranchRef + ", "
+ + GitSCM.getParameterString(options.toString(), build.getEnvironment(listener)));
// checkout origin/blah
ObjectId target = git.revParse(remoteBranchRef);
String paramLocalBranch = scm.getParamLocalBranch(build, listener);
- CheckoutCommand checkoutCommand = git.checkout().branch(paramLocalBranch).ref(remoteBranchRef).deleteBranchIfExist(true);
- for (GitSCMExtension ext : scm.getExtensions())
+ CheckoutCommand checkoutCommand =
+ git.checkout().branch(paramLocalBranch).ref(remoteBranchRef).deleteBranchIfExist(true);
+ for (GitSCMExtension ext : scm.getExtensions()) {
ext.decorateCheckoutCommand(scm, build, git, listener, checkoutCommand);
+ }
checkoutCommand.execute();
try {
MergeCommand cmd = git.merge().setRevisionToMerge(rev.getSha1());
- for (GitSCMExtension ext : scm.getExtensions())
+ for (GitSCMExtension ext : scm.getExtensions()) {
ext.decorateMergeCommand(scm, build, git, listener, cmd);
+ }
cmd.execute();
} catch (GitException ex) {
// merge conflict. First, avoid leaving any conflict markers in the working tree
// by checking out some known clean state. We don't really mind what commit this is,
// since the next build is going to pick its own commit to build, but 'rev' is as good any.
- checkoutCommand = git.checkout().branch(paramLocalBranch).ref(rev.getSha1String()).deleteBranchIfExist(true);
- for (GitSCMExtension ext : scm.getExtensions())
+ checkoutCommand = git.checkout()
+ .branch(paramLocalBranch)
+ .ref(rev.getSha1String())
+ .deleteBranchIfExist(true);
+ for (GitSCMExtension ext : scm.getExtensions()) {
ext.decorateCheckoutCommand(scm, build, git, listener, checkoutCommand);
+ }
checkoutCommand.execute();
// record the fact that we've tried building 'rev' and it failed, or else
- // BuildChooser in future builds will pick up this same 'rev' again and we'll see the exact same merge failure
+ // BuildChooser in future builds will pick up this same 'rev' again and we'll see the exact same merge
+ // failure
// all over again.
// Track whether we're trying to add a duplicate BuildData, now that it's been updated with
@@ -96,14 +110,14 @@ public Revision decorateRevisionToBuild(GitSCM scm, Run, ?> build, GitClient g
BuildData buildData = scm.copyBuildData(build);
boolean buildDataAlreadyPresent = false;
List actions = build.getActions(BuildData.class);
- for (BuildData d: actions) {
+ for (BuildData d : actions) {
if (d.similarTo(buildData)) {
buildDataAlreadyPresent = true;
break;
}
}
if (!actions.isEmpty()) {
- buildData.setIndex(actions.size()+1);
+ buildData.setIndex(actions.size() + 1);
}
// If the BuildData is not already attached to this build, add it to the build and mark that
@@ -113,19 +127,22 @@ public Revision decorateRevisionToBuild(GitSCM scm, Run, ?> build, GitClient g
build.addAction(buildData);
}
- buildData.saveBuild(new Build(marked,rev, build.getNumber(), FAILURE));
- throw new AbortException("Branch not suitable for integration as it does not merge cleanly: " + ex.getMessage());
+ buildData.saveBuild(new Build(marked, rev, build.getNumber(), FAILURE));
+ throw new AbortException(
+ "Branch not suitable for integration as it does not merge cleanly: " + ex.getMessage());
}
- build.addAction(new MergeRecord(remoteBranchRef,target.getName()));
+ build.addAction(new MergeRecord(remoteBranchRef, target.getName()));
- Revision mergeRevision = new GitUtils(listener,git).getRevisionForSHA1(git.revParse(HEAD));
+ Revision mergeRevision = new GitUtils(listener, git).getRevisionForSHA1(git.revParse(HEAD));
mergeRevision.getBranches().add(new Branch(remoteBranchRef, target));
return mergeRevision;
}
@Override
- public void decorateMergeCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, MergeCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateMergeCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, MergeCommand cmd)
+ throws IOException, InterruptedException, GitException {
if (options.getMergeStrategy() != null) {
cmd.setStrategy(options.getMergeStrategy());
}
@@ -167,9 +184,7 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "PreBuildMerge{" +
- "options=" + options +
- '}';
+ return "PreBuildMerge{" + "options=" + options + '}';
}
@Extension
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleBranch.java b/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleBranch.java
index fccec00ddb..b087d56add 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleBranch.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleBranch.java
@@ -7,9 +7,9 @@
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import java.io.IOException;
+import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.FetchCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
-import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
/**
@@ -20,15 +20,15 @@
*/
public class PruneStaleBranch extends GitSCMExtension {
@DataBoundConstructor
- public PruneStaleBranch() {
- }
+ public PruneStaleBranch() {}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
- public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd)
+ throws IOException, InterruptedException, GitException {
listener.getLogger().println("Pruning obsolete local branches");
cmd.prune(true);
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java b/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java
index 70815d5dbe..e46f77319c 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java
@@ -32,14 +32,13 @@
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
-import net.sf.json.JSONObject;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.Map.Entry;
+import java.util.Objects;
+import net.sf.json.JSONObject;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
@@ -86,11 +85,9 @@ public boolean getPruneTags() {
* {@inheritDoc}
*/
@Override
- public void decorateFetchCommand(GitSCM scm,
- @CheckForNull Run, ?> run,
- GitClient git,
- TaskListener listener,
- FetchCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateFetchCommand(
+ GitSCM scm, @CheckForNull Run, ?> run, GitClient git, TaskListener listener, FetchCommand cmd)
+ throws IOException, InterruptedException, GitException {
if (!pruneTags) {
return;
@@ -116,7 +113,8 @@ public void decorateFetchCommand(GitSCM scm,
remoteTagName = remoteTagName.substring(TAG_REF.length());
}
ObjectId remoteTagId = ref.getValue();
- if (localTags.containsKey(remoteTagName) && localTags.get(remoteTagName).equals(remoteTagId)) {
+ if (localTags.containsKey(remoteTagName)
+ && localTags.get(remoteTagName).equals(remoteTagId)) {
localTags.remove(remoteTagName);
}
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/RelativeTargetDirectory.java b/src/main/java/hudson/plugins/git/extensions/impl/RelativeTargetDirectory.java
index 2f93739a34..e6d10e5fe5 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/RelativeTargetDirectory.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/RelativeTargetDirectory.java
@@ -10,9 +10,8 @@
import hudson.plugins.git.Messages;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.io.IOException;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* Instead of checking out to the top of the workspace, check out somewhere else.
@@ -34,7 +33,9 @@ public String getRelativeTargetDir() {
}
@Override
- public FilePath getWorkingDirectory(GitSCM scm, Job, ?> context, FilePath workspace, EnvVars environment, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public FilePath getWorkingDirectory(
+ GitSCM scm, Job, ?> context, FilePath workspace, EnvVars environment, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
if (relativeTargetDir == null || relativeTargetDir.length() == 0 || relativeTargetDir.equals(".")) {
return workspace;
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java
index c07399ca21..6dd261eab9 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java
@@ -6,19 +6,21 @@
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
+import java.io.Serializable;
+import java.util.Objects;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.DataBoundConstructor;
-import java.io.Serializable;
-import java.util.Objects;
-
public class SparseCheckoutPath extends AbstractDescribableImpl implements Serializable {
private static final long serialVersionUID = -6177158367915899356L;
- @SuppressFBWarnings(value="SE_TRANSIENT_FIELD_NOT_RESTORED", justification="Default value is OK in deserialization")
- public static final transient SparseCheckoutPathToPath SPARSE_CHECKOUT_PATH_TO_PATH = new SparseCheckoutPathToPath();
+ @SuppressFBWarnings(
+ value = "SE_TRANSIENT_FIELD_NOT_RESTORED",
+ justification = "Default value is OK in deserialization")
+ public static final transient SparseCheckoutPathToPath SPARSE_CHECKOUT_PATH_TO_PATH =
+ new SparseCheckoutPathToPath();
private final String path;
@@ -57,19 +59,22 @@ public String toString() {
}
private static class SparseCheckoutPathToPath implements Function, Serializable {
+ @Override
public String apply(@NonNull SparseCheckoutPath sparseCheckoutPath) {
return sparseCheckoutPath.getPath();
}
}
- public Descriptor getDescriptor()
- {
+ @Override
+ public Descriptor getDescriptor() {
return Jenkins.get().getDescriptor(getClass());
}
@Extension
public static class DescriptorImpl extends Descriptor {
@Override
- public String getDisplayName() { return "Path"; }
+ public String getDisplayName() {
+ return "Path";
+ }
}
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java
index 0a8796f1d7..e7170961af 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java
@@ -1,6 +1,7 @@
package hudson.plugins.git.extensions.impl;
import com.google.common.collect.Lists;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
@@ -8,18 +9,16 @@
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
import org.jenkinsci.plugins.gitclient.CheckoutCommand;
import org.jenkinsci.plugins.gitclient.CloneCommand;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.DataBoundConstructor;
-import edu.umd.cs.findbugs.annotations.NonNull;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
public class SparseCheckoutPaths extends GitSCMExtension {
private final List sparseCheckoutPaths;
@@ -35,14 +34,18 @@ public List getSparseCheckoutPaths() {
}
@Override
- public void decorateCloneCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd) throws IOException, InterruptedException, GitException {
- if (! sparseCheckoutPaths.isEmpty()) {
+ public void decorateCloneCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CloneCommand cmd)
+ throws IOException, InterruptedException, GitException {
+ if (!sparseCheckoutPaths.isEmpty()) {
listener.getLogger().println("Using no checkout clone with sparse checkout.");
}
}
@Override
- public void decorateCheckoutCommand(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd) throws IOException, InterruptedException, GitException {
+ public void decorateCheckoutCommand(
+ GitSCM scm, Run, ?> build, GitClient git, TaskListener listener, CheckoutCommand cmd)
+ throws IOException, InterruptedException, GitException {
cmd.sparseCheckoutPaths(Lists.transform(sparseCheckoutPaths, SparseCheckoutPath.SPARSE_CHECKOUT_PATH_TO_PATH));
}
@@ -67,11 +70,11 @@ public boolean equals(Object o) {
if (this == o) {
return true;
}
-
+
if (o == null || getClass() != o.getClass()) {
return false;
}
-
+
SparseCheckoutPaths that = (SparseCheckoutPaths) o;
return Objects.equals(getSparseCheckoutPaths(), that.getSparseCheckoutPaths());
}
@@ -83,14 +86,12 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(getSparseCheckoutPaths());
}
-
+
/**
* {@inheritDoc}
*/
@Override
public String toString() {
- return "SparseCheckoutPaths{" +
- "sparseCheckoutPaths=" + sparseCheckoutPaths +
- '}';
+ return "SparseCheckoutPaths{" + "sparseCheckoutPaths=" + sparseCheckoutPaths + '}';
}
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java b/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java
index 94ecfe6878..7b34bf28fa 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java
@@ -1,5 +1,6 @@
package hudson.plugins.git.extensions.impl;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Run;
import hudson.model.TaskListener;
@@ -11,14 +12,13 @@
import hudson.plugins.git.util.BuildData;
import java.io.IOException;
import java.util.Objects;
+import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.SubmoduleUpdateCommand;
import org.jenkinsci.plugins.gitclient.UnsupportedCommand;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
-import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
-import edu.umd.cs.findbugs.annotations.NonNull;
/**
* Further tweak the behaviour of git-submodule.
@@ -45,10 +45,12 @@ public class SubmoduleOption extends GitSCMExtension {
private boolean trackingSubmodules;
/** Use --reference flag on submodule update command - requires git>=1.6.4 */
private String reference;
+
private boolean parentCredentials;
private Integer timeout;
/** Use --depth flag on submodule update command - requires git>=1.8.4 */
private boolean shallow;
+
private Integer depth;
private Integer threads;
@@ -58,7 +60,13 @@ public SubmoduleOption() {
}
@Whitelisted
- public SubmoduleOption(boolean disableSubmodules, boolean recursiveSubmodules, boolean trackingSubmodules, String reference, Integer timeout, boolean parentCredentials) {
+ public SubmoduleOption(
+ boolean disableSubmodules,
+ boolean recursiveSubmodules,
+ boolean trackingSubmodules,
+ String reference,
+ Integer timeout,
+ boolean parentCredentials) {
this.disableSubmodules = disableSubmodules;
this.recursiveSubmodules = recursiveSubmodules;
this.trackingSubmodules = trackingSubmodules;
@@ -171,7 +179,8 @@ public void onClean(GitSCM scm, GitClient git) throws IOException, InterruptedEx
* {@inheritDoc}
*/
@Override
- public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void onCheckoutCompleted(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
BuildData revToBuild = scm.getBuildData(build);
try {
@@ -249,7 +258,16 @@ public boolean equals(Object o) {
*/
@Override
public int hashCode() {
- return Objects.hash(disableSubmodules, recursiveSubmodules, trackingSubmodules, parentCredentials, reference, timeout, shallow, depth, threads);
+ return Objects.hash(
+ disableSubmodules,
+ recursiveSubmodules,
+ trackingSubmodules,
+ parentCredentials,
+ reference,
+ timeout,
+ shallow,
+ depth,
+ threads);
}
/**
@@ -257,17 +275,16 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "SubmoduleOption{" +
- "disableSubmodules=" + disableSubmodules +
- ", recursiveSubmodules=" + recursiveSubmodules +
- ", trackingSubmodules=" + trackingSubmodules +
- ", reference='" + reference + '\'' +
- ", parentCredentials=" + parentCredentials +
- ", timeout=" + timeout +
- ", shallow=" + shallow +
- ", depth=" + depth +
- ", threads=" + threads +
- '}';
+ return "SubmoduleOption{" + "disableSubmodules="
+ + disableSubmodules + ", recursiveSubmodules="
+ + recursiveSubmodules + ", trackingSubmodules="
+ + trackingSubmodules + ", reference='"
+ + reference + '\'' + ", parentCredentials="
+ + parentCredentials + ", timeout="
+ + timeout + ", shallow="
+ + shallow + ", depth="
+ + depth + ", threads="
+ + threads + '}';
}
@Extension
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java b/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java
index d4c36965cf..2b77a835ca 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java
@@ -3,19 +3,18 @@
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
+import hudson.Util;
import hudson.model.TaskListener;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.GitSCMExtensionDescriptor;
import hudson.plugins.git.util.BuildData;
-import hudson.Util;
-import org.jenkinsci.plugins.gitclient.GitClient;
-import org.kohsuke.stapler.DataBoundConstructor;
-
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
+import org.jenkinsci.plugins.gitclient.GitClient;
+import org.kohsuke.stapler.DataBoundConstructor;
/**
* {@link GitSCMExtension} that ignores commits that are made by specific users.
@@ -56,13 +55,17 @@ public Set getExcludedUsersNormalized() {
}
@Override
- @SuppressFBWarnings(value="NP_BOOLEAN_RETURN_NULL", justification="null used to indicate other extensions should decide")
+ @SuppressFBWarnings(
+ value = "NP_BOOLEAN_RETURN_NULL",
+ justification = "null used to indicate other extensions should decide")
@CheckForNull
- public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) {
+ public Boolean isRevExcluded(
+ GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) {
String author = commit.getAuthorName();
if (getExcludedUsersNormalized().contains(author)) {
// If the author is an excluded user, don't count this entry as a change
- listener.getLogger().println("Ignored commit " + commit.getCommitId() + ": Found excluded author: " + author);
+ listener.getLogger()
+ .println("Ignored commit " + commit.getCommitId() + ": Found excluded author: " + author);
return true;
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java b/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java
index cbad3a0988..e418db9c4f 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java
@@ -1,5 +1,7 @@
package hudson.plugins.git.extensions.impl;
+import static hudson.Util.fixEmptyAndTrim;
+
import hudson.Extension;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitSCM;
@@ -11,8 +13,6 @@
import org.jenkinsci.plugins.gitclient.GitClient;
import org.kohsuke.stapler.DataBoundConstructor;
-import static hudson.Util.fixEmptyAndTrim;
-
/**
* {@link GitSCMExtension} that sets a different name and/or e-mail address for commits.
*
@@ -43,11 +43,11 @@ public String getEmail() {
@Override
public void populateEnvironmentVariables(GitSCM scm, Map env) {
// for backward compatibility, in case the user's shell script invokes Git inside
- if (name!=null) {
+ if (name != null) {
env.put("GIT_COMMITTER_NAME", name);
env.put("GIT_AUTHOR_NAME", name);
}
- if (email!=null) {
+ if (email != null) {
env.put("GIT_COMMITTER_EMAIL", email);
env.put("GIT_AUTHOR_EMAIL", email);
}
@@ -67,8 +67,7 @@ public boolean equals(Object o) {
UserIdentity that = (UserIdentity) o;
- return Objects.equals(name, that.name)
- && Objects.equals(email, that.email);
+ return Objects.equals(name, that.name) && Objects.equals(email, that.email);
}
/**
@@ -84,10 +83,7 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "UserIdentity{" +
- "name='" + name + '\'' +
- ", email='" + email + '\'' +
- '}';
+ return "UserIdentity{" + "name='" + name + '\'' + ", email='" + email + '\'' + '}';
}
/**
@@ -98,13 +94,17 @@ public GitClient decorate(GitSCM scm, GitClient git) throws IOException, Interru
GitSCM.DescriptorImpl d = scm.getDescriptor();
String n = d.getGlobalConfigName();
- if (name!=null) n = name;
+ if (name != null) {
+ n = name;
+ }
String e = d.getGlobalConfigEmail();
- if (email!=null) e = email;
+ if (email != null) {
+ e = email;
+ }
- git.setAuthor(n,e);
- git.setCommitter(n,e);
+ git.setAuthor(n, e);
+ git.setCommitter(n, e);
return git;
}
diff --git a/src/main/java/hudson/plugins/git/extensions/impl/WipeWorkspace.java b/src/main/java/hudson/plugins/git/extensions/impl/WipeWorkspace.java
index 45c9c415ac..aac7d0ae55 100644
--- a/src/main/java/hudson/plugins/git/extensions/impl/WipeWorkspace.java
+++ b/src/main/java/hudson/plugins/git/extensions/impl/WipeWorkspace.java
@@ -18,14 +18,14 @@
*/
public class WipeWorkspace extends GitSCMExtension {
@DataBoundConstructor
- public WipeWorkspace() {
- }
+ public WipeWorkspace() {}
/**
* {@inheritDoc}
*/
@Override
- public void beforeCheckout(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener) throws IOException, InterruptedException, GitException {
+ public void beforeCheckout(GitSCM scm, Run, ?> build, GitClient git, TaskListener listener)
+ throws IOException, InterruptedException, GitException {
listener.getLogger().println("Wiping out workspace first.");
git.getWorkTree().deleteContents();
}
diff --git a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java
index 264710ff92..185100c0fc 100644
--- a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java
+++ b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java
@@ -1,12 +1,11 @@
package hudson.plugins.git.opt;
+import java.io.Serializable;
import org.eclipse.jgit.transport.RemoteConfig;
import org.jenkinsci.plugins.gitclient.MergeCommand;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
-import java.io.Serializable;
-
/**
* Git SCM can optionally perform a merge with another branch (possibly another repository.)
*
@@ -52,9 +51,11 @@ public void setMergeTarget(String mergeTarget) {
@Exported
public MergeCommand.Strategy getMergeStrategy() {
- for (MergeCommand.Strategy strategy: MergeCommand.Strategy.values())
- if (strategy.toString().equals(mergeStrategy))
+ for (MergeCommand.Strategy strategy : MergeCommand.Strategy.values()) {
+ if (strategy.toString().equals(mergeStrategy)) {
return strategy;
+ }
+ }
return MergeCommand.Strategy.DEFAULT;
}
@@ -64,14 +65,16 @@ public void setMergeStrategy(MergeCommand.Strategy mergeStrategy) {
@Exported
public MergeCommand.GitPluginFastForwardMode getFastForwardMode() {
- for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values())
- if (ffMode == fastForwardMode)
+ for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values()) {
+ if (ffMode == fastForwardMode) {
return ffMode;
+ }
+ }
return MergeCommand.GitPluginFastForwardMode.FF;
}
public void setFastForwardMode(MergeCommand.GitPluginFastForwardMode fastForwardMode) {
- this.fastForwardMode = fastForwardMode;
+ this.fastForwardMode = fastForwardMode;
}
@Exported
diff --git a/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java b/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java
index e3af18e6e0..4745764d97 100644
--- a/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java
+++ b/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java
@@ -1,59 +1,62 @@
package hudson.plugins.git.util;
+import com.google.common.base.Throwables;
+import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.TaskListener;
import hudson.plugins.git.GitException;
import hudson.plugins.git.Messages;
import hudson.plugins.git.Revision;
import hudson.remoting.VirtualChannel;
-
import java.io.IOException;
import java.io.UncheckedIOException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
-
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.jenkinsci.plugins.gitclient.GitClient;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
import org.kohsuke.stapler.DataBoundConstructor;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import com.google.common.base.Throwables;
-
public class AncestryBuildChooser extends DefaultBuildChooser {
private final Integer maximumAgeInDays;
private final String ancestorCommitSha1;
-
+
@DataBoundConstructor
public AncestryBuildChooser(Integer maximumAgeInDays, String ancestorCommitSha1) {
this.maximumAgeInDays = maximumAgeInDays;
this.ancestorCommitSha1 = ancestorCommitSha1;
}
-
+
public Integer getMaximumAgeInDays() {
return maximumAgeInDays;
}
-
+
public String getAncestorCommitSha1() {
return ancestorCommitSha1;
}
@Override
- public Collection getCandidateRevisions(boolean isPollCall, String branchSpec,
- GitClient git, final TaskListener listener, BuildData data, BuildChooserContext context)
- throws GitException, IOException, InterruptedException {
-
- final Collection candidates = super.getCandidateRevisions(isPollCall, branchSpec, git, listener, data, context);
-
+ public Collection getCandidateRevisions(
+ boolean isPollCall,
+ String branchSpec,
+ GitClient git,
+ final TaskListener listener,
+ BuildData data,
+ BuildChooserContext context)
+ throws GitException, IOException, InterruptedException {
+
+ final Collection candidates =
+ super.getCandidateRevisions(isPollCall, branchSpec, git, listener, data, context);
+
// filter candidates based on branch age and ancestry
return git.withRepository((Repository repository, VirtualChannel channel) -> {
try (RevWalk walk = new RevWalk(repository)) {
@@ -93,63 +96,65 @@ public Collection getCandidateRevisions(boolean isPollCall, String bra
.filter(IOException.class::isInstance)
.map(IOException.class::cast)
.iterator();
- if (ioeIter.hasNext())
+ if (ioeIter.hasNext()) {
throw ioeIter.next();
- else
+ } else {
throw Throwables.propagate(e);
+ }
}
return filteredCandidates;
}
});
}
-
+
private static class CommitAgeFilter implements Predicate {
-
+
private LocalDateTime oldestAllowableCommitDate = null;
-
+
public CommitAgeFilter(Integer oldestAllowableAgeInDays) {
if (oldestAllowableAgeInDays != null && oldestAllowableAgeInDays >= 0) {
this.oldestAllowableCommitDate = LocalDate.now().atStartOfDay().minusDays(oldestAllowableAgeInDays);
}
}
-
+
@Override
public boolean test(@NonNull RevCommit rev) {
- return LocalDateTime.ofInstant(rev.getCommitterIdent().getWhen().toInstant(), ZoneId.systemDefault()).isAfter(this.oldestAllowableCommitDate);
+ return LocalDateTime.ofInstant(rev.getCommitterIdent().getWhen().toInstant(), ZoneId.systemDefault())
+ .isAfter(this.oldestAllowableCommitDate);
}
-
+
public boolean isEnabled() {
return oldestAllowableCommitDate != null;
}
}
-
+
private static class AncestryFilter implements Predicate {
-
+
RevWalk revwalk;
RevCommit ancestor;
-
+
public AncestryFilter(RevWalk revwalk, RevCommit ancestor) {
this.revwalk = revwalk;
this.ancestor = ancestor;
}
-
+
@Override
public boolean test(RevCommit rev) {
try {
return revwalk.isMergedInto(ancestor, rev);
- // wrap IOException so it can propagate
+ // wrap IOException so it can propagate
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
-
+
public boolean isEnabled() {
return (revwalk != null) && (ancestor != null);
}
}
-
+
@Extension
public static final class DescriptorImpl extends BuildChooserDescriptor {
@Override
@@ -157,6 +162,6 @@ public String getDisplayName() {
return Messages.BuildChooser_Ancestry();
}
}
-
+
private static final long serialVersionUID = 1L;
}
diff --git a/src/main/java/hudson/plugins/git/util/Build.java b/src/main/java/hudson/plugins/git/util/Build.java
index f77866969b..239ba8a9c8 100644
--- a/src/main/java/hudson/plugins/git/util/Build.java
+++ b/src/main/java/hudson/plugins/git/util/Build.java
@@ -3,13 +3,12 @@
import hudson.model.Result;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.Revision;
-import org.eclipse.jgit.lib.ObjectId;
-import org.kohsuke.stapler.export.Exported;
-import org.kohsuke.stapler.export.ExportedBean;
-
import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;
+import org.eclipse.jgit.lib.ObjectId;
+import org.kohsuke.stapler.export.Exported;
+import org.kohsuke.stapler.export.ExportedBean;
/**
* Remembers which build built which {@link Revision}.
@@ -48,8 +47,8 @@ public class Build implements Serializable, Cloneable {
*/
public Revision revision;
- public int hudsonBuildNumber;
- public Result hudsonBuildResult;
+ public int hudsonBuildNumber;
+ public Result hudsonBuildResult;
// TODO: We don't currently store the result correctly.
@@ -61,7 +60,7 @@ public Build(Revision marked, Revision revision, int buildNumber, Result result)
}
public Build(Revision revision, int buildNumber, Result result) {
- this(revision,revision,buildNumber,result);
+ this(revision, revision, buildNumber, result);
}
public ObjectId getSHA1() {
@@ -118,15 +117,16 @@ public Build clone() {
Build clone;
try {
clone = (Build) super.clone();
- }
- catch (CloneNotSupportedException e) {
+ } catch (CloneNotSupportedException e) {
throw new RuntimeException("Error cloning Build", e);
}
- if (revision != null)
+ if (revision != null) {
clone.revision = revision.clone();
- if (marked != null)
+ }
+ if (marked != null) {
clone.marked = marked.clone();
+ }
return clone;
}
@@ -135,8 +135,9 @@ public boolean isFor(String sha1) {
}
public Object readResolve() throws IOException {
- if (marked==null) // this field was introduced later than 'revision'
+ if (marked == null) { // this field was introduced later than 'revision'
marked = revision;
+ }
return this;
}
}
diff --git a/src/main/java/hudson/plugins/git/util/BuildChooser.java b/src/main/java/hudson/plugins/git/util/BuildChooser.java
index d574f3d775..5a502ca35e 100644
--- a/src/main/java/hudson/plugins/git/util/BuildChooser.java
+++ b/src/main/java/hudson/plugins/git/util/BuildChooser.java
@@ -7,19 +7,18 @@
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
-import jenkins.model.Jenkins;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.Revision;
-import org.jenkinsci.plugins.gitclient.GitClient;
-
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import jenkins.model.Jenkins;
+import org.jenkinsci.plugins.gitclient.GitClient;
/**
* Interface defining an API to choose which revisions ought to be
@@ -79,10 +78,14 @@ public final String getDisplayName() {
* @throws GitException on git error
* @throws InterruptedException when interrupted
*/
- public Collection getCandidateRevisions(boolean isPollCall, @CheckForNull String singleBranch,
- @NonNull GitClient git, @NonNull TaskListener listener,
- @NonNull BuildData buildData, @NonNull BuildChooserContext context)
- throws GitException, IOException, InterruptedException {
+ public Collection getCandidateRevisions(
+ boolean isPollCall,
+ @CheckForNull String singleBranch,
+ @NonNull GitClient git,
+ @NonNull TaskListener listener,
+ @NonNull BuildData buildData,
+ @NonNull BuildChooserContext context)
+ throws GitException, IOException, InterruptedException {
// fallback to the previous signature
@SuppressWarnings("deprecation")
hudson.plugins.git.IGitAPI iGit = (hudson.plugins.git.IGitAPI) git;
@@ -118,13 +121,18 @@ public Collection getCandidateRevisions(boolean isPollCall, @CheckForN
* @throws InterruptedException when interrupted
*/
@Deprecated
- public Collection getCandidateRevisions(boolean isPollCall, String singleBranch,
- hudson.plugins.git.IGitAPI git, TaskListener listener, BuildData buildData, BuildChooserContext context) throws GitException, IOException, InterruptedException {
+ public Collection getCandidateRevisions(
+ boolean isPollCall,
+ String singleBranch,
+ hudson.plugins.git.IGitAPI git,
+ TaskListener listener,
+ BuildData buildData,
+ BuildChooserContext context)
+ throws GitException, IOException, InterruptedException {
// fallback to the previous signature
- return getCandidateRevisions(isPollCall,singleBranch,git,listener,buildData);
+ return getCandidateRevisions(isPollCall, singleBranch, git, listener, buildData);
}
-
/**
* @deprecated as of 1.1.17
* Use and override {@link #getCandidateRevisions(boolean, String, hudson.plugins.git.IGitAPI, TaskListener, BuildData, BuildChooserContext)}
@@ -143,8 +151,13 @@ public Collection