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 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 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 getCandidateRevisions(boolean isPollCall, String sin * @throws GitException on git error */ @Deprecated - public Collection getCandidateRevisions(boolean isPollCall, String singleBranch, - hudson.plugins.git.IGitAPI git, TaskListener listener, BuildData buildData) throws GitException, IOException { + public Collection getCandidateRevisions( + boolean isPollCall, + String singleBranch, + hudson.plugins.git.IGitAPI git, + TaskListener listener, + BuildData buildData) + throws GitException, IOException { throw new UnsupportedOperationException("getCandidateRevisions method must be overridden"); } @@ -191,7 +204,9 @@ public Build prevBuildForChangelog(String branch, @Nullable BuildData buildData, * @throws InterruptedException when interrupted * @return candidate revision. Can be an empty set to indicate that there's nothing to build. */ - public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitClient git, BuildChooserContext context) throws IOException,InterruptedException { + public Build prevBuildForChangelog( + String branch, @Nullable BuildData data, GitClient git, BuildChooserContext context) + throws IOException, InterruptedException { @SuppressWarnings("deprecation") hudson.plugins.git.IGitAPI iGit = (hudson.plugins.git.IGitAPI) git; return prevBuildForChangelog(branch, data, iGit, context); @@ -223,25 +238,27 @@ public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitC * @throws InterruptedException if interrupted */ @Deprecated - public Build prevBuildForChangelog(String branch, @Nullable BuildData data, hudson.plugins.git.IGitAPI git, BuildChooserContext context) throws IOException,InterruptedException { - return prevBuildForChangelog(branch,data,git); + public Build prevBuildForChangelog( + String branch, @Nullable BuildData data, hudson.plugins.git.IGitAPI git, BuildChooserContext context) + throws IOException, InterruptedException { + return prevBuildForChangelog(branch, data, git); } /** * Returns build chooser descriptor. * @return build chooser descriptor */ + @Override public BuildChooserDescriptor getDescriptor() { - return (BuildChooserDescriptor)Jenkins.get().getDescriptorOrDie(getClass()); + return (BuildChooserDescriptor) Jenkins.get().getDescriptorOrDie(getClass()); } /** * All the registered build choosers. * @return all registered build choosers */ - public static DescriptorExtensionList all() { - return Jenkins.get() - .getDescriptorList(BuildChooser.class); + public static DescriptorExtensionList all() { + return Jenkins.get().getDescriptorList(BuildChooser.class); } /** @@ -252,9 +269,10 @@ public static DescriptorExtensionList all() */ public static List allApplicableTo(Item item) { List result = new ArrayList<>(); - for (BuildChooserDescriptor d: all()) { - if (d.isApplicable(item.getClass())) + for (BuildChooserDescriptor d : all()) { + if (d.isApplicable(item.getClass())) { result.add(d); + } } return result; } @@ -276,7 +294,8 @@ public static List allApplicableTo(Item item) { * @throws IOException on input or output error * @throws InterruptedException when interrupted */ - public void prepareWorkingTree(GitClient git, TaskListener listener, BuildChooserContext context) throws IOException,InterruptedException { + public void prepareWorkingTree(GitClient git, TaskListener listener, BuildChooserContext context) + throws IOException, InterruptedException { // Nop } } diff --git a/src/main/java/hudson/plugins/git/util/BuildChooserContext.java b/src/main/java/hudson/plugins/git/util/BuildChooserContext.java index 43dc6ae574..e8ee6ab929 100644 --- a/src/main/java/hudson/plugins/git/util/BuildChooserContext.java +++ b/src/main/java/hudson/plugins/git/util/BuildChooserContext.java @@ -5,7 +5,6 @@ import hudson.model.Run; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; - import java.io.IOException; import java.io.Serializable; @@ -19,14 +18,15 @@ * @author Kohsuke Kawaguchi */ public interface BuildChooserContext { - T actOnBuild(ContextCallable,T> callable) throws IOException,InterruptedException; - T actOnProject(ContextCallable,T> callable) throws IOException,InterruptedException; + T actOnBuild(ContextCallable, T> callable) throws IOException, InterruptedException; + + T actOnProject(ContextCallable, T> callable) throws IOException, InterruptedException; - Run getBuild(); + Run getBuild(); EnvVars getEnvironment(); - public static interface ContextCallable extends Serializable { + public static interface ContextCallable extends Serializable { /** * Performs the computational task on the node where the data is located. * diff --git a/src/main/java/hudson/plugins/git/util/BuildChooserDescriptor.java b/src/main/java/hudson/plugins/git/util/BuildChooserDescriptor.java index ad52c1e7e5..f96f4403d6 100644 --- a/src/main/java/hudson/plugins/git/util/BuildChooserDescriptor.java +++ b/src/main/java/hudson/plugins/git/util/BuildChooserDescriptor.java @@ -2,8 +2,8 @@ import hudson.DescriptorExtensionList; import hudson.model.Descriptor; -import jenkins.model.Jenkins; import hudson.model.Item; +import jenkins.model.Jenkins; /** * @author Kohsuke Kawaguchi @@ -21,7 +21,7 @@ public String getLegacyId() { return null; } - public static DescriptorExtensionList all() { + public static DescriptorExtensionList all() { Jenkins jenkins = Jenkins.get(); return jenkins.getDescriptorList(BuildChooser.class); } diff --git a/src/main/java/hudson/plugins/git/util/BuildData.java b/src/main/java/hudson/plugins/git/util/BuildData.java index a15faf2485..388f32bd8b 100644 --- a/src/main/java/hudson/plugins/git/util/BuildData.java +++ b/src/main/java/hudson/plugins/git/util/BuildData.java @@ -1,5 +1,7 @@ package hudson.plugins.git.util; +import static hudson.Util.fixNull; + import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.model.AbstractBuild; import hudson.model.Action; @@ -9,6 +11,8 @@ import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; import java.io.Serializable; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -16,6 +20,8 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; import org.eclipse.jgit.lib.ObjectId; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; @@ -24,11 +30,6 @@ import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; -import static hudson.Util.fixNull; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.logging.Level; -import java.util.logging.Logger; /** * Captures the Git related information for a build. * @@ -70,8 +71,7 @@ public class BuildData implements Action, Serializable, Cloneable { @CheckForNull private Integer index; - public BuildData() { - } + public BuildData() {} public BuildData(String scmName) { this.scmName = scmName; @@ -79,7 +79,7 @@ public BuildData(String scmName) { public BuildData(String scmName, Collection remoteConfigs) { this.scmName = scmName; - for(UserRemoteConfig c : remoteConfigs) { + for (UserRemoteConfig c : remoteConfigs) { remoteUrls.add(c.getUrl()); } } @@ -95,19 +95,20 @@ public BuildData(String scmName, Collection remoteConfigs) { */ @Override public String getDisplayName() { - if (scmName != null && !scmName.isEmpty()) + if (scmName != null && !scmName.isEmpty()) { return "Git Build Data:" + scmName; + } return "Git Build Data"; } @Override public String getIconFileName() { - return jenkins.model.Jenkins.RESOURCE_PATH+"/plugin/git/icons/git-icon.svg"; + return jenkins.model.Jenkins.RESOURCE_PATH + "/plugin/git/icons/git-icon.svg"; } @Override public String getUrlName() { - return index == null ? "git" : "git-"+index; + return index == null ? "git" : "git-" + index; } /** @@ -131,7 +132,7 @@ public Integer getIndex() { @Restricted(NoExternalUse.class) // only used from stapler/jelly @CheckForNull - public Run getOwningRun() { + public Run getOwningRun() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { return null; @@ -140,7 +141,7 @@ public Run getOwningRun() { } public Object readResolve() { - Map newBuildsByBranchName = new HashMap<>(); + Map newBuildsByBranchName = new HashMap<>(); for (Map.Entry buildByBranchName : buildsByBranchName.entrySet()) { String branchName = fixNull(buildByBranchName.getKey()); @@ -150,8 +151,9 @@ public Object readResolve() { this.buildsByBranchName = newBuildsByBranchName; - if(this.remoteUrls == null) + if (this.remoteUrls == null) { this.remoteUrls = new HashSet<>(); + } return this; } @@ -163,7 +165,7 @@ public Object readResolve() { * @return true if sha1 has been built */ public boolean hasBeenBuilt(ObjectId sha1) { - return getLastBuild(sha1) != null; + return getLastBuild(sha1) != null; } public Build getLastBuild(ObjectId sha1) { @@ -177,11 +179,16 @@ public Build getLastBuild(ObjectId sha1) { ObjectId lastBuildRevisionSha1 = lastBuild.revision.getSha1(); if (lastBuildRevisionSha1 != null) { if (lastBuildRevisionSha1.equals(sha1)) { - LOGGER.log(Level.FINEST, "lastBuildRevisionSha1 matches sha1:{0}, returning lastBuild", sha1.getName()); + LOGGER.log( + Level.FINEST, + "lastBuildRevisionSha1 matches sha1:{0}, returning lastBuild", + sha1.getName()); return lastBuild; } else { - LOGGER.log(Level.FINEST, "lastBuildRevisionSha1: {0} does not match sha1:{1}, checking lastBuild.marked", - new Object[]{lastBuildRevisionSha1.getName(), sha1.getName()}); + LOGGER.log( + Level.FINEST, + "lastBuildRevisionSha1: {0} does not match sha1:{1}, checking lastBuild.marked", + new Object[] {lastBuildRevisionSha1.getName(), sha1.getName()}); } } else { LOGGER.log(Level.FINEST, "lastBuild.revision.getSha1() is null, checking lastBuild.marked"); @@ -193,11 +200,15 @@ public Build getLastBuild(ObjectId sha1) { ObjectId lastBuildMarkedSha1 = lastBuild.marked.getSha1(); if (lastBuildMarkedSha1 != null) { if (lastBuildMarkedSha1.equals(sha1)) { - LOGGER.log(Level.FINEST, "lastBuildMarkedSha1 matches sha1:{0}, returning lastBuild", sha1.getName()); + LOGGER.log( + Level.FINEST, + "lastBuildMarkedSha1 matches sha1:{0}, returning lastBuild", + sha1.getName()); return lastBuild; } else { - LOGGER.log(Level.FINEST, "lastBuildMarkedSha1: {0} does not match sha1:{1}", - new Object[]{lastBuildMarkedSha1.getName(), sha1.getName()}); + LOGGER.log(Level.FINEST, "lastBuildMarkedSha1: {0} does not match sha1:{1}", new Object[] { + lastBuildMarkedSha1.getName(), sha1.getName() + }); } } else { LOGGER.log(Level.FINEST, "lastBuild.marked.getSha1() is null"); @@ -230,11 +241,11 @@ public Build getLastBuild(ObjectId sha1) { } public void saveBuild(Build build) { - lastBuild = build; - for(Branch branch : build.marked.getBranches()) { + lastBuild = build; + for (Branch branch : build.marked.getBranches()) { buildsByBranchName.put(fixNull(branch.getName()), build); - } - for(Branch branch : build.revision.getBranches()) { + } + for (Branch branch : build.revision.getBranches()) { buildsByBranchName.put(fixNull(branch.getName()), build); } } @@ -250,24 +261,23 @@ public Build getLastBuildOfBranch(String branch) { */ @Exported public @CheckForNull Revision getLastBuiltRevision() { - return lastBuild==null?null:lastBuild.revision; + return lastBuild == null ? null : lastBuild.revision; } @Exported - public Map getBuildsByBranchName() { + public Map getBuildsByBranchName() { return buildsByBranchName; } - public void setScmName(String scmName) - { + public void setScmName(String scmName) { this.scmName = scmName; } @Exported - public String getScmName() - { - if (scmName == null) + public String getScmName() { + if (scmName == null) { scmName = ""; + } return scmName; } @@ -276,7 +286,7 @@ public void addRemoteUrl(String remoteUrl) { } @Exported - public Set getRemoteUrls() { + public Set getRemoteUrls() { return remoteUrls; } @@ -289,8 +299,7 @@ public BuildData clone() { BuildData clone; try { clone = (BuildData) super.clone(); - } - catch (CloneNotSupportedException e) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning BuildData", e); } @@ -321,8 +330,7 @@ public BuildData clone() { } } - for(String remoteUrl : getRemoteUrls()) - { + for (String remoteUrl : getRemoteUrls()) { clone.addRemoteUrl(remoteUrl); } @@ -336,10 +344,10 @@ public Api getApi() { @Override public String toString() { final String scmNameString = scmName == null ? "" : scmName; - return super.toString()+"[scmName="+scmNameString+ - ",remoteUrls="+remoteUrls+ - ",buildsByBranchName="+buildsByBranchName+ - ",lastBuild="+lastBuild+"]"; + return super.toString() + "[scmName=" + scmNameString + ",remoteUrls=" + + remoteUrls + ",buildsByBranchName=" + + buildsByBranchName + ",lastBuild=" + + lastBuild + "]"; } /** @@ -392,11 +400,11 @@ public boolean similarTo(BuildData that) { return false; } Set thisUrls = new HashSet<>(this.remoteUrls.size()); - for (String url: this.remoteUrls) { + for (String url : this.remoteUrls) { thisUrls.add(normalize(url)); } Set thatUrls = new HashSet<>(that.remoteUrls.size()); - for (String url: that.remoteUrls) { + for (String url : that.remoteUrls) { thatUrls.add(normalize(url)); } return thisUrls.equals(thatUrls); diff --git a/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java b/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java index a9d8740818..d83a366fde 100644 --- a/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java +++ b/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java @@ -25,18 +25,19 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.plugins.git.Revision; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; - import java.io.IOException; import java.util.Comparator; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevWalk; /** * Compares {@link Revision} by their timestamps. - * + * * @author Kohsuke Kawaguchi */ -@SuppressFBWarnings(value="SE_COMPARATOR_SHOULD_BE_SERIALIZABLE", justification="Known non-serializable field critical part of class") +@SuppressFBWarnings( + value = "SE_COMPARATOR_SHOULD_BE_SERIALIZABLE", + justification = "Known non-serializable field critical part of class") public class CommitTimeComparator implements Comparator { private final RevWalk walk; @@ -44,8 +45,9 @@ public CommitTimeComparator(Repository r) { walk = new RevWalk(r); } + @Override public int compare(Revision lhs, Revision rhs) { - return compare(time(lhs),time(rhs)); + return compare(time(lhs), time(rhs)); } private int time(Revision r) { @@ -53,7 +55,7 @@ private int time(Revision r) { try { return walk.parseCommit(r.getSha1()).getCommitTime(); } catch (IOException e) { - throw new RuntimeException("Failed to parse "+r.getSha1(),e); + throw new RuntimeException("Failed to parse " + r.getSha1(), e); } } diff --git a/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java b/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java index 226946c575..a297bb5efa 100644 --- a/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java @@ -1,30 +1,28 @@ package hudson.plugins.git.util; -import hudson.Extension; +import static java.util.Collections.emptyList; + import hudson.EnvVars; +import hudson.Extension; import hudson.model.TaskListener; import hudson.plugins.git.*; import hudson.remoting.VirtualChannel; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.*; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.RemoteConfig; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.stapler.DataBoundConstructor; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.*; - -import static java.util.Collections.emptyList; - public class DefaultBuildChooser extends BuildChooser { /* Ignore symbolic default branch ref. */ private static final BranchSpec HEAD = new BranchSpec("*/HEAD"); @DataBoundConstructor - public DefaultBuildChooser() { - } + public DefaultBuildChooser() {} /** * Determines which Revisions to build. @@ -41,16 +39,27 @@ public DefaultBuildChooser() { * @throws InterruptedException when interrupted */ @Override - public Collection getCandidateRevisions(boolean isPollCall, String branchSpec, - GitClient git, TaskListener listener, BuildData data, BuildChooserContext context) + public Collection getCandidateRevisions( + boolean isPollCall, + String branchSpec, + GitClient git, + TaskListener listener, + BuildData data, + BuildChooserContext context) throws GitException, IOException, InterruptedException { - verbose(listener,"getCandidateRevisions({0},{1},,,{2}) considering branches to build",isPollCall,branchSpec,data); + verbose( + listener, + "getCandidateRevisions({0},{1},,,{2}) considering branches to build", + isPollCall, + branchSpec, + data); // if the branch name contains more wildcards then the simple usecase // does not apply and we need to skip to the advanced usecase - if (isAdvancedSpec(branchSpec)) - return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data, context); + if (isAdvancedSpec(branchSpec)) { + return getAdvancedCandidateRevisions(isPollCall, listener, new GitUtils(listener, git), data, context); + } // check if we're trying to build a specific commit // this only makes sense for a build, there is no @@ -60,7 +69,7 @@ public Collection getCandidateRevisions(boolean isPollCall, String bra ObjectId sha1 = git.revParse(branchSpec); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch("detached", sha1)); - verbose(listener,"Will build the detached SHA1 {0}",sha1); + verbose(listener, "Will build the detached SHA1 {0}", sha1); return Collections.singletonList(revision); } catch (GitException e) { // revision does not exist, may still be a branch @@ -91,24 +100,29 @@ public Collection getCandidateRevisions(boolean isPollCall, String bra String fqbn; if (branchSpec.startsWith(repository + "/")) { fqbn = "refs/remotes/" + branchSpec; - } else if(branchSpec.startsWith("remotes/" + repository + "/")) { + } else if (branchSpec.startsWith("remotes/" + repository + "/")) { fqbn = "refs/" + branchSpec; - } else if(branchSpec.startsWith("refs/heads/")) { + } else if (branchSpec.startsWith("refs/heads/")) { fqbn = "refs/remotes/" + repository + "/" + branchSpec.substring("refs/heads/".length()); } else { - //Check if exact branch name exists + // Check if exact branch name exists fqbn = "refs/remotes/" + repository + "/" + branchSpec; - verbose(listener, "Qualifying {0} as a branch in repository {1} -> {2}", branchSpec, repository, fqbn); + verbose( + listener, + "Qualifying {0} as a branch in repository {1} -> {2}", + branchSpec, + repository, + fqbn); possibleQualifiedBranches.add(fqbn); - //Try branchSpec as it is - e.g. "refs/tags/mytag" + // Try branchSpec as it is - e.g. "refs/tags/mytag" fqbn = branchSpec; } verbose(listener, "Qualifying {0} as a branch in repository {1} -> {2}", branchSpec, repository, fqbn); possibleQualifiedBranches.add(fqbn); } for (String fqbn : possibleQualifiedBranches) { - revisions.addAll(getHeadRevision(isPollCall, fqbn, git, listener, data)); + revisions.addAll(getHeadRevision(isPollCall, fqbn, git, listener, data)); } } @@ -120,11 +134,13 @@ public Collection getCandidateRevisions(boolean isPollCall, String bra verbose(listener, "{0} seems to be a non-branch reference (tag?)"); } } - + return revisions; } - private Collection getHeadRevision(boolean isPollCall, String singleBranch, GitClient git, TaskListener listener, BuildData data) throws InterruptedException { + private Collection getHeadRevision( + boolean isPollCall, String singleBranch, GitClient git, TaskListener listener, BuildData data) + throws InterruptedException { try { ObjectId sha1 = git.revParse(singleBranch); verbose(listener, "rev-parse {0} -> {1}", singleBranch, sha1); @@ -165,7 +181,9 @@ private Collection getHeadRevision(boolean isPollCall, String singleBr * @throws IOException on input or output error * @throws GitException on git error */ - private List getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data, BuildChooserContext context) throws GitException, IOException, InterruptedException { + private List getAdvancedCandidateRevisions( + boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data, BuildChooserContext context) + throws GitException, IOException, InterruptedException { EnvVars env = context.getEnvironment(); @@ -175,11 +193,11 @@ private List getAdvancedCandidateRevisions(boolean isPollCall, TaskLis // 2. Filter out any revisions that don't contain any branches that we // actually care about (spec) - for (Iterator i = revs.iterator(); i.hasNext();) { + for (Iterator i = revs.iterator(); i.hasNext(); ) { Revision r = i.next(); // filter out uninteresting branches - for (Iterator j = r.getBranches().iterator(); j.hasNext();) { + for (Iterator j = r.getBranches().iterator(); j.hasNext(); ) { Branch b = j.next(); boolean keep = false; for (BranchSpec bspec : gitSCM.getBranches()) { @@ -194,14 +212,14 @@ private List getAdvancedCandidateRevisions(boolean isPollCall, TaskLis j.remove(); } } - + // filter out HEAD ref if it's not the only ref if (r.getBranches().size() > 1) { - for (Iterator j = r.getBranches().iterator(); j.hasNext();) { + for (Iterator j = r.getBranches().iterator(); j.hasNext(); ) { Branch b = j.next(); if (HEAD.matches(b.getName(), env)) { - verbose(listener, "Ignoring {0} because there''s named branch for this revision", b.getName()); - j.remove(); + verbose(listener, "Ignoring {0} because there''s named branch for this revision", b.getName()); + j.remove(); } } } @@ -221,15 +239,15 @@ private List getAdvancedCandidateRevisions(boolean isPollCall, TaskLis // 4. Finally, remove any revisions that have already been built. verbose(listener, "Removing what''s already been built: {0}", data.getBuildsByBranchName()); Revision lastBuiltRevision = data.getLastBuiltRevision(); - for (Iterator i = revs.iterator(); i.hasNext();) { + for (Iterator i = revs.iterator(); i.hasNext(); ) { Revision r = i.next(); if (data.hasBeenBuilt(r.getSha1())) { i.remove(); - + // keep track of new branches pointing to the last built revision if (lastBuiltRevision != null && lastBuiltRevision.getSha1().equals(r.getSha1())) { - lastBuiltRevision = r; + lastBuiltRevision = r; } } } @@ -241,8 +259,12 @@ private List getAdvancedCandidateRevisions(boolean isPollCall, TaskLis // a deterministic value for GIT_BRANCH and allows a git-flow style workflow // with fast-forward merges between branches if (!isPollCall && revs.isEmpty() && lastBuiltRevision != null) { - verbose(listener, "Nothing seems worth building, so falling back to the previously built revision: {0}", data.getLastBuiltRevision()); - return Collections.singletonList(utils.sortBranchesForRevision(lastBuiltRevision, gitSCM.getBranches(), env)); + verbose( + listener, + "Nothing seems worth building, so falling back to the previously built revision: {0}", + data.getLastBuiltRevision()); + return Collections.singletonList( + utils.sortBranchesForRevision(lastBuiltRevision, gitSCM.getBranches(), env)); } // 5. sort them by the date of commit, old to new @@ -258,8 +280,9 @@ private List getAdvancedCandidateRevisions(boolean isPollCall, TaskLis * Write the message to the listener only when the verbose mode is on. */ private void verbose(TaskListener listener, String format, Object... args) { - if (GitSCM.VERBOSE) - listener.getLogger().println(MessageFormat.format(format,args)); + if (GitSCM.VERBOSE) { + listener.getLogger().println(MessageFormat.format(format, args)); + } } @Extension diff --git a/src/main/java/hudson/plugins/git/util/GitUtils.java b/src/main/java/hudson/plugins/git/util/GitUtils.java index 1142142f63..1bfcba1c28 100644 --- a/src/main/java/hudson/plugins/git/util/GitUtils.java +++ b/src/main/java/hudson/plugins/git/util/GitUtils.java @@ -1,6 +1,8 @@ package hudson.plugins.git.util; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; +import edu.umd.cs.findbugs.annotations.CheckForNull; +import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.FilePath; @@ -14,14 +16,6 @@ import hudson.plugins.git.Revision; import hudson.remoting.VirtualChannel; import hudson.slaves.NodeProperty; -import jenkins.model.Jenkins; -import org.eclipse.jgit.lib.Constants; -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.io.IOException; import java.io.OutputStream; import java.io.Serializable; @@ -29,14 +23,20 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import edu.umd.cs.findbugs.annotations.CheckForNull; -import edu.umd.cs.findbugs.annotations.NonNull; +import jenkins.model.Jenkins; +import org.eclipse.jgit.lib.Constants; +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; public class GitUtils implements Serializable { - - @SuppressFBWarnings(value="SE_BAD_FIELD", justification="known non-serializable field") + + @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "known non-serializable field") @NonNull GitClient git; + @NonNull TaskListener listener; @@ -56,13 +56,16 @@ public GitUtils(@NonNull TaskListener listener, @NonNull GitClient git) { * @since 4.0.0 */ @CheckForNull - public static GitTool resolveGitTool(@CheckForNull String gitTool, - @CheckForNull Node builtOn, - @CheckForNull EnvVars env, - @NonNull TaskListener listener) { + public static GitTool resolveGitTool( + @CheckForNull String gitTool, + @CheckForNull Node builtOn, + @CheckForNull EnvVars env, + @NonNull TaskListener listener) { GitTool git = gitTool == null ? GitTool.getDefaultInstallation() - : Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallation(gitTool); + : Jenkins.get() + .getDescriptorByType(GitTool.DescriptorImpl.class) + .getInstallation(gitTool); if (git == null) { listener.getLogger().println("Selected Git installation does not exist. Using Default"); git = GitTool.getDefaultInstallation(); @@ -149,10 +152,11 @@ public Collection getAllBranchRevisions() throws GitException, IOExcep * @throws GitException on git error * @throws InterruptedException when interrupted */ - public Revision getRevisionContainingBranch(String branchName) throws GitException, IOException, InterruptedException { - for(Revision revision : getAllBranchRevisions()) { - for(Branch b : revision.getBranches()) { - if(b.getName().equals(branchName)) { + public Revision getRevisionContainingBranch(String branchName) + throws GitException, IOException, InterruptedException { + for (Revision revision : getAllBranchRevisions()) { + for (Branch b : revision.getBranches()) { + if (b.getName().equals(branchName)) { return revision; } } @@ -161,9 +165,10 @@ public Revision getRevisionContainingBranch(String branchName) throws GitExcepti } public Revision getRevisionForSHA1(ObjectId sha1) throws GitException, IOException, InterruptedException { - for(Revision revision : getAllBranchRevisions()) { - if(revision.getSha1().equals(sha1)) + for (Revision revision : getAllBranchRevisions()) { + if (revision.getSha1().equals(sha1)) { return revision; + } } return new Revision(sha1); } @@ -174,11 +179,12 @@ public Revision sortBranchesForRevision(Revision revision, List bran } public Revision sortBranchesForRevision(Revision revision, List branchOrder, EnvVars env) { - ArrayList orderedBranches = new ArrayList<>(revision.getBranches().size()); + ArrayList orderedBranches = + new ArrayList<>(revision.getBranches().size()); ArrayList revisionBranches = new ArrayList<>(revision.getBranches()); - for(BranchSpec branchSpec : branchOrder) { - for (Iterator i = revisionBranches.iterator(); i.hasNext();) { + for (BranchSpec branchSpec : branchOrder) { + for (Iterator i = revisionBranches.iterator(); i.hasNext(); ) { Branch b = i.next(); if (branchSpec.matches(b.getName(), env)) { i.remove(); @@ -208,8 +214,9 @@ public List filterTipBranches(final Collection revisions) th final List l = new ArrayList<>(revisions); // Bypass any rev walks if only one branch or less - if (l.size() <= 1) + if (l.size() <= 1) { return l; + } try { return git.withRepository((Repository repo, VirtualChannel channel) -> { @@ -224,9 +231,9 @@ public List filterTipBranches(final Collection revisions) th final boolean log = LOGGER.isLoggable(Level.FINE); - if (log) - LOGGER.fine(MessageFormat.format( - "Computing merge base of {0} branches", l.size())); + if (log) { + LOGGER.fine(MessageFormat.format("Computing merge base of {0} branches", l.size())); + } try (RevWalk walk = new RevWalk(repo)) { walk.setRetainBody(false); @@ -257,10 +264,11 @@ public List filterTipBranches(final Collection revisions) th } } - if (log) + if (log) { LOGGER.fine(MessageFormat.format( - "Computed merge bases in {0} commit steps and {1} ms", calls, - (System.currentTimeMillis() - start))); + "Computed merge bases in {0} commit steps and {1} ms", + calls, (System.currentTimeMillis() - start))); + } return new ArrayList<>(tipCandidates.values()); }); @@ -270,11 +278,10 @@ public List filterTipBranches(final Collection revisions) th } public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener) - throws IOException, InterruptedException { + throws IOException, InterruptedException { return getPollEnvironment(p, ws, launcher, listener, true); } - /** * An attempt to generate at least semi-useful EnvVars for polling calls, based on previous build. * Cribbed from various places. @@ -287,18 +294,19 @@ public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launche * @throws IOException on input or output error * @throws InterruptedException when interrupted */ - public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener, boolean reuseLastBuildEnv) - throws IOException,InterruptedException { + public static EnvVars getPollEnvironment( + AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener, boolean reuseLastBuildEnv) + throws IOException, InterruptedException { EnvVars env = null; - StreamBuildListener buildListener = new StreamBuildListener((OutputStream)listener.getLogger()); + StreamBuildListener buildListener = new StreamBuildListener((OutputStream) listener.getLogger()); AbstractBuild b = p.getLastBuild(); if (b == null) { // If there is no last build, we need to trigger a new build anyway, and // GitSCM.compareRemoteRevisionWithImpl() will short-circuit and never call this code // ("No previous build, so forcing an initial build."). - throw new IllegalArgumentException("Last build must not be null. If there really is no last build, " + - "a new build should be triggered without polling the SCM."); + throw new IllegalArgumentException("Last build must not be null. If there really is no last build, " + + "a new build should be triggered without polling the SCM."); } if (reuseLastBuildEnv) { @@ -320,7 +328,7 @@ public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launche env = p.getEnvironment(workspaceToNode(ws), listener); } - p.getScm().buildEnvironment(b,env); + p.getScm().buildEnvironment(b, env); } else { env = p.getEnvironment(workspaceToNode(ws), listener); } @@ -330,23 +338,26 @@ public static EnvVars getPollEnvironment(AbstractProject p, FilePath ws, Launche throw new IllegalArgumentException("Jenkins instance is null"); } String rootUrl = jenkinsInstance.getRootUrl(); - if(rootUrl!=null) { + if (rootUrl != null) { env.put("HUDSON_URL", rootUrl); // Legacy. env.put("JENKINS_URL", rootUrl); - env.put("BUILD_URL", rootUrl+b.getUrl()); - env.put("JOB_URL", rootUrl+p.getUrl()); + env.put("BUILD_URL", rootUrl + b.getUrl()); + env.put("JOB_URL", rootUrl + p.getUrl()); } - if(!env.containsKey("HUDSON_HOME")) // Legacy - env.put("HUDSON_HOME", jenkinsInstance.getRootDir().getPath() ); + if (!env.containsKey("HUDSON_HOME")) { // Legacy + env.put("HUDSON_HOME", jenkinsInstance.getRootDir().getPath()); + } - if(!env.containsKey("JENKINS_HOME")) - env.put("JENKINS_HOME", jenkinsInstance.getRootDir().getPath() ); + if (!env.containsKey("JENKINS_HOME")) { + env.put("JENKINS_HOME", jenkinsInstance.getRootDir().getPath()); + } - if (ws != null) + if (ws != null) { env.put("WORKSPACE", ws.getRemote()); + } - for (NodeProperty nodeProperty: jenkinsInstance.getGlobalNodeProperties()) { + for (NodeProperty nodeProperty : jenkinsInstance.getGlobalNodeProperties()) { Environment environment = nodeProperty.setUp(b, launcher, buildListener); if (environment != null) { environment.buildEnvVars(env); @@ -372,13 +383,14 @@ private static void addEnvironmentContributingActionsValues(EnvVars env, Abstrac } // Use the default parameter values (if any) instead of the ones from the last build - ParametersDefinitionProperty paramDefProp = (ParametersDefinitionProperty) b.getProject().getProperty(ParametersDefinitionProperty.class); + ParametersDefinitionProperty paramDefProp = + (ParametersDefinitionProperty) b.getProject().getProperty(ParametersDefinitionProperty.class); if (paramDefProp != null) { - for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) { - ParameterValue defaultValue = paramDefinition.getDefaultParameterValue(); - if (defaultValue != null) { - defaultValue.buildEnvironment(b, env); - } + for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) { + ParameterValue defaultValue = paramDefinition.getDefaultParameterValue(); + if (defaultValue != null) { + defaultValue.buildEnvironment(b, env); + } } } } @@ -387,16 +399,16 @@ public static String[] fixupNames(String[] names, String[] urls) { String[] returnNames = new String[urls.length]; Set usedNames = new HashSet<>(); - for(int i=0; iexcept for those which match the * configured branch specifiers. @@ -33,13 +32,17 @@ public class InverseBuildChooser extends BuildChooser { private static final BranchSpec HEAD = new BranchSpec("*/HEAD"); @DataBoundConstructor - public InverseBuildChooser() { - } + public InverseBuildChooser() {} @Override - public Collection getCandidateRevisions(boolean isPollCall, - String singleBranch, GitClient git, TaskListener listener, - BuildData buildData, BuildChooserContext context) throws GitException, IOException, InterruptedException { + public Collection getCandidateRevisions( + boolean isPollCall, + String singleBranch, + GitClient git, + TaskListener listener, + BuildData buildData, + BuildChooserContext context) + throws GitException, IOException, InterruptedException { EnvVars env = context.getEnvironment(); GitUtils utils = new GitUtils(listener, git); @@ -104,5 +107,4 @@ public String getDisplayName() { } private static final long serialVersionUID = 1L; - } diff --git a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java index 429f4e8234..dc0b4d1d23 100644 --- a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java @@ -150,7 +150,8 @@ public abstract class AbstractGitSCMSource extends SCMSource { * * @since 3.4.0 */ - public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER = "(?i)"+Pattern.quote(REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR); + public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER = + "(?i)" + Pattern.quote(REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR); /** * The default ref spec template. * @@ -166,9 +167,8 @@ public abstract class AbstractGitSCMSource extends SCMSource { private static final Logger LOGGER = Logger.getLogger(AbstractGitSCMSource.class.getName()); - public AbstractGitSCMSource() { - } - + public AbstractGitSCMSource() {} + @Deprecated public AbstractGitSCMSource(String id) { setId(id); @@ -262,6 +262,7 @@ public List getExtensions() { * @return the {@link SCMSourceTrait} instances * @since 3.4.0 */ + @Override @NonNull public List getTraits() { // Always return empty list (we expect subclasses to override) @@ -322,41 +323,42 @@ private interface Retriever2 extends Retriever { } @NonNull - private , R extends GitSCMSourceRequest> T doRetrieve(Retriever retriever, - @NonNull C context, - @NonNull TaskListener listener, - boolean prune) - throws IOException, InterruptedException { + private , R extends GitSCMSourceRequest> T doRetrieve( + Retriever retriever, @NonNull C context, @NonNull TaskListener listener, boolean prune) + throws IOException, InterruptedException { return doRetrieve(retriever, context, listener, prune, getOwner(), false); } @NonNull - private , R extends GitSCMSourceRequest> T doRetrieve(Retriever retriever, - @NonNull C context, - @NonNull TaskListener listener, - boolean prune, - @CheckForNull Item retrieveContext) + private , R extends GitSCMSourceRequest> T doRetrieve( + Retriever retriever, + @NonNull C context, + @NonNull TaskListener listener, + boolean prune, + @CheckForNull Item retrieveContext) throws IOException, InterruptedException { return doRetrieve(retriever, context, listener, prune, retrieveContext, false); } @NonNull - private , R extends GitSCMSourceRequest> T doRetrieve(Retriever retriever, - @NonNull C context, - @NonNull TaskListener listener, - boolean prune, - boolean delayFetch) + private , R extends GitSCMSourceRequest> T doRetrieve( + Retriever retriever, + @NonNull C context, + @NonNull TaskListener listener, + boolean prune, + boolean delayFetch) throws IOException, InterruptedException { return doRetrieve(retriever, context, listener, prune, getOwner(), delayFetch); } @NonNull - private , R extends GitSCMSourceRequest> T doRetrieve(Retriever retriever, - @NonNull C context, - @NonNull TaskListener listener, - boolean prune, - @CheckForNull Item retrieveContext, - boolean delayFetch) + private , R extends GitSCMSourceRequest> T doRetrieve( + Retriever retriever, + @NonNull C context, + @NonNull TaskListener listener, + boolean prune, + @CheckForNull Item retrieveContext, + boolean delayFetch) throws IOException, InterruptedException { String cacheEntry = getCacheEntry(); Lock cacheLock = getCacheLock(cacheEntry); @@ -393,7 +395,7 @@ private , R extends GitSCMSourceRequest> if (!delayFetch) { fetchCommand.execute(); } else if (retriever instanceof Retriever2) { - return ((Retriever2)retriever).run(client, remoteName, fetchCommand); + return ((Retriever2) retriever).run(client, remoteName, fetchCommand); } return retriever.run(client, remoteName); } finally { @@ -416,61 +418,64 @@ protected SCMRevision retrieve(@NonNull final SCMHead head, @NonNull final TaskL telescope.validate(remote, credentials); return telescope.getRevision(remote, credentials, head); } - //TODO write test using GitRefSCMHead - return doRetrieve(new Retriever() { - @Override - public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { - if (head instanceof GitTagSCMHead) { - try { - ObjectId objectId = client.revParse(Constants.R_TAGS + head.getName()); - return new GitTagSCMRevision((GitTagSCMHead) head, objectId.name()); - } catch (GitException e) { - // tag does not exist - return null; - } - } else if (head instanceof GitBranchSCMHead) { - for (Branch b : client.getRemoteBranches()) { - String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); - if (branchName.equals(head.getName())) { - return new GitBranchSCMRevision((GitBranchSCMHead)head, b.getSHA1String()); - } - } - } else if (head instanceof GitRefSCMHead) { - try { - ObjectId objectId = client.revParse(((GitRefSCMHead) head).getRef()); - return new GitRefSCMRevision((GitRefSCMHead)head, objectId.name()); - } catch (GitException e) { - // ref could not be found - return null; - } - } else { - //Entering default/legacy git retrieve code path - for (Branch b : client.getRemoteBranches()) { - String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); - if (branchName.equals(head.getName())) { - return new SCMRevisionImpl(head, b.getSHA1String()); - } - } - } - return null; - } - }, + // TODO write test using GitRefSCMHead + return doRetrieve( + new Retriever() { + @Override + public SCMRevision run(GitClient client, String remoteName) + throws IOException, InterruptedException { + if (head instanceof GitTagSCMHead) { + try { + ObjectId objectId = client.revParse(Constants.R_TAGS + head.getName()); + return new GitTagSCMRevision((GitTagSCMHead) head, objectId.name()); + } catch (GitException e) { + // tag does not exist + return null; + } + } else if (head instanceof GitBranchSCMHead) { + for (Branch b : client.getRemoteBranches()) { + String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); + if (branchName.equals(head.getName())) { + return new GitBranchSCMRevision((GitBranchSCMHead) head, b.getSHA1String()); + } + } + } else if (head instanceof GitRefSCMHead) { + try { + ObjectId objectId = client.revParse(((GitRefSCMHead) head).getRef()); + return new GitRefSCMRevision((GitRefSCMHead) head, objectId.name()); + } catch (GitException e) { + // ref could not be found + return null; + } + } else { + // Entering default/legacy git retrieve code path + for (Branch b : client.getRemoteBranches()) { + String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); + if (branchName.equals(head.getName())) { + return new SCMRevisionImpl(head, b.getSHA1String()); + } + } + } + return null; + } + }, context, - listener, /* we don't prune remotes here, as we just want one head's revision */false); + listener, /* we don't prune remotes here, as we just want one head's revision */ + false); } /** * {@inheritDoc} */ @Override - @SuppressFBWarnings(value="SE_BAD_FIELD", justification="Known non-serializable this") - protected void retrieve(@CheckForNull SCMSourceCriteria criteria, - @NonNull SCMHeadObserver observer, - @CheckForNull SCMHeadEvent event, - @NonNull final TaskListener listener) + @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Known non-serializable this") + protected void retrieve( + @CheckForNull SCMSourceCriteria criteria, + @NonNull SCMHeadObserver observer, + @CheckForNull SCMHeadEvent event, + @NonNull final TaskListener listener) throws IOException, InterruptedException { - final GitSCMSourceContext context = - new GitSCMSourceContext<>(criteria, observer).withTraits(getTraits()); + final GitSCMSourceContext context = new GitSCMSourceContext<>(criteria, observer).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); @@ -483,7 +488,7 @@ protected void retrieve(@CheckForNull SCMSourceCriteria criteria, if (context.wantTags()) { referenceTypes.add(GitSCMTelescope.ReferenceType.TAG); } - //TODO JENKINS-51134 DiscoverOtherRefsTrait + // TODO JENKINS-51134 DiscoverOtherRefsTrait if (!referenceTypes.isEmpty()) { try (GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { listener.getLogger().println("Listing remote references..."); @@ -496,37 +501,39 @@ protected void retrieve(@CheckForNull SCMSourceCriteria criteria, continue; } count++; - if (request.process(revision.getHead(), + if (request.process( + revision.getHead(), new SCMSourceRequest.RevisionLambda() { @NonNull @Override public SCMRevisionImpl create(@NonNull SCMHead head) throws IOException, InterruptedException { listener.getLogger() - .println(" Checking branch " + revision.getHead().getName()); + .println(" Checking branch " + + revision.getHead().getName()); return (SCMRevisionImpl) revision; } }, new SCMSourceRequest.ProbeLambda() { @NonNull @Override - public SCMSourceCriteria.Probe create(@NonNull SCMHead head, - @NonNull SCMRevisionImpl revision) + public SCMSourceCriteria.Probe create( + @NonNull SCMHead head, @NonNull SCMRevisionImpl revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } - }, new SCMSourceRequest.Witness() { + }, + new SCMSourceRequest.Witness() { @Override - public void record(@NonNull SCMHead head, SCMRevision revision, - boolean isMatch) { + public void record( + @NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } - } - )) { + })) { listener.getLogger().format("Processed %d branches (query complete)%n", count); return; } @@ -546,37 +553,39 @@ public void record(@NonNull SCMHead head, SCMRevision revision, continue; } GitTagSCMHead gitTagHead = (GitTagSCMHead) scmHead; - if (request.process(gitTagHead, + if (request.process( + gitTagHead, new SCMSourceRequest.RevisionLambda() { @NonNull @Override public GitTagSCMRevision create(@NonNull GitTagSCMHead head) throws IOException, InterruptedException { listener.getLogger() - .println(" Checking tag " + revision.getHead().getName()); + .println(" Checking tag " + + revision.getHead().getName()); return (GitTagSCMRevision) revision; } }, new SCMSourceRequest.ProbeLambda() { @NonNull @Override - public SCMSourceCriteria.Probe create(@NonNull final GitTagSCMHead head, - @NonNull GitTagSCMRevision revision) + public SCMSourceCriteria.Probe create( + @NonNull final GitTagSCMHead head, @NonNull GitTagSCMRevision revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } - }, new SCMSourceRequest.Witness() { + }, + new SCMSourceRequest.Witness() { @Override - public void record(@NonNull SCMHead head, SCMRevision revision, - boolean isMatch) { + public void record( + @NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } - } - )) { + })) { listener.getLogger().format("Processed %d tags (query complete)%n", count); return; } @@ -587,228 +596,262 @@ public void record(@NonNull SCMHead head, SCMRevision revision, return; } } - doRetrieve(new Retriever2() { - @Override - public Void run(GitClient client, String remoteName, FetchCommand fetch) throws IOException, InterruptedException { - final Map remoteReferences; - if (context.wantBranches() || context.wantTags() || context.wantOtherRefs()) { - listener.getLogger().println("Listing remote references..."); - boolean headsOnly = !context.wantOtherRefs() && context.wantBranches(); - boolean tagsOnly = !context.wantOtherRefs() && context.wantTags(); - remoteReferences = client.getRemoteReferences( - client.getRemoteUrl(remoteName), null, headsOnly, tagsOnly - ); - } else { - remoteReferences = Collections.emptyMap(); - } - fetch.execute(); - try (@SuppressWarnings("deprecation") // Local repository reference - Repository repository = client.getRepository(); - RevWalk walk = new RevWalk(repository); - GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { - - if (context.wantBranches()) { - discoverBranches(repository, walk, request, remoteReferences); - } - if (context.wantTags()) { - discoverTags(repository, walk, request, remoteReferences); - } - if (context.wantOtherRefs()) { - discoverOtherRefs(repository, walk, request, remoteReferences, - (Collection)context.getRefNameMappings()); - } - } - return null; - } - - private void discoverOtherRefs(final Repository repository, - final RevWalk walk, GitSCMSourceRequest request, - Map remoteReferences, - Collection wantedRefs) - throws IOException, InterruptedException { - listener.getLogger().println("Checking other refs..."); - walk.setRetainBody(false); - int count = 0; - for (final Map.Entry ref : remoteReferences.entrySet()) { - if (ref.getKey().startsWith(Constants.R_HEADS) || ref.getKey().startsWith(Constants.R_TAGS)) { - continue; - } - for (GitSCMSourceContext.RefNameMapping otherRef : wantedRefs) { - if (!otherRef.matches(ref.getKey())) { - continue; - } - final String refName = otherRef.getName(ref.getKey()); - if (refName == null) { - listener.getLogger().println(" Possible badly configured name mapping (" + otherRef.getName() + ") (for " + ref.getKey() + ") ignoring."); - continue; + doRetrieve( + new Retriever2() { + @Override + public Void run(GitClient client, String remoteName, FetchCommand fetch) + throws IOException, InterruptedException { + final Map remoteReferences; + if (context.wantBranches() || context.wantTags() || context.wantOtherRefs()) { + listener.getLogger().println("Listing remote references..."); + boolean headsOnly = !context.wantOtherRefs() && context.wantBranches(); + boolean tagsOnly = !context.wantOtherRefs() && context.wantTags(); + remoteReferences = client.getRemoteReferences( + client.getRemoteUrl(remoteName), null, headsOnly, tagsOnly); + } else { + remoteReferences = Collections.emptyMap(); } - count++; - if (request.process(new GitRefSCMHead(refName, ref.getKey()), - new SCMSourceRequest.IntermediateLambda() { - @Nullable - @Override - public ObjectId create() throws IOException, InterruptedException { - listener.getLogger().println(" Checking ref " + refName + " (" + ref.getKey() + ")"); - return ref.getValue(); - } - }, - new SCMSourceRequest.ProbeLambda() { - @NonNull - @Override - public SCMSourceCriteria.Probe create(@NonNull GitRefSCMHead head, - @Nullable ObjectId revisionInfo) - throws IOException, InterruptedException { - RevCommit commit = walk.parseCommit(revisionInfo); - final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); - final RevTree tree = commit.getTree(); - return new TreeWalkingSCMProbe(refName, lastModified, repository, tree); - } - }, new SCMSourceRequest.LazyRevisionLambda() { - @NonNull - @Override - public SCMRevision create(@NonNull GitRefSCMHead head, @Nullable ObjectId intermediate) - throws IOException, InterruptedException { - return new GitRefSCMRevision(head, ref.getValue().name()); - } - }, new SCMSourceRequest.Witness() { - @Override - public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { - if (isMatch) { - listener.getLogger().println(" Met criteria"); - } else { - listener.getLogger().println(" Does not meet criteria"); - } - } - } - )) { - listener.getLogger().format("Processed %d refs (query complete)%n", count); - return; + fetch.execute(); + try (@SuppressWarnings("deprecation") // Local repository reference + Repository repository = client.getRepository(); + RevWalk walk = new RevWalk(repository); + GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { + + if (context.wantBranches()) { + discoverBranches(repository, walk, request, remoteReferences); + } + if (context.wantTags()) { + discoverTags(repository, walk, request, remoteReferences); + } + if (context.wantOtherRefs()) { + discoverOtherRefs(repository, walk, request, remoteReferences, (Collection< + GitSCMSourceContext.RefNameMapping>) + context.getRefNameMappings()); + } } - break; + return null; } - } - listener.getLogger().format("Processed %d refs%n", count); - } - - private void discoverBranches(final Repository repository, - final RevWalk walk, GitSCMSourceRequest request, - Map remoteReferences) - throws IOException, InterruptedException { - listener.getLogger().println("Checking branches..."); - walk.setRetainBody(false); - int count = 0; - for (final Map.Entry ref : remoteReferences.entrySet()) { - if (!ref.getKey().startsWith(Constants.R_HEADS)) { - continue; - } - count++; - final String branchName = StringUtils.removeStart(ref.getKey(), Constants.R_HEADS); - if (request.process(new GitBranchSCMHead(branchName), - new SCMSourceRequest.IntermediateLambda() { - @Nullable - @Override - public ObjectId create() throws IOException, InterruptedException { - listener.getLogger().println(" Checking branch " + branchName); - return ref.getValue(); - } - }, - new SCMSourceRequest.ProbeLambda() { - @NonNull - @Override - public SCMSourceCriteria.Probe create(@NonNull GitBranchSCMHead head, - @Nullable ObjectId revisionInfo) - throws IOException, InterruptedException { - RevCommit commit = walk.parseCommit(revisionInfo); - final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); - final RevTree tree = commit.getTree(); - return new TreeWalkingSCMProbe(branchName, lastModified, repository, tree); + private void discoverOtherRefs( + final Repository repository, + final RevWalk walk, + GitSCMSourceRequest request, + Map remoteReferences, + Collection wantedRefs) + throws IOException, InterruptedException { + listener.getLogger().println("Checking other refs..."); + walk.setRetainBody(false); + int count = 0; + for (final Map.Entry ref : remoteReferences.entrySet()) { + if (ref.getKey().startsWith(Constants.R_HEADS) + || ref.getKey().startsWith(Constants.R_TAGS)) { + continue; + } + for (GitSCMSourceContext.RefNameMapping otherRef : wantedRefs) { + if (!otherRef.matches(ref.getKey())) { + continue; } - }, new SCMSourceRequest.LazyRevisionLambda() { - @NonNull - @Override - public SCMRevision create(@NonNull GitBranchSCMHead head, @Nullable ObjectId intermediate) - throws IOException, InterruptedException { - return new GitBranchSCMRevision(head, ref.getValue().name()); + final String refName = otherRef.getName(ref.getKey()); + if (refName == null) { + listener.getLogger() + .println(" Possible badly configured name mapping (" + otherRef.getName() + + ") (for " + ref.getKey() + ") ignoring."); + continue; } - }, new SCMSourceRequest.Witness() { - @Override - public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { - if (isMatch) { - listener.getLogger().println(" Met criteria"); - } else { - listener.getLogger().println(" Does not meet criteria"); - } + count++; + if (request.process( + new GitRefSCMHead(refName, ref.getKey()), + new SCMSourceRequest.IntermediateLambda() { + @Nullable + @Override + public ObjectId create() throws IOException, InterruptedException { + listener.getLogger() + .println(" Checking ref " + refName + " (" + ref.getKey() + + ")"); + return ref.getValue(); + } + }, + new SCMSourceRequest.ProbeLambda() { + @NonNull + @Override + public SCMSourceCriteria.Probe create( + @NonNull GitRefSCMHead head, @Nullable ObjectId revisionInfo) + throws IOException, InterruptedException { + RevCommit commit = walk.parseCommit(revisionInfo); + final long lastModified = + TimeUnit.SECONDS.toMillis(commit.getCommitTime()); + final RevTree tree = commit.getTree(); + return new TreeWalkingSCMProbe(refName, lastModified, repository, tree); + } + }, + new SCMSourceRequest.LazyRevisionLambda< + GitRefSCMHead, SCMRevision, ObjectId>() { + @NonNull + @Override + public SCMRevision create( + @NonNull GitRefSCMHead head, @Nullable ObjectId intermediate) + throws IOException, InterruptedException { + return new GitRefSCMRevision( + head, ref.getValue().name()); + } + }, + new SCMSourceRequest.Witness() { + @Override + public void record( + @NonNull SCMHead head, SCMRevision revision, boolean isMatch) { + if (isMatch) { + listener.getLogger().println(" Met criteria"); + } else { + listener.getLogger().println(" Does not meet criteria"); + } + } + })) { + listener.getLogger().format("Processed %d refs (query complete)%n", count); + return; } + break; } - )) { - listener.getLogger().format("Processed %d branches (query complete)%n", count); - return; + } + listener.getLogger().format("Processed %d refs%n", count); } - } - listener.getLogger().format("Processed %d branches%n", count); - } - private void discoverTags(final Repository repository, - final RevWalk walk, GitSCMSourceRequest request, - Map remoteReferences) - throws IOException, InterruptedException { - listener.getLogger().println("Checking tags..."); - walk.setRetainBody(false); - int count = 0; - for (final Map.Entry ref : remoteReferences.entrySet()) { - if (!ref.getKey().startsWith(Constants.R_TAGS)) { - continue; + private void discoverBranches( + final Repository repository, + final RevWalk walk, + GitSCMSourceRequest request, + Map remoteReferences) + throws IOException, InterruptedException { + listener.getLogger().println("Checking branches..."); + walk.setRetainBody(false); + int count = 0; + for (final Map.Entry ref : remoteReferences.entrySet()) { + if (!ref.getKey().startsWith(Constants.R_HEADS)) { + continue; + } + count++; + final String branchName = StringUtils.removeStart(ref.getKey(), Constants.R_HEADS); + if (request.process( + new GitBranchSCMHead(branchName), + new SCMSourceRequest.IntermediateLambda() { + @Nullable + @Override + public ObjectId create() throws IOException, InterruptedException { + listener.getLogger().println(" Checking branch " + branchName); + return ref.getValue(); + } + }, + new SCMSourceRequest.ProbeLambda() { + @NonNull + @Override + public SCMSourceCriteria.Probe create( + @NonNull GitBranchSCMHead head, @Nullable ObjectId revisionInfo) + throws IOException, InterruptedException { + RevCommit commit = walk.parseCommit(revisionInfo); + final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); + final RevTree tree = commit.getTree(); + return new TreeWalkingSCMProbe(branchName, lastModified, repository, tree); + } + }, + new SCMSourceRequest.LazyRevisionLambda() { + @NonNull + @Override + public SCMRevision create( + @NonNull GitBranchSCMHead head, @Nullable ObjectId intermediate) + throws IOException, InterruptedException { + return new GitBranchSCMRevision( + head, ref.getValue().name()); + } + }, + new SCMSourceRequest.Witness() { + @Override + public void record( + @NonNull SCMHead head, SCMRevision revision, boolean isMatch) { + if (isMatch) { + listener.getLogger().println(" Met criteria"); + } else { + listener.getLogger().println(" Does not meet criteria"); + } + } + })) { + listener.getLogger().format("Processed %d branches (query complete)%n", count); + return; + } + } + listener.getLogger().format("Processed %d branches%n", count); } - count++; - final String tagName = StringUtils.removeStart(ref.getKey(), Constants.R_TAGS); - RevCommit commit = walk.parseCommit(ref.getValue()); - final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); - if (request.process(new GitTagSCMHead(tagName, lastModified), - new SCMSourceRequest.IntermediateLambda() { - @Nullable - @Override - public ObjectId create() throws IOException, InterruptedException { - listener.getLogger().println(" Checking tag " + tagName); - return ref.getValue(); - } - }, - new SCMSourceRequest.ProbeLambda() { - @NonNull - @Override - public SCMSourceCriteria.Probe create(@NonNull GitTagSCMHead head, - @Nullable ObjectId revisionInfo) - throws IOException, InterruptedException { - RevCommit commit = walk.parseCommit(revisionInfo); - final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); - final RevTree tree = commit.getTree(); - return new TreeWalkingSCMProbe(tagName, lastModified, repository, tree); - } - }, new SCMSourceRequest.LazyRevisionLambda() { - @NonNull - @Override - public GitTagSCMRevision create(@NonNull GitTagSCMHead head, @Nullable ObjectId intermediate) - throws IOException, InterruptedException { - return new GitTagSCMRevision(head, ref.getValue().name()); - } - }, new SCMSourceRequest.Witness() { - @Override - public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { - if (isMatch) { - listener.getLogger().println(" Met criteria"); - } else { - listener.getLogger().println(" Does not meet criteria"); - } - } + + private void discoverTags( + final Repository repository, + final RevWalk walk, + GitSCMSourceRequest request, + Map remoteReferences) + throws IOException, InterruptedException { + listener.getLogger().println("Checking tags..."); + walk.setRetainBody(false); + int count = 0; + for (final Map.Entry ref : remoteReferences.entrySet()) { + if (!ref.getKey().startsWith(Constants.R_TAGS)) { + continue; + } + count++; + final String tagName = StringUtils.removeStart(ref.getKey(), Constants.R_TAGS); + RevCommit commit = walk.parseCommit(ref.getValue()); + final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); + if (request.process( + new GitTagSCMHead(tagName, lastModified), + new SCMSourceRequest.IntermediateLambda() { + @Nullable + @Override + public ObjectId create() throws IOException, InterruptedException { + listener.getLogger().println(" Checking tag " + tagName); + return ref.getValue(); + } + }, + new SCMSourceRequest.ProbeLambda() { + @NonNull + @Override + public SCMSourceCriteria.Probe create( + @NonNull GitTagSCMHead head, @Nullable ObjectId revisionInfo) + throws IOException, InterruptedException { + RevCommit commit = walk.parseCommit(revisionInfo); + final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); + final RevTree tree = commit.getTree(); + return new TreeWalkingSCMProbe(tagName, lastModified, repository, tree); + } + }, + new SCMSourceRequest.LazyRevisionLambda< + GitTagSCMHead, GitTagSCMRevision, ObjectId>() { + @NonNull + @Override + public GitTagSCMRevision create( + @NonNull GitTagSCMHead head, @Nullable ObjectId intermediate) + throws IOException, InterruptedException { + return new GitTagSCMRevision( + head, ref.getValue().name()); + } + }, + new SCMSourceRequest.Witness() { + @Override + public void record( + @NonNull SCMHead head, SCMRevision revision, boolean isMatch) { + if (isMatch) { + listener.getLogger().println(" Met criteria"); + } else { + listener.getLogger().println(" Does not meet criteria"); + } + } + })) { + listener.getLogger().format("Processed %d tags (query complete)%n", count); + return; } - )) { - listener.getLogger().format("Processed %d tags (query complete)%n", count); - return; + } + listener.getLogger().format("Processed %d tags%n", count); } - } - listener.getLogger().format("Processed %d tags%n", count); - } - }, context, listener, true, true); + }, + context, + listener, + true, + true); } /** @@ -816,7 +859,9 @@ public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) */ @CheckForNull @Override - protected SCMRevision retrieve(@NonNull final String revision, @NonNull final TaskListener listener, @CheckForNull Item retrieveContext) throws IOException, InterruptedException { + protected SCMRevision retrieve( + @NonNull final String revision, @NonNull final TaskListener listener, @CheckForNull Item retrieveContext) + throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); @@ -859,9 +904,7 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta listener.getLogger().printf("Attempting to resolve %s from remote references...%n", revision); boolean headsOnly = !context.wantOtherRefs() && context.wantBranches(); boolean tagsOnly = !context.wantOtherRefs() && context.wantTags(); - Map remoteReferences = client.getRemoteReferences( - getRemote(), null, headsOnly, tagsOnly - ); + Map remoteReferences = client.getRemoteReferences(getRemote(), null, headsOnly, tagsOnly); String tagName = null; Set shortNameMatches = new TreeSet<>(); String shortHashMatch = null; @@ -869,11 +912,11 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta Set fullHashMatches = new TreeSet<>(); String fullHashMatch = null; GitRefSCMRevision candidateOtherRef = null; - for (Map.Entry entry: remoteReferences.entrySet()) { + for (Map.Entry entry : remoteReferences.entrySet()) { String name = entry.getKey(); String rev = entry.getValue().name(); if ("HEAD".equals(name)) { - //Skip HEAD as it should only appear during testing, not for standard bare repos iirc + // Skip HEAD as it should only appear during testing, not for standard bare repos iirc continue; } if (name.equals(Constants.R_HEADS + revision)) { @@ -881,7 +924,7 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta // WIN! return new GitBranchSCMRevision(new GitBranchSCMHead(revision), rev); } - if (name.equals(Constants.R_TAGS+revision)) { + if (name.equals(Constants.R_TAGS + revision)) { listener.getLogger().printf("Found match: %s revision %s%n", name, rev); // WIN but not the good kind tagName = revision; @@ -893,7 +936,8 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta if (name.startsWith(Constants.R_HEADS) && revision.equalsIgnoreCase(rev)) { listener.getLogger().printf("Found match: %s revision %s%n", name, rev); // WIN! - return new GitBranchSCMRevision(new GitBranchSCMHead(StringUtils.removeStart(name, Constants.R_HEADS)), rev); + return new GitBranchSCMRevision( + new GitBranchSCMHead(StringUtils.removeStart(name, Constants.R_HEADS)), rev); } if (name.startsWith(Constants.R_TAGS) && revision.equalsIgnoreCase(rev)) { listener.getLogger().printf("Candidate match: %s revision %s%n", name, rev); @@ -901,7 +945,7 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta fullTagMatches.add(name); continue; } - if((Constants.R_REFS + revision.toLowerCase(Locale.ENGLISH)).equals(name.toLowerCase(Locale.ENGLISH))) { + if ((Constants.R_REFS + revision.toLowerCase(Locale.ENGLISH)).equals(name.toLowerCase(Locale.ENGLISH))) { fullHashMatches.add(name); if (fullHashMatch == null) { fullHashMatch = rev; @@ -913,10 +957,11 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta if (fullHashMatch == null) { fullHashMatch = rev; } - //Since it was a full match then the shortMatch below will also match, so just skip it + // Since it was a full match then the shortMatch below will also match, so just skip it continue; } - for (GitSCMSourceContext.RefNameMapping o : (Collection)context.getRefNameMappings()) { + for (GitSCMSourceContext.RefNameMapping o : + (Collection) context.getRefNameMappings()) { if (o.matches(revision, name, rev)) { candidateOtherRef = new GitRefSCMRevision(new GitRefSCMHead(revision, name), rev); break; @@ -944,17 +989,18 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta context.withoutRefSpecs(); } if (fullHashMatch != null) { - //since this would have been skipped if this was a head or a tag we can just return whatever - return new GitRefSCMRevision(new GitRefSCMHead(fullHashMatch, fullHashMatches.iterator().next()), fullHashMatch); + // since this would have been skipped if this was a head or a tag we can just return whatever + return new GitRefSCMRevision( + new GitRefSCMHead(fullHashMatch, fullHashMatches.iterator().next()), fullHashMatch); } if (shortHashMatch != null) { // woot this seems unambiguous - for (String name: shortNameMatches) { + for (String name : shortNameMatches) { if (name.startsWith(Constants.R_HEADS)) { listener.getLogger().printf("Selected match: %s revision %s%n", name, shortHashMatch); // WIN it's also a branch - return new GitBranchSCMRevision(new GitBranchSCMHead(StringUtils.removeStart(name, Constants.R_HEADS)), - shortHashMatch); + return new GitBranchSCMRevision( + new GitBranchSCMHead(StringUtils.removeStart(name, Constants.R_HEADS)), shortHashMatch); } else if (name.startsWith(Constants.R_TAGS)) { tagName = StringUtils.removeStart(name, Constants.R_TAGS); context.wantBranches(false); @@ -965,83 +1011,91 @@ protected SCMRevision retrieve(@NonNull final String revision, @NonNull final Ta if (tagName != null) { listener.getLogger().printf("Selected match: %s revision %s%n", tagName, shortHashMatch); } else { - return new GitRefSCMRevision(new GitRefSCMHead(shortHashMatch, shortNameMatches.iterator().next()), shortHashMatch); + return new GitRefSCMRevision( + new GitRefSCMHead( + shortHashMatch, shortNameMatches.iterator().next()), + shortHashMatch); } } if (candidateOtherRef != null) { return candidateOtherRef; } - //if PruneStaleBranches it should take affect on the following retrievals + // if PruneStaleBranches it should take affect on the following retrievals boolean pruneRefs = context.pruneRefs(); if (tagName != null) { - listener.getLogger().println( - "Resolving tag commit... (remote references may be a lightweight tag or an annotated tag)"); - final String tagRef = Constants.R_TAGS+tagName; - return doRetrieve(new Retriever() { - @Override - public SCMRevision run(GitClient client, String remoteName) throws IOException, - InterruptedException { - try (@SuppressWarnings("deprecation") // Local repo reference - final Repository repository = client.getRepository(); - RevWalk walk = new RevWalk(repository)) { - ObjectId ref = client.revParse(tagRef); - RevCommit commit = walk.parseCommit(ref); - long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); - listener.getLogger().printf("Resolved tag %s revision %s%n", revision, - ref.getName()); - return new GitTagSCMRevision(new GitTagSCMHead(revision, lastModified), - ref.name()); - } - } - }, + listener.getLogger() + .println( + "Resolving tag commit... (remote references may be a lightweight tag or an annotated tag)"); + final String tagRef = Constants.R_TAGS + tagName; + return doRetrieve( + new Retriever() { + @Override + public SCMRevision run(GitClient client, String remoteName) + throws IOException, InterruptedException { + try (@SuppressWarnings("deprecation") // Local repo reference + final Repository repository = client.getRepository(); + RevWalk walk = new RevWalk(repository)) { + ObjectId ref = client.revParse(tagRef); + RevCommit commit = walk.parseCommit(ref); + long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); + listener.getLogger().printf("Resolved tag %s revision %s%n", revision, ref.getName()); + return new GitTagSCMRevision(new GitTagSCMHead(revision, lastModified), ref.name()); + } + } + }, context, - listener, pruneRefs, retrieveContext); + listener, + pruneRefs, + retrieveContext); } // Pokémon!... Got to catch them all - listener.getLogger().printf("Could not find %s in remote references. " - + "Pulling heads to local for deep search...%n", revision); + listener.getLogger() + .printf( + "Could not find %s in remote references. " + "Pulling heads to local for deep search...%n", + revision); context.wantTags(true); context.wantBranches(true); - return doRetrieve(new Retriever() { - @Override - public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { - ObjectId objectId; - String hash; - try { - objectId = client.revParse(revision); - if (objectId == null) { - //just to be safe - listener.error("Could not resolve %s", revision); - return null; - - } - hash = objectId.name(); - String candidatePrefix = Constants.R_REMOTES.substring(Constants.R_REFS.length()) - + context.remoteName() + "/"; - String name = null; - for (Branch b: client.getBranchesContaining(hash, true)) { - if (b.getName().startsWith(candidatePrefix)) { - name = b.getName().substring(candidatePrefix.length()); - break; - } - } - if (name == null) { - listener.getLogger().printf("Could not find a branch containing commit %s%n", - hash); - return null; - } - listener.getLogger() - .printf("Selected match: %s revision %s%n", name, hash); - return new GitBranchSCMRevision(new GitBranchSCMHead(name), hash); - } catch (GitException x) { - x.printStackTrace(listener.error("Could not resolve %s", revision)); - return null; - } - } - }, + return doRetrieve( + new Retriever() { + @Override + public SCMRevision run(GitClient client, String remoteName) + throws IOException, InterruptedException { + ObjectId objectId; + String hash; + try { + objectId = client.revParse(revision); + if (objectId == null) { + // just to be safe + listener.error("Could not resolve %s", revision); + return null; + } + hash = objectId.name(); + String candidatePrefix = Constants.R_REMOTES.substring(Constants.R_REFS.length()) + + context.remoteName() + "/"; + String name = null; + for (Branch b : client.getBranchesContaining(hash, true)) { + if (b.getName().startsWith(candidatePrefix)) { + name = b.getName().substring(candidatePrefix.length()); + break; + } + } + if (name == null) { + listener.getLogger().printf("Could not find a branch containing commit %s%n", hash); + return null; + } + listener.getLogger().printf("Selected match: %s revision %s%n", name, hash); + return new GitBranchSCMRevision(new GitBranchSCMHead(name), hash); + } catch (GitException x) { + x.printStackTrace(listener.error("Could not resolve %s", revision)); + return null; + } + } + }, context, - listener, pruneRefs, retrieveContext); + listener, + pruneRefs, + retrieveContext); } /** @@ -1049,7 +1103,8 @@ public SCMRevision run(GitClient client, String remoteName) throws IOException, */ @NonNull @Override - protected Set retrieveRevisions(@NonNull final TaskListener listener, @CheckForNull Item retrieveContext) throws IOException, InterruptedException { + protected Set retrieveRevisions(@NonNull final TaskListener listener, @CheckForNull Item retrieveContext) + throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); @@ -1087,9 +1142,7 @@ protected Set retrieveRevisions(@NonNull final TaskListener listener, @C listener.getLogger().println("Listing remote references..."); boolean headsOnly = !context.wantOtherRefs() && context.wantBranches(); boolean tagsOnly = !context.wantOtherRefs() && context.wantTags(); - Map remoteReferences = client.getRemoteReferences( - getRemote(), null, headsOnly, tagsOnly - ); + Map remoteReferences = client.getRemoteReferences(getRemote(), null, headsOnly, tagsOnly); for (String name : remoteReferences.keySet()) { if (context.wantBranches()) { if (name.startsWith(Constants.R_HEADS)) { @@ -1101,8 +1154,10 @@ protected Set retrieveRevisions(@NonNull final TaskListener listener, @C revisions.add(StringUtils.removeStart(name, Constants.R_TAGS)); } } - if (context.wantOtherRefs() && (!name.startsWith(Constants.R_HEADS) || !name.startsWith(Constants.R_TAGS))) { - for (GitSCMSourceContext.RefNameMapping o : (Collection)context.getRefNameMappings()) { + if (context.wantOtherRefs() + && (!name.startsWith(Constants.R_HEADS) || !name.startsWith(Constants.R_TAGS))) { + for (GitSCMSourceContext.RefNameMapping o : + (Collection) context.getRefNameMappings()) { if (o.matches(name)) { final String revName = o.getName(name); if (revName != null) { @@ -1174,7 +1229,9 @@ protected List retrieveActions(@CheckForNull SCMSourceEvent event, @NonN ObjectId head = remoteReferences.get(Constants.HEAD); Set names = new TreeSet<>(); for (Map.Entry entry : remoteReferences.entrySet()) { - if (entry.getKey().equals(Constants.HEAD)) continue; + if (entry.getKey().equals(Constants.HEAD)) { + continue; + } if (head.equals(entry.getValue())) { names.add(entry.getKey()); } @@ -1208,11 +1265,12 @@ protected List retrieveActions(@CheckForNull SCMSourceEvent event, @NonN */ @NonNull @Override - protected List retrieveActions(@NonNull SCMHead head, @CheckForNull SCMHeadEvent event, - @NonNull TaskListener listener) throws IOException, InterruptedException { + protected List retrieveActions( + @NonNull SCMHead head, @CheckForNull SCMHeadEvent event, @NonNull TaskListener listener) + throws IOException, InterruptedException { SCMSourceOwner owner = getOwner(); if (owner instanceof Actionable) { - for (GitRemoteHeadRefAction a: ((Actionable) owner).getActions(GitRemoteHeadRefAction.class)) { + for (GitRemoteHeadRefAction a : ((Actionable) owner).getActions(GitRemoteHeadRefAction.class)) { if (getRemote().equals(a.getRemote())) { if (head.getName().equals(a.getName())) { return Collections.singletonList(new PrimaryInstanceMetadataAction()); @@ -1284,12 +1342,13 @@ private StandardUsernameCredentials getCredentials(@CheckForNull Item context) { if (credentialsId == null) { return null; } - return CredentialsMatchers - .firstOrNull( - CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, - ACL.SYSTEM, URIRequirementBuilder.fromUri(getRemote()).build()), - CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), - GitClient.CREDENTIALS_MATCHER)); + return CredentialsMatchers.firstOrNull( + CredentialsProvider.lookupCredentials( + StandardUsernameCredentials.class, + context, + ACL.SYSTEM, + URIRequirementBuilder.fromUri(getRemote()).build()), + CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); } /** @@ -1324,8 +1383,7 @@ protected GitSCMBuilder newBuilder(@NonNull SCMHead head, @CheckForNull SCMRe * * @param builder the builder to decorate. */ - protected void decorate(GitSCMBuilder builder) { - } + protected void decorate(GitSCMBuilder builder) {} /** * {@inheritDoc} @@ -1345,7 +1403,7 @@ public SCM build(@NonNull SCMHead head, @CheckForNull SCMRevision revision) { } if (Util.isOverridden(AbstractGitSCMSource.class, getClass(), "getRefSpecs")) { List specs = new ArrayList<>(); - for (RefSpec spec: getRefSpecs()) { + for (RefSpec spec : getRefSpecs()) { specs.add(spec.toString()); } builder.withoutRefSpecs().withRefSpecs(specs); @@ -1371,10 +1429,10 @@ protected List getRemoteConfigs() { } return result; } - + /** * Returns true if the branchName isn't matched by includes or is matched by excludes. - * + * * @param branchName name of branch to be tested * @return true if branchName is excluded or is not included * @deprecated use {@link WildcardSCMSourceFilterTrait} @@ -1382,33 +1440,34 @@ protected List getRemoteConfigs() { @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") - protected boolean isExcluded (String branchName){ - return !Pattern.matches(getPattern(getIncludes()), branchName) || (Pattern.matches(getPattern(getExcludes()), branchName)); + protected boolean isExcluded(String branchName) { + return !Pattern.matches(getPattern(getIncludes()), branchName) + || (Pattern.matches(getPattern(getExcludes()), branchName)); } - + /** - * Returns the pattern corresponding to the branches containing wildcards. - * + * Returns the pattern corresponding to the branches containing wildcards. + * * @param branches branch names to evaluate * @return pattern corresponding to the branches containing wildcards */ - private String getPattern(String branches){ - StringBuilder quotedBranches = new StringBuilder(); - for (String wildcard : branches.split(" ")){ - StringBuilder quotedBranch = new StringBuilder(); - for(String branch : wildcard.split("(?=[*])|(?<=[*])")){ - if (branch.equals("*")) { - quotedBranch.append(".*"); - } else if (!branch.isEmpty()) { - quotedBranch.append(Pattern.quote(branch)); - } - } - if (quotedBranches.length()>0) { - quotedBranches.append("|"); + private String getPattern(String branches) { + StringBuilder quotedBranches = new StringBuilder(); + for (String wildcard : branches.split(" ")) { + StringBuilder quotedBranch = new StringBuilder(); + for (String branch : wildcard.split("(?=[*])|(?<=[*])")) { + if (branch.equals("*")) { + quotedBranch.append(".*"); + } else if (!branch.isEmpty()) { + quotedBranch.append(Pattern.quote(branch)); + } + } + if (quotedBranches.length() > 0) { + quotedBranches.append("|"); + } + quotedBranches.append(quotedBranch); } - quotedBranches.append(quotedBranch); - } - return quotedBranches.toString(); + return quotedBranches.toString(); } /*package*/ static String getCacheEntry(String remote) { @@ -1449,8 +1508,7 @@ public boolean equals(Object o) { SCMRevisionImpl that = (SCMRevisionImpl) o; - return Objects.equals(hash, that.hash) - && Objects.equals(getHead(), that.getHead()); + return Objects.equals(hash, that.hash) && Objects.equals(getHead(), that.getHead()); } /** @@ -1468,7 +1526,6 @@ public int hashCode() { public String toString() { return hash; } - } public static class SpecificRevisionBuildChooser extends BuildChooser { @@ -1485,9 +1542,13 @@ public SpecificRevisionBuildChooser(SCMRevisionImpl revision) { * {@inheritDoc} */ @Override - public Collection getCandidateRevisions(boolean isPollCall, String singleBranch, GitClient git, - TaskListener listener, BuildData buildData, - BuildChooserContext context) + public Collection getCandidateRevisions( + boolean isPollCall, + String singleBranch, + GitClient git, + TaskListener listener, + BuildData buildData, + BuildChooserContext context) throws GitException, IOException, InterruptedException { return Collections.singleton(revision); } @@ -1496,12 +1557,12 @@ public Collection getCandidateRevisions(boolean isPollCall, String sin * {@inheritDoc} */ @Override - public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitClient git, - BuildChooserContext context) throws IOException, InterruptedException { + public Build prevBuildForChangelog( + String branch, @Nullable BuildData data, GitClient git, BuildChooserContext context) + throws IOException, InterruptedException { // we have ditched that crazy multiple branch stuff from the regular GIT SCM. return data == null ? null : data.lastBuild; } - } /** @@ -1509,11 +1570,13 @@ public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitC * * @since 3.6.1 */ - @SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", - "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", - "NP_LOAD_OF_KNOWN_NULL_VALUE" - }, - justification = "Java 11 generated code causes redundant nullcheck") + @SuppressFBWarnings( + value = { + "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", + "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + "NP_LOAD_OF_KNOWN_NULL_VALUE" + }, + justification = "Java 11 generated code causes redundant nullcheck") private static class TreeWalkingSCMProbe extends SCMProbe { private final String name; private final long lastModified; @@ -1628,8 +1691,8 @@ private static class TelescopingSCMProbe extends SCMProbe { * @param credentials the credentials to use. * @param revision the revision to probe. */ - public TelescopingSCMProbe(GitSCMTelescope telescope, String remote, StandardCredentials credentials, - SCMRevision revision) { + public TelescopingSCMProbe( + GitSCMTelescope telescope, String remote, StandardCredentials credentials, SCMRevision revision) { this.telescope = telescope; this.remote = remote; this.credentials = credentials; diff --git a/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java b/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java index 14ba4feab2..6c9d21fbfc 100644 --- a/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java +++ b/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java @@ -55,7 +55,8 @@ public String toString() { @Restricted(NoExternalUse.class) @Extension - public static class SCMHeadMigrationImpl extends SCMHeadMigration { + public static class SCMHeadMigrationImpl + extends SCMHeadMigration { public SCMHeadMigrationImpl() { super(GitSCMSource.class, SCMHead.class, AbstractGitSCMSource.SCMRevisionImpl.class); @@ -67,7 +68,8 @@ public SCMHead migrate(@NonNull GitSCMSource source, @NonNull SCMHead head) { } @Override - public SCMRevision migrate(@NonNull GitSCMSource source, @NonNull AbstractGitSCMSource.SCMRevisionImpl revision) { + public SCMRevision migrate( + @NonNull GitSCMSource source, @NonNull AbstractGitSCMSource.SCMRevisionImpl revision) { if (revision.getHead().getClass() == SCMHead.class) { SCMHead revisionHead = revision.getHead(); SCMHead branchHead = migrate(source, revisionHead); @@ -79,6 +81,5 @@ public SCMRevision migrate(@NonNull GitSCMSource source, @NonNull AbstractGitSCM } return null; } - } } diff --git a/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java b/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java index 486296f02e..b2a7721ff2 100644 --- a/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java +++ b/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java @@ -24,12 +24,9 @@ */ package jenkins.plugins.git; - public class GitBranchSCMRevision extends AbstractGitSCMSource.SCMRevisionImpl { public GitBranchSCMRevision(GitBranchSCMHead head, String hash) { super(head, hash); } - - } diff --git a/src/main/java/jenkins/plugins/git/GitCredentialBindings.java b/src/main/java/jenkins/plugins/git/GitCredentialBindings.java index 063c9241a7..0deee361ba 100644 --- a/src/main/java/jenkins/plugins/git/GitCredentialBindings.java +++ b/src/main/java/jenkins/plugins/git/GitCredentialBindings.java @@ -11,11 +11,10 @@ import hudson.model.TaskListener; import hudson.plugins.git.GitTool; import hudson.plugins.git.util.GitUtils; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.util.Map; +import org.jenkinsci.plugins.gitclient.GitClient; public interface GitCredentialBindings { @@ -25,7 +24,10 @@ public interface GitCredentialBindings { * @param secretValues The values{@link java.util.Map} to be hidden in build logs * @param publicValues The values{@link java.util.Map} to be visible in build logs **/ - void setCredentialPairBindings(@NonNull StandardCredentials credentials, Map secretValues, Map publicValues); + void setCredentialPairBindings( + @NonNull StandardCredentials credentials, + Map secretValues, + Map publicValues); /** * Set Git specific environment variable @@ -33,7 +35,9 @@ public interface GitCredentialBindings { * @param secretValues The values{@link java.util.Map} to be hidden in build logs * @param publicValues The values{@link java.util.Map} to be visible in build logs **/ - void setGitEnvironmentVariables(@NonNull GitClient git, Map secretValues, Map publicValues) throws IOException, InterruptedException; + void setGitEnvironmentVariables( + @NonNull GitClient git, Map secretValues, Map publicValues) + throws IOException, InterruptedException; /** * Use GitClient to perform git operations in a repository. Using Git implementations JGit/JGit Apache/Cli Git @@ -43,14 +47,14 @@ public interface GitCredentialBindings { * @param listener The task listener. * @return a GitClient implementation {@link org.jenkinsci.plugins.gitclient.GitClient} **/ - GitClient getGitClientInstance(String gitExe, FilePath repository, - EnvVars env, TaskListener listener) throws IOException, InterruptedException; + GitClient getGitClientInstance(String gitExe, FilePath repository, EnvVars env, TaskListener listener) + throws IOException, InterruptedException; /** * Checks the OS environment of the node/controller * @param launcher The launcher.Cannot be null * @return false if current node/controller is not running in windows environment **/ - default boolean isCurrentNodeOSUnix(@NonNull Launcher launcher){ + default boolean isCurrentNodeOSUnix(@NonNull Launcher launcher) { return launcher.isUnix(); } @@ -61,18 +65,20 @@ default boolean isCurrentNodeOSUnix(@NonNull Launcher launcher){ * @param listener The task listener. Cannot be null. * @return A git tool of type GitTool.class {@link hudson.plugins.git.GitTool} or null **/ - default GitTool getCliGitTool(Run run, String gitToolName, - TaskListener listener) throws IOException, InterruptedException { + default GitTool getCliGitTool(Run run, String gitToolName, TaskListener listener) + throws IOException, InterruptedException { Executor buildExecutor = run.getExecutor(); if (buildExecutor != null) { Node currentNode = buildExecutor.getOwner().getNode(); - //Check node is not null + // Check node is not null if (currentNode != null) { - GitTool nameSpecificGitTool = GitUtils.resolveGitTool(gitToolName,currentNode,new EnvVars(),listener); - if(nameSpecificGitTool != null){ - GitTool typeSpecificGitTool = nameSpecificGitTool.getDescriptor().getInstallation(nameSpecificGitTool.getName()); - if(typeSpecificGitTool != null) { + GitTool nameSpecificGitTool = + GitUtils.resolveGitTool(gitToolName, currentNode, new EnvVars(), listener); + if (nameSpecificGitTool != null) { + GitTool typeSpecificGitTool = + nameSpecificGitTool.getDescriptor().getInstallation(nameSpecificGitTool.getName()); + if (typeSpecificGitTool != null) { boolean check = typeSpecificGitTool.getClass().equals(GitTool.class); if (check) { return nameSpecificGitTool; diff --git a/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java b/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java index e170e4225e..9b4fdb47b3 100644 --- a/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java +++ b/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java @@ -29,6 +29,8 @@ import hudson.Functions; import hudson.model.PersistentDescriptor; import hudson.remoting.Channel; +import java.io.IOException; +import java.util.logging.Logger; import jenkins.model.GlobalConfiguration; import jenkins.model.GlobalConfigurationCategory; import org.eclipse.jgit.lib.Repository; @@ -38,12 +40,9 @@ import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; -import java.io.IOException; -import java.util.logging.Logger; - - - -@Extension @Symbol("gitHooks") @Restricted(NoExternalUse.class) +@Extension +@Symbol("gitHooks") +@Restricted(NoExternalUse.class) public class GitHooksConfiguration extends GlobalConfiguration implements PersistentDescriptor { public static final String DISABLED_WIN = "NUL:"; @@ -57,7 +56,8 @@ public class GitHooksConfiguration extends GlobalConfiguration implements Persis public static GitHooksConfiguration get() { final GitHooksConfiguration configuration = GlobalConfiguration.all().get(GitHooksConfiguration.class); if (configuration == null) { - throw new IllegalStateException("[BUG] No configuration registered, make sure not running on an agent or that Jenkins has started properly."); + throw new IllegalStateException( + "[BUG] No configuration registered, make sure not running on an agent or that Jenkins has started properly."); } return configuration; } @@ -80,7 +80,8 @@ public void setAllowedOnAgents(final boolean allowedOnAgents) { save(); } - @Override @NonNull + @Override + @NonNull public GlobalConfigurationCategory getCategory() { return GlobalConfigurationCategory.get(GlobalConfigurationCategory.Security.class); } @@ -90,18 +91,20 @@ public static void configure(GitClient client) throws IOException, InterruptedEx configure(client, configuration.isAllowedOnController(), configuration.isAllowedOnAgents()); } - public static void configure(GitClient client, final boolean allowedOnController, final boolean allowedOnAgents) throws IOException, InterruptedException { + public static void configure(GitClient client, final boolean allowedOnController, final boolean allowedOnAgents) + throws IOException, InterruptedException { if (Channel.current() == null) { - //Running on controller - try (Repository ignored = client.getRepository()){ - //That went well, so the code runs on the controller and the repo is local + // Running on controller + try (Repository ignored = client.getRepository()) { + // That went well, so the code runs on the controller and the repo is local configure(client, allowedOnController); } catch (UnsupportedOperationException e) { - // Client represents a remote repository, so this code runs on the controller but the repo is on an agent + // Client represents a remote repository, so this code runs on the controller but the repo is on an + // agent configure(client, allowedOnAgents); } } else { - //Running on agent + // Running on agent configure(client, allowedOnAgents); } } @@ -124,7 +127,8 @@ private static void unset(final Repository repo) throws IOException { final StoredConfig repoConfig = repo.getConfig(); final String val = repoConfig.getString("core", null, "hooksPath"); if (val != null && !val.isEmpty() && !DISABLED_NIX.equals(val) && !DISABLED_WIN.equals(val)) { - LOGGER.warning(() -> String.format("core.hooksPath explicitly set to %s and will be left intact on %s.", val, repo.getDirectory())); + LOGGER.warning(() -> String.format( + "core.hooksPath explicitly set to %s and will be left intact on %s.", val, repo.getDirectory())); } else { repoConfig.unset("core", null, "hooksPath"); repoConfig.save(); diff --git a/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java b/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java index 4bf85259c0..7d956a2256 100644 --- a/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java +++ b/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java @@ -14,6 +14,7 @@ public class GitRemoteHeadRefAction extends InvisibleAction implements Serializa @NonNull private final String remote; + @NonNull private final String name; @@ -43,8 +44,7 @@ public boolean equals(Object o) { GitRemoteHeadRefAction that = (GitRemoteHeadRefAction) o; - return Objects.equals(remote, that.remote) - && Objects.equals(name, that.name); + return Objects.equals(remote, that.remote) && Objects.equals(name, that.name); } @Override @@ -54,11 +54,6 @@ public int hashCode() { @Override public String toString() { - return "GitRemoteHeadRefAction{" + - "remote='" + remote + '\'' + - ", name='" + name + '\'' + - '}'; + return "GitRemoteHeadRefAction{" + "remote='" + remote + '\'' + ", name='" + name + '\'' + '}'; } - - } diff --git a/src/main/java/jenkins/plugins/git/GitSCMBuilder.java b/src/main/java/jenkins/plugins/git/GitSCMBuilder.java index fbfa2f8d47..bcee71e84f 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMBuilder.java +++ b/src/main/java/jenkins/plugins/git/GitSCMBuilder.java @@ -115,8 +115,11 @@ public class GitSCMBuilder> extends SCMBuilder refSpecs) { public GitSCM build() { List extensions = new ArrayList<>(extensions()); boolean foundClone = false; - for (GitSCMExtension e: extensions) { + for (GitSCMExtension e : extensions) { if (e instanceof CloneOption) { foundClone = true; break; @@ -512,7 +515,8 @@ public GitSCM build() { return new GitSCM( asRemoteConfigs(), Collections.singletonList(new BranchSpec(head().getName())), - browser(), gitTool(), + browser(), + gitTool(), extensions); } @@ -547,10 +551,7 @@ public AdditionalRemote(@NonNull String name, @NonNull String url, @NonNull List this.name = name; this.url = url; this.refSpecs = new ArrayList<>( - refSpecs.isEmpty() - ? Collections.singletonList(AbstractGitSCMSource.REF_SPEC_DEFAULT) - : refSpecs - ); + refSpecs.isEmpty() ? Collections.singletonList(AbstractGitSCMSource.REF_SPEC_DEFAULT) : refSpecs); } /** @@ -599,5 +600,4 @@ public final List asRefSpecs() { return result; } } - } diff --git a/src/main/java/jenkins/plugins/git/GitSCMFile.java b/src/main/java/jenkins/plugins/git/GitSCMFile.java index 9b468d89ac..3c27bd80a0 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMFile.java +++ b/src/main/java/jenkins/plugins/git/GitSCMFile.java @@ -47,11 +47,13 @@ * * @since 3.0.2 */ -@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", - "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", - "NP_LOAD_OF_KNOWN_NULL_VALUE" - }, - justification = "Java 11 generated code causes redundant nullcheck") +@SuppressFBWarnings( + value = { + "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", + "NP_LOAD_OF_KNOWN_NULL_VALUE" + }, + justification = "Java 11 generated code causes redundant nullcheck") public class GitSCMFile extends SCMFile { private final GitSCMFileSystem fs; diff --git a/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java b/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java index a8998fb229..6b10a503a0 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java +++ b/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java @@ -107,15 +107,18 @@ public class GitSCMFileSystem extends SCMFileSystem { * @throws IOException on I/O error * @throws InterruptedException on thread interruption */ - protected GitSCMFileSystem(GitClient client, String remote, final String head, @CheckForNull - AbstractGitSCMSource.SCMRevisionImpl rev) throws IOException, InterruptedException { + protected GitSCMFileSystem( + GitClient client, String remote, final String head, @CheckForNull AbstractGitSCMSource.SCMRevisionImpl rev) + throws IOException, InterruptedException { super(rev); this.remote = remote; this.head = head; cacheEntry = AbstractGitSCMSource.getCacheEntry(remote); listener = new LogTaskListener(LOGGER, Level.FINER); this.client = client; - commitId = rev == null ? invoke((Repository repository) -> repository.findRef(head).getObjectId()) : ObjectId.fromString(rev.getHash()); + commitId = rev == null + ? invoke((Repository repository) -> repository.findRef(head).getObjectId()) + : ObjectId.fromString(rev.getHash()); } @Override @@ -182,7 +185,8 @@ public V invoke(final FSFunction function) throws IOException, Interrupte if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } - return client.withRepository((Repository repository, VirtualChannel virtualChannel) -> function.invoke(repository)); + return client.withRepository( + (Repository repository, VirtualChannel virtualChannel) -> function.invoke(repository)); } finally { cacheLock.unlock(); } @@ -259,14 +263,16 @@ public boolean supports(SCM source) { && ((GitSCM) source).getUserRemoteConfigs().size() == 1 && ((GitSCM) source).getBranches().size() == 1 && !((GitSCM) source).getBranches().get(0).getName().equals("*") // JENKINS-57587 - && ( - ((GitSCM) source).getBranches().get(0).getName().matches( - "^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" - ) - || ((GitSCM) source).getBranches().get(0).getName().matches( - "^((\\Q" + Constants.R_TAGS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" - ) - ); + && (((GitSCM) source) + .getBranches() + .get(0) + .getName() + .matches("^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$") + || ((GitSCM) source) + .getBranches() + .get(0) + .getName() + .matches("^((\\Q" + Constants.R_TAGS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$")); // we only support where the branch spec is obvious and not a wildcard } @@ -294,9 +300,8 @@ private HeadNameResult(String headName, String prefix) { this.prefix = prefix; } - static HeadNameResult calculate(@NonNull BranchSpec branchSpec, - @CheckForNull SCMRevision rev, - @CheckForNull EnvVars env) { + static HeadNameResult calculate( + @NonNull BranchSpec branchSpec, @CheckForNull SCMRevision rev, @CheckForNull EnvVars env) { String branchSpecExpandedName = branchSpec.getName(); if (env != null) { branchSpecExpandedName = env.expand(branchSpecExpandedName); @@ -330,8 +335,8 @@ public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull } @Override - public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev, - @CheckForNull Run _build) + public SCMFileSystem build( + @NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev, @CheckForNull Run _build) throws IOException, InterruptedException { if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) { return null; @@ -369,16 +374,12 @@ public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull if (credentialsId != null) { StandardCredentials credential = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( - StandardUsernameCredentials.class, - owner, - ACL.SYSTEM, - URIRequirementBuilder.fromUri(remote).build() - ), + StandardUsernameCredentials.class, + owner, + ACL.SYSTEM, + URIRequirementBuilder.fromUri(remote).build()), CredentialsMatchers.allOf( - CredentialsMatchers.withId(credentialsId), - GitClient.CREDENTIALS_MATCHER - ) - ); + CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); client.addDefaultCredentials(credential); CredentialsProvider.track(owner, credential); } @@ -387,7 +388,8 @@ public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } - GitHooksConfiguration.configure(client, GitHooksConfiguration.get().isAllowedOnController()); + GitHooksConfiguration.configure( + client, GitHooksConfiguration.get().isAllowedOnController()); String remoteName = StringUtils.defaultIfBlank(config.getName(), Constants.DEFAULT_REMOTE_NAME); listener.getLogger().println("Setting " + remoteName + " to " + remote); client.setRemoteUrl(remoteName, remote); @@ -401,12 +403,21 @@ public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull HeadNameResult headNameResult = HeadNameResult.calculate(branchSpec, rev, env); - client.fetch_().prune(true).from(remoteURI, Collections.singletonList(new RefSpec( - "+" + headNameResult.prefix + headNameResult.headName + ":" + Constants.R_REMOTES + remoteName + "/" - + headNameResult.headName))).execute(); + client.fetch_() + .prune(true) + .from( + remoteURI, + Collections.singletonList( + new RefSpec("+" + headNameResult.prefix + headNameResult.headName + ":" + + Constants.R_REMOTES + remoteName + "/" + headNameResult.headName))) + .execute(); listener.getLogger().println("Done."); - return new GitSCMFileSystem(client, remote, Constants.R_REMOTES + remoteName + "/" + headNameResult.headName, (AbstractGitSCMSource.SCMRevisionImpl) rev); + return new GitSCMFileSystem( + client, + remote, + Constants.R_REMOTES + remoteName + "/" + headNameResult.headName, + (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); } @@ -437,7 +448,8 @@ public SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @Ch listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } - GitHooksConfiguration.configure(client, GitHooksConfiguration.get().isAllowedOnController()); + GitHooksConfiguration.configure( + client, GitHooksConfiguration.get().isAllowedOnController()); String remoteName = builder.remoteName(); listener.getLogger().println("Setting " + remoteName + " to " + gitSCMSource.getRemote()); client.setRemoteUrl(remoteName, gitSCMSource.getRemote()); @@ -448,9 +460,15 @@ public SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @Ch } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } - client.fetch_().prune(true).from(remoteURI, builder.asRefSpecs()).execute(); + client.fetch_() + .prune(true) + .from(remoteURI, builder.asRefSpecs()) + .execute(); listener.getLogger().println("Done."); - return new GitSCMFileSystem(client, gitSCMSource.getRemote(), Constants.R_REMOTES+remoteName+"/"+head.getName(), + return new GitSCMFileSystem( + client, + gitSCMSource.getRemote(), + Constants.R_REMOTES + remoteName + "/" + head.getName(), (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); diff --git a/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java b/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java index 7e80773b2e..00e1af6339 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java +++ b/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java @@ -5,11 +5,10 @@ import hudson.plugins.git.Revision; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; -import org.kohsuke.accmod.Restricted; -import org.kohsuke.accmod.restrictions.NoExternalUse; - import java.util.Collections; import java.util.Set; +import org.kohsuke.accmod.Restricted; +import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Utility methods for integrating with Matrix Project plugin. @@ -23,8 +22,9 @@ public static Set populateCandidatesFromRootBuild(AbstractBuild build, BuildData parentBuildData = scm.getBuildData(parentBuild); if (parentBuildData != null) { Build lastBuild = parentBuildData.lastBuild; - if (lastBuild != null) + if (lastBuild != null) { return Collections.singleton(lastBuild.getMarked()); + } } } return Collections.emptySet(); diff --git a/src/main/java/jenkins/plugins/git/GitSCMSource.java b/src/main/java/jenkins/plugins/git/GitSCMSource.java index a4ecc310bc..755111a8f7 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSource.java @@ -154,7 +154,7 @@ public class GitSCMSource extends AbstractGitSCMSource { @DataBoundConstructor public GitSCMSource(String remote) { - this.remote = remote; + this.remote = remote; } @DataBoundSetter @@ -162,6 +162,7 @@ public void setCredentialsId(@CheckForNull String credentialsId) { this.credentialsId = credentialsId; } + @Override @DataBoundSetter public void setTraits(List traits) { this.traits = SCMTrait.asSetList(traits); @@ -170,7 +171,15 @@ public void setTraits(List traits) { @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") - public GitSCMSource(String id, String remote, String credentialsId, String remoteName, String rawRefSpecs, String includes, String excludes, boolean ignoreOnPushNotifications) { + public GitSCMSource( + String id, + String remote, + String credentialsId, + String remoteName, + String rawRefSpecs, + String includes, + String excludes, + boolean ignoreOnPushNotifications) { super(id); this.remote = remote; this.credentialsId = credentialsId; @@ -195,7 +204,13 @@ public GitSCMSource(String id, String remote, String credentialsId, String remot @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") - public GitSCMSource(String id, String remote, String credentialsId, String includes, String excludes, boolean ignoreOnPushNotifications) { + public GitSCMSource( + String id, + String remote, + String credentialsId, + String includes, + String excludes, + boolean ignoreOnPushNotifications) { this(id, remote, credentialsId, null, null, includes, excludes, ignoreOnPushNotifications); } @@ -221,13 +236,19 @@ protected Object readResolve() throws ObjectStreamException { continue EXTENSIONS; } } catch (UnsupportedOperationException e) { - LOGGER.log(Level.WARNING, - "Could not convert " + extension.getClass().getName() + " to a trait", e); + LOGGER.log( + Level.WARNING, + "Could not convert " + + extension.getClass().getName() + " to a trait", + e); } } } - LOGGER.log(Level.FINE, "Could not convert {0} to a trait (likely because this option does not " - + "make sense for a GitSCMSource)", getClass().getName()); + LOGGER.log( + Level.FINE, + "Could not convert {0} to a trait (likely because this option does not " + + "make sense for a GitSCMSource)", + getClass().getName()); } } } @@ -257,7 +278,7 @@ private RefSpecsSCMSourceTrait asRefSpecsSCMSourceTrait(String rawRefSpecs, Stri Set defaults = new HashSet<>(); defaults.add("+refs/heads/*:refs/remotes/origin/*"); if (remoteName != null) { - defaults.add("+refs/heads/*:refs/remotes/"+remoteName+"/*"); + defaults.add("+refs/heads/*:refs/remotes/" + remoteName + "/*"); } if (!defaults.contains(rawRefSpecs.trim())) { List templates = new ArrayList<>(); @@ -286,7 +307,6 @@ public boolean isIgnoreOnPushNotifications() { return SCMTrait.find(traits, IgnoreOnPushNotificationTrait.class) != null; } - // For Stapler only @Restricted(DoNotUse.class) @DataBoundSetter @@ -332,13 +352,18 @@ public void setExtensions(@CheckForNull List extensions) { continue EXTENSIONS; } } catch (UnsupportedOperationException e) { - LOGGER.log(Level.WARNING, - "Could not convert " + extension.getClass().getName() + " to a trait", e); + LOGGER.log( + Level.WARNING, + "Could not convert " + extension.getClass().getName() + " to a trait", + e); } } } - LOGGER.log(Level.FINE, "Could not convert {0} to a trait (likely because this option does not " - + "make sense for a GitSCMSource)", extension.getClass().getName()); + LOGGER.log( + Level.FINE, + "Could not convert {0} to a trait (likely because this option does not " + + "make sense for a GitSCMSource)", + extension.getClass().getName()); } } setTraits(traits); @@ -349,6 +374,7 @@ public String getCredentialsId() { return credentialsId; } + @Override public String getRemote() { return remote; } @@ -362,19 +388,23 @@ public String getRawRefSpecs() { for (SCMSourceTrait trait : traits) { if (trait instanceof RemoteNameSCMSourceTrait) { remoteName = ((RemoteNameSCMSourceTrait) trait).getRemoteName(); - if (refSpecs != null) break; + if (refSpecs != null) { + break; + } } if (trait instanceof RefSpecsSCMSourceTrait) { refSpecs = (RefSpecsSCMSourceTrait) trait; - if (remoteName != null) break; + if (remoteName != null) { + break; + } } } if (remoteName == null) { remoteName = AbstractGitSCMSource.DEFAULT_REMOTE_NAME; } if (refSpecs == null) { - return AbstractGitSCMSource.REF_SPEC_DEFAULT - .replaceAll(AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER, remoteName); + return AbstractGitSCMSource.REF_SPEC_DEFAULT.replaceAll( + AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER, remoteName); } StringBuilder result = new StringBuilder(); boolean first = true; @@ -395,7 +425,9 @@ public String getRawRefSpecs() { @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected List getRefSpecs() { - return new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(traits).asRefSpecs(); + return new GitSCMSourceContext<>(null, SCMHeadObserver.none()) + .withTraits(traits) + .asRefSpecs(); } @NonNull @@ -413,17 +445,18 @@ public String getDisplayName() { return Messages.GitSCMSource_DisplayName(); } - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, - @QueryParameter String remote, - @QueryParameter String credentialsId) { - if (context == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) || - context != null && !context.hasPermission(Item.EXTENDED_READ)) { + public ListBoxModel doFillCredentialsIdItems( + @AncestorInPath Item context, @QueryParameter String remote, @QueryParameter String credentialsId) { + if (context == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) + || context != null && !context.hasPermission(Item.EXTENDED_READ)) { return new StandardListBoxModel().includeCurrentValue(credentialsId); } return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( - context instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task)context) : ACL.SYSTEM, + context instanceof Queue.Task + ? Tasks.getAuthenticationOf((Queue.Task) context) + : ACL.SYSTEM, context, StandardUsernameCredentials.class, URIRequirementBuilder.fromUri(remote).build(), @@ -431,11 +464,10 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, .includeCurrentValue(credentialsId); } - public FormValidation doCheckCredentialsId(@AncestorInPath Item context, - @QueryParameter String remote, - @QueryParameter String value) { - if (context == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) || - context != null && !context.hasPermission(Item.EXTENDED_READ)) { + public FormValidation doCheckCredentialsId( + @AncestorInPath Item context, @QueryParameter String remote, @QueryParameter String value) { + if (context == null && !Jenkins.get().hasPermission(Jenkins.ADMINISTER) + || context != null && !context.hasPermission(Item.EXTENDED_READ)) { return FormValidation.ok(); } @@ -454,9 +486,7 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item context, for (ListBoxModel.Option o : CredentialsProvider.listCredentials( StandardUsernameCredentials.class, context, - context instanceof Queue.Task - ? Tasks.getAuthenticationOf((Queue.Task) context) - : ACL.SYSTEM, + context instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) context) : ACL.SYSTEM, URIRequirementBuilder.fromUri(remote).build(), GitClient.CREDENTIALS_MATCHER)) { if (Objects.equals(value, o.value)) { @@ -475,7 +505,7 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item context, @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public GitSCM.DescriptorImpl getSCMDescriptor() { - return (GitSCM.DescriptorImpl)Jenkins.getActiveInstance().getDescriptor(GitSCM.class); + return (GitSCM.DescriptorImpl) Jenkins.getActiveInstance().getDescriptor(GitSCM.class); } @Deprecated @@ -510,16 +540,19 @@ public List> getTraitsDescrip List> result = new ArrayList<>(); List descriptors = SCMSourceTrait._for(this, GitSCMSourceContext.class, GitSCMBuilder.class); - NamedArrayList.select(descriptors, Messages.within_Repository(), + NamedArrayList.select( + descriptors, + Messages.within_Repository(), NamedArrayList.anyOf( NamedArrayList.withAnnotation(Selection.class), - NamedArrayList.withAnnotation(Discovery.class) - ), - true, result); + NamedArrayList.withAnnotation(Discovery.class)), + true, + result); NamedArrayList.select(descriptors, Messages.additional(), null, true, result); return result; } + @Override public List getTraitsDefaults() { return Collections.singletonList(new BranchDiscoveryTrait()); } @@ -527,18 +560,19 @@ public List getTraitsDefaults() { @NonNull @Override protected SCMHeadCategory[] createCategories() { - return new SCMHeadCategory[]{UncategorizedSCMHeadCategory.DEFAULT, TagSCMHeadCategory.DEFAULT}; + return new SCMHeadCategory[] {UncategorizedSCMHeadCategory.DEFAULT, TagSCMHeadCategory.DEFAULT}; } } @Extension public static class ListenerImpl extends GitStatus.Listener { @Override - public List onNotifyCommit(String origin, - URIish uri, - @Nullable final String sha1, - List buildParameters, - String... branches) { + public List onNotifyCommit( + String origin, + URIish uri, + @Nullable final String sha1, + List buildParameters, + String... branches) { List result = new ArrayList<>(); final boolean notified[] = {false}; // run in high privilege to see all the projects anonymous users don't see. @@ -547,8 +581,8 @@ public List onNotifyCommit(String origin, try (ACLContext context = ACL.as(ACL.SYSTEM)) { if (branches.length > 0) { final URIish u = uri; - for (final String branch: branches) { - SCMHeadEvent.fireNow(new SCMHeadEvent(SCMEvent.Type.UPDATED, branch, origin){ + for (final String branch : branches) { + SCMHeadEvent.fireNow(new SCMHeadEvent(SCMEvent.Type.UPDATED, branch, origin) { @Override public boolean isMatch(@NonNull SCMNavigator navigator) { return false; @@ -565,9 +599,8 @@ public String getSourceName() { public boolean isMatch(SCMSource source) { if (source instanceof GitSCMSource) { GitSCMSource git = (GitSCMSource) source; - GitSCMSourceContext ctx = - new GitSCMSourceContext<>(null, SCMHeadObserver.none()) - .withTraits(git.getTraits()); + GitSCMSourceContext ctx = new GitSCMSourceContext<>(null, SCMHeadObserver.none()) + .withTraits(git.getTraits()); if (ctx.ignoreOnPushNotifications()) { return false; } @@ -592,9 +625,9 @@ public boolean isMatch(SCMSource source) { public Map heads(@NonNull SCMSource source) { if (source instanceof GitSCMSource) { GitSCMSource git = (GitSCMSource) source; - GitSCMSourceContext ctx = - new GitSCMSourceContext<>(null, SCMHeadObserver.none()) - .withTraits(git.getTraits()); + GitSCMSourceContext ctx = new GitSCMSourceContext<>( + null, SCMHeadObserver.none()) + .withTraits(git.getTraits()); if (ctx.ignoreOnPushNotifications()) { return Collections.emptyMap(); } @@ -607,13 +640,13 @@ public Map heads(@NonNull SCMSource source) { } if (GitStatus.looselyMatches(u, remote)) { GitBranchSCMHead head = new GitBranchSCMHead(branch); - for (SCMHeadPrefilter filter: ctx.prefilters()) { + for (SCMHeadPrefilter filter : ctx.prefilters()) { if (filter.isExcluded(git, head)) { return Collections.emptyMap(); } } - return Collections.singletonMap(head, - sha1 != null ? new GitBranchSCMRevision(head, sha1) : null); + return Collections.singletonMap( + head, sha1 != null ? new GitBranchSCMRevision(head, sha1) : null); } } return Collections.emptyMap(); @@ -630,9 +663,8 @@ public boolean isMatch(@NonNull SCM scm) { for (SCMSource source : owner.getSCMSources()) { if (source instanceof GitSCMSource) { GitSCMSource git = (GitSCMSource) source; - GitSCMSourceContext ctx = - new GitSCMSourceContext<>(null, SCMHeadObserver.none()) - .withTraits(git.getTraits()); + GitSCMSourceContext ctx = new GitSCMSourceContext<>(null, SCMHeadObserver.none()) + .withTraits(git.getTraits()); if (ctx.ignoreOnPushNotifications()) { continue; } @@ -651,7 +683,8 @@ public boolean isMatch(@NonNull SCM scm) { @Override @SuppressWarnings("deprecation") public void addHeaders(StaplerRequest req, StaplerResponse rsp) { - // Calls a deprecated getAbsoluteUrl() method because this is a remote API case + // Calls a deprecated getAbsoluteUrl() method because this is a remote API + // case // as described in the Javadoc of the deprecated getAbsoluteUrl() method. rsp.addHeader("Triggered", owner.getAbsoluteUrl()); } @@ -669,7 +702,8 @@ public void writeBody(PrintWriter w) { } } if (!notified[0]) { - result.add(new GitStatus.MessageResponseContributor("No Git consumers using SCM API plugin for: " + uri.toString())); + result.add(new GitStatus.MessageResponseContributor( + "No Git consumers using SCM API plugin for: " + uri.toString())); } return result; } diff --git a/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java b/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java index 494d027d2f..dbff593332 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java @@ -39,7 +39,6 @@ import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; - import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceCriteria; @@ -346,14 +345,13 @@ public final C withRemoteName(String remoteName) { public final List asRefSpecs() { List result = new ArrayList<>(Math.max(refSpecs.size(), 1)); if (wantOtherRefs() && wantBranches()) { - //If wantOtherRefs() there will be a refspec in the list not added manually by a user - //So if also wantBranches() we need to add the default respec for branches so we actually fetch them + // If wantOtherRefs() there will be a refspec in the list not added manually by a user + // So if also wantBranches() we need to add the default respec for branches so we actually fetch them result.add(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + remoteName() + "/*")); } for (String template : refSpecs()) { result.add(new RefSpec( - template.replaceAll(AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER, remoteName()) - )); + template.replaceAll(AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER, remoteName()))); } return result; } @@ -406,8 +404,7 @@ public boolean equals(Object o) { RefNameMapping that = (RefNameMapping) o; - return Objects.equals(ref, that.ref) - && Objects.equals(name, that.name); + return Objects.equals(ref, that.ref) && Objects.equals(name, that.name); } @Override @@ -423,8 +420,8 @@ public int compareTo(RefNameMapping o) { public boolean matches(String revision, String remoteName, String remoteRev) { final Matcher matcher = refAsPattern().matcher(remoteName); if (matcher.matches()) { - //TODO support multiple capture groups? - if (matcher.groupCount() > 0) { //Group 0 apparently not in this count according to javadoc + // TODO support multiple capture groups? + if (matcher.groupCount() > 0) { // Group 0 apparently not in this count according to javadoc String resolvedName = name.replace("@{1}", matcher.group(1)); return resolvedName.equals(revision); } else { @@ -442,7 +439,7 @@ public boolean matches(String remoteName) { public String getName(String remoteName) { final Matcher matcher = refAsPattern().matcher(remoteName); if (matcher.matches()) { - if (matcher.groupCount() > 0) { //Group 0 apparently not in this count according to javadoc + if (matcher.groupCount() > 0) { // Group 0 apparently not in this count according to javadoc return name.replace("@{1}", matcher.group(1)); } else if (!name.contains("@{1}")) { return name; @@ -451,5 +448,4 @@ public String getName(String remoteName) { return null; } } - } diff --git a/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java b/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java index 3d03df8ffb..4050728aaa 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java @@ -96,17 +96,16 @@ public int hashCode() { */ @Override public String toString() { - return "GitSCMSourceDefaults{" + - "includeTags=" + includeTags + - '}'; + return "GitSCMSourceDefaults{" + "includeTags=" + includeTags + '}'; } /** * {@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 { listener.getLogger() .printf("Cloning with configured refspecs honoured and %s tags%n", includeTags ? "with" : "without"); RemoteConfig rc = scm.getRepositories().get(0); @@ -122,8 +121,7 @@ public void decorateCloneCommand(GitSCM scm, Run build, GitClient git, Tas @Deprecated public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listener, FetchCommand cmd) throws IOException, InterruptedException, GitException { - listener.getLogger() - .printf("Fetching %s tags%n", includeTags ? "with" : "without"); + listener.getLogger().printf("Fetching %s tags%n", includeTags ? "with" : "without"); cmd.tags(includeTags); } } diff --git a/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java b/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java index 5262567c19..ff6d4ea6e7 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java @@ -61,7 +61,8 @@ public class GitSCMSourceRequest extends SCMSourceRequest { * @param context the context. * @param listener the (optional) {@link TaskListener}. */ - public GitSCMSourceRequest(@NonNull SCMSource source, @NonNull GitSCMSourceContext context, TaskListener listener) { + public GitSCMSourceRequest( + @NonNull SCMSource source, @NonNull GitSCMSourceContext context, TaskListener listener) { super(source, context, listener); remoteName = context.remoteName(); gitTool = context.gitTool(); @@ -88,7 +89,6 @@ public final String remoteName() { return remoteName; } - /** * Returns the list of {@link RefSpec} instances to use. * diff --git a/src/main/java/jenkins/plugins/git/GitSCMTelescope.java b/src/main/java/jenkins/plugins/git/GitSCMTelescope.java index 44492fe3cc..2688a01e19 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMTelescope.java +++ b/src/main/java/jenkins/plugins/git/GitSCMTelescope.java @@ -61,7 +61,7 @@ * @since 3.6.1 */ public abstract class GitSCMTelescope extends SCMFileSystem.Builder { - //TODO JENKINS-51134 DiscoverOtherRefsTrait + // TODO JENKINS-51134 DiscoverOtherRefsTrait /** * Returns the {@link GitSCMTelescope} to use for the specified {@link GitSCM} or {@code null} if none match. @@ -140,9 +140,9 @@ public final boolean supports(@NonNull SCM source) { if (configs.size() == 1) { String remote = configs.get(0).getUrl(); return remote != null - && supports(remote) - && branches.size() == 1 - && !branches.get(0).getName().contains("*"); + && supports(remote) + && branches.size() == 1 + && !branches.get(0).getName().contains("*"); } } return false; @@ -153,8 +153,9 @@ && supports(remote) */ @Override public final boolean supports(@NonNull SCMSource source) { - return source instanceof AbstractGitSCMSource && source.getOwner() != null && supports( - ((AbstractGitSCMSource) source).getRemote()); + return source instanceof AbstractGitSCMSource + && source.getOwner() != null + && supports(((AbstractGitSCMSource) source).getRemote()); } /** @@ -164,8 +165,9 @@ public final boolean supports(@NonNull SCMSource source) { public final SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision rev) throws IOException, InterruptedException { SCMSourceOwner owner = source.getOwner(); - if (source instanceof AbstractGitSCMSource && owner != null && supports( - ((AbstractGitSCMSource) source).getRemote())) { + if (source instanceof AbstractGitSCMSource + && owner != null + && supports(((AbstractGitSCMSource) source).getRemote())) { AbstractGitSCMSource git = (AbstractGitSCMSource) source; String remote = git.getRemote(); StandardUsernameCredentials credentials = git.getCredentials(); @@ -189,21 +191,24 @@ public final SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, SCMRevis if (configs.size() == 1) { UserRemoteConfig config = configs.get(0); String remote = config.getUrl(); - if (remote != null && supports(remote) - && branches.size() == 1 && !branches.get(0).getName().contains("*")) { + if (remote != null + && supports(remote) + && branches.size() == 1 + && !branches.get(0).getName().contains("*")) { StandardCredentials credentials; String credentialsId = config.getCredentialsId(); if (credentialsId != null) { - List urlCredentials = CredentialsProvider - .lookupCredentials(StandardUsernameCredentials.class, owner, - owner instanceof Queue.Task - ? Tasks.getAuthenticationOf((Queue.Task) owner) - : ACL.SYSTEM, URIRequirementBuilder.fromUri(remote).build()); + List urlCredentials = CredentialsProvider.lookupCredentials( + StandardUsernameCredentials.class, + owner, + owner instanceof Queue.Task + ? Tasks.getAuthenticationOf((Queue.Task) owner) + : ACL.SYSTEM, + URIRequirementBuilder.fromUri(remote).build()); credentials = CredentialsMatchers.firstOrNull( urlCredentials, - CredentialsMatchers - .allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER) - ); + CredentialsMatchers.allOf( + CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); } else { credentials = null; } @@ -213,14 +218,13 @@ public final SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, SCMRevis String name = branches.get(0).getName(); if (name.startsWith(Constants.R_TAGS)) { head = new GitTagSCMHead( - name.substring(Constants.R_TAGS.length()), - getTimestamp(remote, credentials, name) - ); + name.substring(Constants.R_TAGS.length()), getTimestamp(remote, credentials, name)); } else if (name.startsWith(Constants.R_HEADS)) { head = new GitBranchSCMHead(name.substring(Constants.R_HEADS.length())); } else { if (name.startsWith(config.getName() + "/")) { - head = new GitBranchSCMHead(name.substring(config.getName().length() + 1)); + head = new GitBranchSCMHead( + name.substring(config.getName().length() + 1)); } else { head = new GitBranchSCMHead(name); } @@ -252,8 +256,11 @@ public final SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, SCMRevis * @throws InterruptedException if the attempt to create a {@link SCMFileSystem} was interrupted. */ @CheckForNull - protected abstract SCMFileSystem build(@NonNull String remote, @CheckForNull StandardCredentials credentials, - @NonNull SCMHead head, @CheckForNull SCMRevision rev) + protected abstract SCMFileSystem build( + @NonNull String remote, + @CheckForNull StandardCredentials credentials, + @NonNull SCMHead head, + @CheckForNull SCMRevision rev) throws IOException, InterruptedException; /** @@ -267,8 +274,9 @@ protected abstract SCMFileSystem build(@NonNull String remote, @CheckForNull Sta * @throws IOException if the operation failed due to an IO error. * @throws InterruptedException if the operation was interrupted. */ - public abstract long getTimestamp(@NonNull String remote, @CheckForNull StandardCredentials credentials, - @NonNull String refOrHash) throws IOException, InterruptedException; + public abstract long getTimestamp( + @NonNull String remote, @CheckForNull StandardCredentials credentials, @NonNull String refOrHash) + throws IOException, InterruptedException; /** * Retrieves the current revision of the specified reference or object hash. @@ -282,9 +290,8 @@ public abstract long getTimestamp(@NonNull String remote, @CheckForNull Standard * @throws InterruptedException if the operation was interrupted. */ @CheckForNull - public abstract SCMRevision getRevision(@NonNull String remote, - @CheckForNull StandardCredentials credentials, - @NonNull String refOrHash) + public abstract SCMRevision getRevision( + @NonNull String remote, @CheckForNull StandardCredentials credentials, @NonNull String refOrHash) throws IOException, InterruptedException; /** @@ -297,8 +304,9 @@ public abstract SCMRevision getRevision(@NonNull String remote, * @throws IOException if the operation failed due to an IO error. * @throws InterruptedException if the operation was interrupted. */ - public long getTimestamp(@NonNull String remote, @CheckForNull StandardCredentials credentials, - @NonNull SCMHead head) throws IOException, InterruptedException { + public long getTimestamp( + @NonNull String remote, @CheckForNull StandardCredentials credentials, @NonNull SCMHead head) + throws IOException, InterruptedException { if ((head instanceof TagSCMHead)) { return getTimestamp(remote, credentials, Constants.R_TAGS + head.getName()); } else { @@ -317,9 +325,8 @@ public long getTimestamp(@NonNull String remote, @CheckForNull StandardCredentia * @throws InterruptedException if the operation was interrupted. */ @CheckForNull - public SCMRevision getRevision(@NonNull String remote, - @CheckForNull StandardCredentials credentials, - @NonNull SCMHead head) + public SCMRevision getRevision( + @NonNull String remote, @CheckForNull StandardCredentials credentials, @NonNull SCMHead head) throws IOException, InterruptedException { if ((head instanceof TagSCMHead)) { return getRevision(remote, credentials, Constants.R_TAGS + head.getName()); @@ -337,8 +344,8 @@ public SCMRevision getRevision(@NonNull String remote, * @throws IOException if the operation failed due to an IO error. * @throws InterruptedException if the operation was interrupted. */ - public final Iterable getRevisions(@NonNull String remote, - @CheckForNull StandardCredentials credentials) + public final Iterable getRevisions( + @NonNull String remote, @CheckForNull StandardCredentials credentials) throws IOException, InterruptedException { return getRevisions(remote, credentials, EnumSet.allOf(ReferenceType.class)); } @@ -353,9 +360,10 @@ public final Iterable getRevisions(@NonNull String remote, * @throws IOException if the operation failed due to an IO error. * @throws InterruptedException if the operation was interrupted. */ - public abstract Iterable getRevisions(@NonNull String remote, - @CheckForNull StandardCredentials credentials, - @NonNull Set referenceTypes) + public abstract Iterable getRevisions( + @NonNull String remote, + @CheckForNull StandardCredentials credentials, + @NonNull Set referenceTypes) throws IOException, InterruptedException; /** @@ -367,8 +375,7 @@ public abstract Iterable getRevisions(@NonNull String remote, * @throws IOException if the operation failed due to an IO error. * @throws InterruptedException if the operation was interrupted. */ - public abstract String getDefaultTarget(@NonNull String remote, - @CheckForNull StandardCredentials credentials) + public abstract String getDefaultTarget(@NonNull String remote, @CheckForNull StandardCredentials credentials) throws IOException, InterruptedException; /** diff --git a/src/main/java/jenkins/plugins/git/GitStep.java b/src/main/java/jenkins/plugins/git/GitStep.java index 67cf84c371..8fb8fd9145 100644 --- a/src/main/java/jenkins/plugins/git/GitStep.java +++ b/src/main/java/jenkins/plugins/git/GitStep.java @@ -82,7 +82,12 @@ public void setCredentialsId(String credentialsId) { @Override public SCM createSCM() { - return new GitSCM(GitSCM.createRepoList(url, credentialsId), Collections.singletonList(new BranchSpec("*/" + branch)), null, null, Collections.singletonList(new LocalBranch(branch))); + return new GitSCM( + GitSCM.createRepoList(url, credentialsId), + Collections.singletonList(new BranchSpec("*/" + branch)), + null, + null, + Collections.singletonList(new LocalBranch(branch))); } @Extension @@ -91,16 +96,15 @@ public static final class DescriptorImpl extends SCMStepDescriptor { @Inject private UserRemoteConfig.DescriptorImpl delegate; - public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project, - @QueryParameter String url, - @QueryParameter String credentialsId) { + public ListBoxModel doFillCredentialsIdItems( + @AncestorInPath Item project, @QueryParameter String url, @QueryParameter String credentialsId) { return delegate.doFillCredentialsIdItems(project, url, credentialsId); } @RequirePOST - public FormValidation doCheckUrl(@AncestorInPath Item item, - @QueryParameter String credentialsId, - @QueryParameter String value) throws IOException, InterruptedException { + public FormValidation doCheckUrl( + @AncestorInPath Item item, @QueryParameter String credentialsId, @QueryParameter String value) + throws IOException, InterruptedException { return delegate.doCheckUrl(item, credentialsId, value); } @@ -113,7 +117,5 @@ public String getFunctionName() { public String getDisplayName() { return Messages.GitStep_git(); } - } - } diff --git a/src/main/java/jenkins/plugins/git/GitTagSCMHead.java b/src/main/java/jenkins/plugins/git/GitTagSCMHead.java index 07512cd636..5232fc9664 100644 --- a/src/main/java/jenkins/plugins/git/GitTagSCMHead.java +++ b/src/main/java/jenkins/plugins/git/GitTagSCMHead.java @@ -58,5 +58,4 @@ public GitTagSCMHead(@NonNull String name, long timestamp) { public long getTimestamp() { return timestamp; } - } diff --git a/src/main/java/jenkins/plugins/git/GitToolChooser.java b/src/main/java/jenkins/plugins/git/GitToolChooser.java index ef71ba783c..639c6b54b8 100644 --- a/src/main/java/jenkins/plugins/git/GitToolChooser.java +++ b/src/main/java/jenkins/plugins/git/GitToolChooser.java @@ -9,13 +9,6 @@ import hudson.model.TaskListener; import hudson.plugins.git.GitTool; import hudson.plugins.git.util.GitUtils; -import jenkins.model.Jenkins; -import org.apache.commons.io.FileUtils; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; -import org.jenkinsci.plugins.gitclient.JGitApacheTool; -import org.jenkinsci.plugins.gitclient.JGitTool; - import java.io.File; import java.io.IOException; import java.util.*; @@ -25,6 +18,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import jenkins.model.Jenkins; +import org.apache.commons.io.FileUtils; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; +import org.jenkinsci.plugins.gitclient.JGitApacheTool; +import org.jenkinsci.plugins.gitclient.JGitTool; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; @@ -43,6 +42,7 @@ public class GitToolChooser { * Size to switch implementation in KiB */ private static final int SIZE_TO_SWITCH = 5000; + private boolean JGIT_SUPPORTED = false; /** Cache of repository sizes based on remoteURL. **/ @@ -61,8 +61,15 @@ public class GitToolChooser { * @throws IOException on error * @throws InterruptedException on error */ - public GitToolChooser(String remoteName, Item projectContext, String credentialsId, - GitTool gitExe, Node n, TaskListener listener, Boolean useJGit) throws IOException, InterruptedException { + public GitToolChooser( + String remoteName, + Item projectContext, + String credentialsId, + GitTool gitExe, + Node n, + TaskListener listener, + Boolean useJGit) + throws IOException, InterruptedException { boolean useCache = false; if (useJGit != null) { JGIT_SUPPORTED = useJGit; @@ -90,9 +97,7 @@ public GitToolChooser(String remoteName, Item projectContext, String credentials private boolean decideAndUseCache(String remoteName) throws IOException, InterruptedException { boolean useCache = false; if (setSizeFromInternalCache(remoteName)) { - LOGGER.log(Level.FINE, - "Found cache key for {0} with size {1}", - new Object[]{remoteName, sizeOfRepo}); + LOGGER.log(Level.FINE, "Found cache key for {0} with size {1}", new Object[] {remoteName, sizeOfRepo}); useCache = true; return useCache; } @@ -100,29 +105,38 @@ private boolean decideAndUseCache(String remoteName) throws IOException, Interru String cacheEntry = AbstractGitSCMSource.getCacheEntry(repoUrl); File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry, false); if (cacheDir != null) { - Git git = Git.with(TaskListener.NULL, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir).using("git"); + Git git = Git.with(TaskListener.NULL, new EnvVars(EnvVars.masterEnvVars)) + .in(cacheDir) + .using("git"); GitClient client = git.getClient(); if (client.hasGitRepo(false)) { - long clientRepoSize = FileUtils.sizeOfDirectory(cacheDir) / 1024; // Conversion from Bytes to Kilo Bytes + long clientRepoSize = + FileUtils.sizeOfDirectory(cacheDir) / 1024; // Conversion from Bytes to Kilo Bytes if (clientRepoSize > sizeOfRepo) { if (sizeOfRepo > 0) { - LOGGER.log(Level.FINE, "Replacing prior size estimate {0} with new size estimate {1} for remote {2} from cache {3}", - new Object[]{sizeOfRepo, clientRepoSize, remoteName, cacheDir}); + LOGGER.log( + Level.FINE, + "Replacing prior size estimate {0} with new size estimate {1} for remote {2} from cache {3}", + new Object[] {sizeOfRepo, clientRepoSize, remoteName, cacheDir}); } sizeOfRepo = clientRepoSize; assignSizeToInternalCache(remoteName, sizeOfRepo); } useCache = true; if (remoteName.equals(repoUrl)) { - LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}", - new Object[]{remoteName, cacheDir, sizeOfRepo}); + LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}", new Object[] { + remoteName, cacheDir, sizeOfRepo + }); } else { - LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}, alternative URL {3}", - new Object[]{remoteName, cacheDir, sizeOfRepo, repoUrl}); + LOGGER.log( + Level.FINE, + "Remote URL {0} found cache {1} with size {2}, alternative URL {3}", + new Object[] {remoteName, cacheDir, sizeOfRepo, repoUrl}); } } else { // Log the surprise but continue looking for a cache - LOGGER.log(Level.FINE, "Remote URL {0} cache {1} has no git dir", new Object[]{remoteName, cacheDir}); + LOGGER.log( + Level.FINE, "Remote URL {0} cache {1} has no git dir", new Object[] {remoteName, cacheDir}); } } } @@ -177,16 +191,15 @@ private String addSuffix(@NonNull String canonicalURL) { * Varies the protocol (https, git, ssh) and the suffix of the repository URL. * Package protected for testing */ - /* package */ @NonNull String convertToCanonicalURL(String remoteURL) { + /* package */ @NonNull + String convertToCanonicalURL(String remoteURL) { if (remoteURL == null || remoteURL.isEmpty()) { LOGGER.log(Level.FINE, "Null or empty remote URL not cached"); return ""; // return an empty string } - Pattern [] protocolPatterns = { - sshAltProtocolPattern, - sshProtocolPattern, - gitProtocolPattern, + Pattern[] protocolPatterns = { + sshAltProtocolPattern, sshProtocolPattern, gitProtocolPattern, }; String matcherReplacement = "https://$1/$2"; @@ -196,7 +209,7 @@ private String addSuffix(@NonNull String canonicalURL) { if (httpProtocolPattern.matcher(remoteURL).matches()) { canonicalURL = remoteURL; } else { - for (Pattern protocolPattern: protocolPatterns) { + for (Pattern protocolPattern : protocolPatterns) { Matcher protocolMatcher = protocolPattern.matcher(remoteURL); if (protocolMatcher.matches()) { canonicalURL = protocolMatcher.replaceAll(matcherReplacement); @@ -222,25 +235,23 @@ private boolean setSizeFromInternalCache(String repoURL) { * Varies the protocol (https, git, ssh) and the suffix of the repository URL. * Package protected for testing */ - /* package */ @NonNull Set remoteAlternatives(String remoteURL) { + /* package */ @NonNull + Set remoteAlternatives(String remoteURL) { Set alternatives = new LinkedHashSet<>(); if (remoteURL == null || remoteURL.isEmpty()) { LOGGER.log(Level.FINE, "Null or empty remote URL not cached"); return alternatives; } - Pattern [] protocolPatterns = { - gitProtocolPattern, - httpProtocolPattern, - sshAltProtocolPattern, - sshProtocolPattern, + Pattern[] protocolPatterns = { + gitProtocolPattern, httpProtocolPattern, sshAltProtocolPattern, sshProtocolPattern, }; String[] matcherReplacements = { - "git://$1/$2", // git protocol - "git@$1:$2", // ssh protocol alternate URL - "https://$1/$2", // https protocol - "ssh://git@$1/$2", // ssh protocol + "git://$1/$2", // git protocol + "git@$1:$2", // ssh protocol alternate URL + "https://$1/$2", // https protocol + "ssh://git@$1/$2", // ssh protocol }; /* For each matching protocol, form alternatives by iterating over replacements */ @@ -272,13 +283,17 @@ private void assignSizeToInternalCache(String repoURL, long repoSize) { if (repositorySizeCache.containsKey(repoURL)) { long oldSize = repositorySizeCache.get(repoURL); if (oldSize < repoSize) { - LOGGER.log(Level.FINE, "Replacing old repo size {0} with new size {1} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); + LOGGER.log(Level.FINE, "Replacing old repo size {0} with new size {1} for repo {2}", new Object[] { + oldSize, repoSize, repoURL + }); repositorySizeCache.put(repoURL, repoSize); } else if (oldSize > repoSize) { - LOGGER.log(Level.FINE, "Ignoring new size {1} in favor of old size {0} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); + LOGGER.log(Level.FINE, "Ignoring new size {1} in favor of old size {0} for repo {2}", new Object[] { + oldSize, repoSize, repoURL + }); } } else { - LOGGER.log(Level.FINE, "Caching repo size {0} for repo {1}", new Object[]{repoSize, repoURL}); + LOGGER.log(Level.FINE, "Caching repo size {0} for repo {1}", new Object[] {repoSize, repoURL}); repositorySizeCache.put(repoURL, repoSize); } } @@ -289,14 +304,13 @@ private void assignSizeToInternalCache(String repoURL, long repoSize) { * @return boolean useAPI or not. */ private boolean setSizeFromAPI(String repoUrl, Item context, String credentialsId) { - List acceptedRepository = Objects.requireNonNull(RepositorySizeAPI.all()) - .stream() + List acceptedRepository = Objects.requireNonNull(RepositorySizeAPI.all()).stream() .filter(r -> r.isApplicableTo(repoUrl, context, credentialsId)) .collect(Collectors.toList()); if (acceptedRepository.size() > 0) { try { - for (RepositorySizeAPI repo: acceptedRepository) { + for (RepositorySizeAPI repo : acceptedRepository) { long size = repo.getSizeOfRepository(repoUrl, context, credentialsId); if (size != 0) { sizeOfRepo = size; @@ -351,10 +365,10 @@ private GitTool resolveGitToolForRecommendation(GitTool userChoice, String recom return null; } } else { - if (!userChoice.getName().equals(JGitTool.MAGIC_EXENAME) && !userChoice.getName().equals(JGitApacheTool.MAGIC_EXENAME)) { + if (!userChoice.getName().equals(JGitTool.MAGIC_EXENAME) + && !userChoice.getName().equals(JGitApacheTool.MAGIC_EXENAME)) { return userChoice; - } - else { + } else { return recommendGitToolOnAgent(userChoice); } } @@ -365,13 +379,15 @@ public GitTool recommendGitToolOnAgent(GitTool userChoice) { GitTool correctTool = GitTool.getDefaultInstallation(); String toolName = userChoice.getName(); if (toolName.equals(JGitTool.MAGIC_EXENAME) || toolName.equals(JGitApacheTool.MAGIC_EXENAME)) { - GitTool[] toolList = Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallations(); + GitTool[] toolList = Jenkins.get() + .getDescriptorByType(GitTool.DescriptorImpl.class) + .getInstallations(); for (GitTool tool : toolList) { if (!tool.getProperties().isEmpty()) { preferredToolList.add(tool); } } - for (GitTool tool: preferredToolList) { + for (GitTool tool : preferredToolList) { if (tool.getName().equals(getResolvedGitTool(tool.getName()).getName())) { correctTool = getResolvedGitTool(tool.getName()); } @@ -404,7 +420,7 @@ public String getGitTool() { * Other plugins can estimate the size of repository using this extension point * The size is assumed to be in KiBs */ - public static abstract class RepositorySizeAPI implements ExtensionPoint { + public abstract static class RepositorySizeAPI implements ExtensionPoint { public abstract boolean isApplicableTo(String remote, Item context, String credentialsId); diff --git a/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java b/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java index 2c5f41ee5a..f11c2af04e 100644 --- a/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java +++ b/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java @@ -3,18 +3,22 @@ import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import edu.umd.cs.findbugs.annotations.NonNull; - import hudson.EnvVars; +import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Run; import hudson.model.TaskListener; -import hudson.Extension; import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitTool; import hudson.util.ListBoxModel; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import jenkins.model.Jenkins; -import org.kohsuke.stapler.interceptor.RequirePOST; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor; import org.jenkinsci.plugins.credentialsbinding.MultiBinding; @@ -24,29 +28,23 @@ import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.stapler.DataBoundConstructor; +import org.kohsuke.stapler.interceptor.RequirePOST; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -public class GitUsernamePasswordBinding extends MultiBinding implements GitCredentialBindings { - final static private String GIT_USERNAME_KEY = "GIT_USERNAME"; - final static private String GIT_PASSWORD_KEY = "GIT_PASSWORD"; - final private String gitToolName; +public class GitUsernamePasswordBinding extends MultiBinding + implements GitCredentialBindings { + private static final String GIT_USERNAME_KEY = "GIT_USERNAME"; + private static final String GIT_PASSWORD_KEY = "GIT_PASSWORD"; + private final String gitToolName; private transient boolean unixNodeType; @DataBoundConstructor public GitUsernamePasswordBinding(String gitToolName, String credentialsId) { super(credentialsId); this.gitToolName = gitToolName; - //Variables could be added if needed + // Variables could be added if needed } - public String getGitToolName(){ + public String getGitToolName() { return this.gitToolName; } @@ -60,30 +58,32 @@ protected Class type() { } @Override - public MultiEnvironment bind(@NonNull Run run, FilePath filePath, - Launcher launcher, @NonNull TaskListener taskListener) + public MultiEnvironment bind( + @NonNull Run run, FilePath filePath, Launcher launcher, @NonNull TaskListener taskListener) throws IOException, InterruptedException { final Map secretValues = new LinkedHashMap<>(); final Map publicValues = new LinkedHashMap<>(); StandardUsernamePasswordCredentials credentials = getCredentials(run); - setCredentialPairBindings(credentials,secretValues,publicValues); + setCredentialPairBindings(credentials, secretValues, publicValues); GitTool cliGitTool = getCliGitTool(run, this.gitToolName, taskListener); if (cliGitTool != null && filePath != null) { final UnbindableDir unbindTempDir = UnbindableDir.create(filePath); setUnixNodeType(isCurrentNodeOSUnix(launcher)); - setGitEnvironmentVariables(getGitClientInstance(cliGitTool.getGitExe(), unbindTempDir.getDirPath(), - new EnvVars(), taskListener), publicValues); + setGitEnvironmentVariables( + getGitClientInstance( + cliGitTool.getGitExe(), unbindTempDir.getDirPath(), new EnvVars(), taskListener), + publicValues); GenerateGitScript gitScript = new GenerateGitScript( - credentials.getUsername(), - credentials.getPassword().getPlainText(), - credentials.getId(), - this.unixNodeType); + credentials.getUsername(), + credentials.getPassword().getPlainText(), + credentials.getId(), + this.unixNodeType); FilePath gitTempFile = gitScript.write(credentials, unbindTempDir.getDirPath()); secretValues.put("GIT_ASKPASS", gitTempFile.getRemote()); return new MultiEnvironment(secretValues, publicValues, unbindTempDir.getUnbinder()); } else { taskListener.getLogger().println("JGit and JGitApache type Git tools are not supported by this binding"); - return new MultiEnvironment(secretValues,publicValues); + return new MultiEnvironment(secretValues, publicValues); } } @@ -96,24 +96,31 @@ public Set variables(@NonNull Run build) { } @Override - public void setCredentialPairBindings(@NonNull StandardCredentials credentials, Map secretValues, Map publicValues) { - StandardUsernamePasswordCredentials usernamePasswordCredentials = (StandardUsernamePasswordCredentials) credentials; - if(usernamePasswordCredentials.isUsernameSecret()){ + public void setCredentialPairBindings( + @NonNull StandardCredentials credentials, + Map secretValues, + Map publicValues) { + StandardUsernamePasswordCredentials usernamePasswordCredentials = + (StandardUsernamePasswordCredentials) credentials; + if (usernamePasswordCredentials.isUsernameSecret()) { secretValues.put(GIT_USERNAME_KEY, usernamePasswordCredentials.getUsername()); - }else{ + } else { publicValues.put(GIT_USERNAME_KEY, usernamePasswordCredentials.getUsername()); } - secretValues.put(GIT_PASSWORD_KEY, usernamePasswordCredentials.getPassword().getPlainText()); + secretValues.put( + GIT_PASSWORD_KEY, usernamePasswordCredentials.getPassword().getPlainText()); } - /*package*/void setGitEnvironmentVariables(@NonNull GitClient git, Map publicValues) throws IOException, InterruptedException { - setGitEnvironmentVariables(git,null,publicValues); + /*package*/ void setGitEnvironmentVariables(@NonNull GitClient git, Map publicValues) + throws IOException, InterruptedException { + setGitEnvironmentVariables(git, null, publicValues); } @Override - public void setGitEnvironmentVariables(@NonNull GitClient git, Map secretValues, Map publicValues) throws IOException, InterruptedException { - if (unixNodeType && ((CliGitAPIImpl) git).isCliGitVerAtLeast(2,3,0,0)) - { + public void setGitEnvironmentVariables( + @NonNull GitClient git, Map secretValues, Map publicValues) + throws IOException, InterruptedException { + if (unixNodeType && ((CliGitAPIImpl) git).isCliGitVerAtLeast(2, 3, 0, 0)) { publicValues.put("GIT_TERMINAL_PROMPT", "false"); } else { publicValues.put("GCM_INTERACTIVE", "false"); @@ -121,8 +128,8 @@ public void setGitEnvironmentVariables(@NonNull GitClient git, Map toolList = Jenkins.get().getDescriptorByType(GitSCM.DescriptorImpl.class).getGitTools(); - for (GitTool t : toolList){ - if(t.getClass().equals(GitTool.class)){ - items.add(t.getName()); - } - } - return items; + List toolList = Jenkins.get() + .getDescriptorByType(GitSCM.DescriptorImpl.class) + .getGitTools(); + for (GitTool t : toolList) { + if (t.getClass().equals(GitTool.class)) { + items.add(t.getName()); + } + } + return items; } @Override diff --git a/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java b/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java index 4e23b0033d..6cbda55212 100644 --- a/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java +++ b/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java @@ -7,7 +7,6 @@ import hudson.matrix.MatrixBuild; import hudson.model.BuildListener; import hudson.plugins.git.GitPublisher; - import java.io.IOException; @Extension(optional = true) @@ -15,8 +14,9 @@ public class MatrixGitPublisher implements MatrixAggregatable { /** * For a matrix project, push should only happen once. */ + @Override public MatrixAggregator createAggregator(MatrixBuild build, Launcher launcher, BuildListener listener) { - return new MatrixAggregator(build,launcher,listener) { + return new MatrixAggregator(build, launcher, listener) { @Override public boolean endBuild() throws InterruptedException, IOException { GitPublisher publisher = build.getParent().getPublishersList().get(GitPublisher.class); diff --git a/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java b/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java index 3ba64b4eec..a88a438a07 100644 --- a/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java +++ b/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java @@ -56,6 +56,7 @@ public class MergeWithGitSCMExtension extends GitSCMExtension { @NonNull private final String baseName; + @CheckForNull private final String baseHash; @@ -74,8 +75,9 @@ public String getBaseHash() { } @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 { // we are doing a merge, so cannot permit a shallow clone cmd.shallow(false); } @@ -89,24 +91,25 @@ public void decorateFetchCommand(GitSCM scm, GitClient git, TaskListener listene } @Override - public Revision decorateRevisionToBuild(GitSCM scm, Run build, GitClient git, TaskListener listener, - Revision marked, Revision rev) + public Revision decorateRevisionToBuild( + GitSCM scm, Run build, GitClient git, TaskListener listener, Revision marked, Revision rev) throws IOException, InterruptedException, GitException { ObjectId baseObjectId; if (baseHash == null || baseHash.isBlank()) { try { baseObjectId = git.revParse(Constants.R_REFS + baseName); } catch (GitException e) { - listener.getLogger().printf("Unable to determine head revision of %s prior to merge with PR%n", - baseName); + listener.getLogger() + .printf("Unable to determine head revision of %s prior to merge with PR%n", baseName); throw e; } } else { baseObjectId = ObjectId.fromString(baseHash); } - listener.getLogger().printf("Merging %s commit %s into PR head commit %s%n", - baseName, baseObjectId.name(), rev.getSha1String() - ); + listener.getLogger() + .printf( + "Merging %s commit %s into PR head commit %s%n", + baseName, baseObjectId.name(), rev.getSha1String()); checkout(scm, build, git, listener, rev); try { /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */ diff --git a/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java b/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java index 3dbb845dd5..f5a817c02e 100644 --- a/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java @@ -56,15 +56,14 @@ public class BranchDiscoveryTrait extends SCMSourceTrait { * Constructor for stapler. */ @DataBoundConstructor - public BranchDiscoveryTrait() { - } + public BranchDiscoveryTrait() {} /** * {@inheritDoc} */ @Override protected void decorateContext(SCMSourceContext context) { - GitSCMSourceContext ctx = (GitSCMSourceContext) context; + GitSCMSourceContext ctx = (GitSCMSourceContext) context; ctx.wantBranches(true); ctx.withAuthority(new BranchSCMHeadAuthority()); } diff --git a/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java b/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java index 50e6dc7771..1cf2c48d08 100644 --- a/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java @@ -25,14 +25,13 @@ package jenkins.plugins.git.traits; +import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.Extension; import hudson.plugins.git.extensions.impl.CleanCheckout; import jenkins.scm.api.trait.SCMSourceTrait; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; -import edu.umd.cs.findbugs.annotations.CheckForNull; - /** * Exposes {@link CleanCheckout} as a {@link SCMSourceTrait}. * diff --git a/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java b/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java index 78d20e800e..a22648ecad 100644 --- a/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java @@ -25,14 +25,13 @@ package jenkins.plugins.git.traits; +import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.Extension; import hudson.plugins.git.extensions.impl.CleanBeforeCheckout; import jenkins.scm.api.trait.SCMSourceTrait; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; -import edu.umd.cs.findbugs.annotations.CheckForNull; - /** * Exposes {@link CleanBeforeCheckout} as a {@link SCMSourceTrait}. * diff --git a/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java b/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java index d512eac7e7..8c08c7bb3a 100644 --- a/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java @@ -23,6 +23,8 @@ */ package jenkins.plugins.git.traits; +import static jenkins.plugins.git.AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR; + import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import jenkins.plugins.git.GitSCMBuilder; @@ -40,8 +42,6 @@ import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; -import static jenkins.plugins.git.AbstractGitSCMSource.REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR; - public class DiscoverOtherRefsTrait extends SCMSourceTrait { private final String ref; @@ -56,7 +56,7 @@ public DiscoverOtherRefsTrait(String ref) { setDefaultNameMapping(); } - //for easier testing + // for easier testing public DiscoverOtherRefsTrait(String ref, String nameMapping) { this(ref); setNameMapping(nameMapping); @@ -67,7 +67,8 @@ public String getRef() { } String getFullRefSpec() { - return "+" + Constants.R_REFS + ref + ':' + Constants.R_REMOTES + REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR + '/' + ref; + return "+" + Constants.R_REFS + ref + ':' + Constants.R_REMOTES + REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR + '/' + + ref; } public String getNameMapping() { @@ -87,8 +88,8 @@ private void setDefaultNameMapping() { this.nameMapping = null; String[] paths = ref.split("/"); for (int i = 0; i < paths.length; i++) { - if("*".equals(paths[i]) && i > 0) { - this.nameMapping = paths[i-1] + "-@{1}"; + if ("*".equals(paths[i]) && i > 0) { + this.nameMapping = paths[i - 1] + "-@{1}"; break; } } @@ -111,7 +112,7 @@ protected void decorateContext(SCMSourceContext context) { /** * Our descriptor. */ - @Symbol(value={"discoverOtherRefs","discoverOtherRefsTrait"}) // Avoid JCasC warning about obsolete symbol + @Symbol(value = {"discoverOtherRefs", "discoverOtherRefsTrait"}) // Avoid JCasC warning about obsolete symbol @Extension @Discovery public static class DescriptorImpl extends SCMSourceTraitDescriptor { diff --git a/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java b/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java index 02dd07afbd..4d3e06b6ed 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java @@ -111,7 +111,8 @@ public String getDisplayName() { */ @Restricted(NoExternalUse.class) // stapler public List>> getBrowserDescriptors() { - GitSCM.DescriptorImpl descriptor = (GitSCM.DescriptorImpl) Jenkins.get().getDescriptor(GitSCM.class); + GitSCM.DescriptorImpl descriptor = + (GitSCM.DescriptorImpl) Jenkins.get().getDescriptor(GitSCM.class); if (descriptor == null) { return java.util.Collections.emptyList(); // Should be unreachable } diff --git a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTrait.java b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTrait.java index 69f85f081f..0a54a4a24c 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTrait.java @@ -67,7 +67,7 @@ public E getExtension() { * {@inheritDoc} */ @Override - protected void decorateBuilder(SCMBuilder builder) { + protected void decorateBuilder(SCMBuilder builder) { ((GitSCMBuilder) builder).withExtension(extension); } } diff --git a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java index f4f2243be7..6002b17c17 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java +++ b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java @@ -25,6 +25,7 @@ package jenkins.plugins.git.traits; +import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Util; import hudson.model.Descriptor; @@ -37,7 +38,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import edu.umd.cs.findbugs.annotations.CheckForNull; import jenkins.model.Jenkins; import jenkins.plugins.git.GitSCMBuilder; import jenkins.scm.api.trait.SCMBuilder; @@ -79,21 +79,23 @@ public abstract class GitSCMExtensionTraitDescriptor extends SCMSourceTraitDescr * @param clazz Pass in the type of {@link SCMTrait} * @param extension Pass in the type of {@link GitSCMExtension}. */ - protected GitSCMExtensionTraitDescriptor(Class clazz, - Class extension) { + protected GitSCMExtensionTraitDescriptor( + Class clazz, Class extension) { super(clazz); this.extension = extension; - if (!Util.isOverridden(GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", - GitSCMExtension.class)) { + if (!Util.isOverridden( + GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", GitSCMExtension.class)) { // check that the GitSCMExtensionTrait has a constructor that takes a single argument of the type // 'extension' so that our default convertToTrait method implementation can be used try { constructor = clazz.getConstructor(extension); noArgConstructor = constructor.getParameterTypes().length == 0; } catch (NoSuchMethodException e) { - throw new AssertionError("Could not infer how to convert a " + extension + " to a " - + clazz + " as there is no obvious constructor. Either provide a simple constructor or " - + "override convertToTrait(GitSCMExtension)", e); + throw new AssertionError( + "Could not infer how to convert a " + extension + " to a " + + clazz + " as there is no obvious constructor. Either provide a simple constructor or " + + "override convertToTrait(GitSCMExtension)", + e); } } else { constructor = null; @@ -119,11 +121,11 @@ protected GitSCMExtensionTraitDescriptor() { + "class constructor)"); } } else { - throw new AssertionError("Could not infer GitSCMExtension type. Consider using the explicit " - + "class constructor)"); + throw new AssertionError( + "Could not infer GitSCMExtension type. Consider using the explicit " + "class constructor)"); } - if (!Util.isOverridden(GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", - GitSCMExtension.class)) { + if (!Util.isOverridden( + GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", GitSCMExtension.class)) { // check that the GitSCMExtensionTrait has a constructor that takes a single argument of the type // 'extension' so that our default convertToTrait method implementation can be used Constructor constructor = null; @@ -148,8 +150,8 @@ protected GitSCMExtensionTraitDescriptor() { + "convertToTrait(GitSCMExtension)"); } } else { - throw new AssertionError("Could not infer how to convert a " + extension + " to a " - + clazz + " as there is no @DataBoundConstructor (which is going to cause other problems)"); + throw new AssertionError("Could not infer how to convert a " + extension + " to a " + clazz + + " as there is no @DataBoundConstructor (which is going to cause other problems)"); } } else { constructor = null; @@ -211,19 +213,17 @@ public Class getExtensionClass() { @CheckForNull public SCMSourceTrait convertToTrait(@NonNull GitSCMExtension extension) { if (!this.extension.isInstance(extension)) { - throw new IllegalArgumentException( - "Expected a " + this.extension.getName() + " but got a " + extension.getClass().getName() - ); + throw new IllegalArgumentException("Expected a " + this.extension.getName() + " but got a " + + extension.getClass().getName()); } if (constructor == null) { - if (!Util.isOverridden(GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", - GitSCMExtension.class)) { - throw new IllegalStateException("Should not be able to instantiate a " + getClass().getName() - + " without an inferred constructor for " + this.extension.getName()); + if (!Util.isOverridden( + GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", GitSCMExtension.class)) { + throw new IllegalStateException("Should not be able to instantiate a " + + getClass().getName() + " without an inferred constructor for " + this.extension.getName()); } - throw new UnsupportedOperationException( - getClass().getName() + " should not delegate convertToTrait() to " + GitSCMExtension.class - .getName()); + throw new UnsupportedOperationException(getClass().getName() + " should not delegate convertToTrait() to " + + GitSCMExtension.class.getName()); } try { return noArgConstructor diff --git a/src/main/java/jenkins/plugins/git/traits/GitToolSCMSourceTrait.java b/src/main/java/jenkins/plugins/git/traits/GitToolSCMSourceTrait.java index c10764d131..747e382933 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitToolSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/GitToolSCMSourceTrait.java @@ -83,7 +83,7 @@ public String getGitTool() { */ @Override protected void decorateContext(SCMSourceContext context) { - ((GitSCMSourceContext)context).withGitTool(gitTool); + ((GitSCMSourceContext) context).withGitTool(gitTool); } /** @@ -130,7 +130,8 @@ public Class getContextClass() { */ @Override public boolean isApplicableToBuilder(@NonNull Class builderClass) { - return super.isApplicableToBuilder(builderClass) && getSCMDescriptor().showGitToolOptions(); + return super.isApplicableToBuilder(builderClass) + && getSCMDescriptor().showGitToolOptions(); } /** @@ -138,7 +139,8 @@ public boolean isApplicableToBuilder(@NonNull Class builde */ @Override public boolean isApplicableToContext(@NonNull Class contextClass) { - return super.isApplicableToContext(contextClass) && getSCMDescriptor().showGitToolOptions(); + return super.isApplicableToContext(contextClass) + && getSCMDescriptor().showGitToolOptions(); } /** @@ -167,6 +169,5 @@ private GitSCM.DescriptorImpl getSCMDescriptor() { public ListBoxModel doFillGitToolItems() { return getSCMDescriptor().doFillGitToolItems(); } - } } diff --git a/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java b/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java index bbf82e0d60..00e09a41d0 100644 --- a/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java @@ -46,8 +46,7 @@ public class IgnoreOnPushNotificationTrait extends SCMSourceTrait { * Stapler constructor. */ @DataBoundConstructor - public IgnoreOnPushNotificationTrait() { - } + public IgnoreOnPushNotificationTrait() {} /** * {@inheritDoc} @@ -81,7 +80,6 @@ public String getDisplayName() { return "Ignore on push notifications"; } - /** * {@inheritDoc} */ @@ -113,6 +111,5 @@ public Class getContextClass() { public Class getSourceClass() { return GitSCMSource.class; } - } } diff --git a/src/main/java/jenkins/plugins/git/traits/LocalBranchTrait.java b/src/main/java/jenkins/plugins/git/traits/LocalBranchTrait.java index d46866a519..f73f713a45 100644 --- a/src/main/java/jenkins/plugins/git/traits/LocalBranchTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/LocalBranchTrait.java @@ -54,7 +54,7 @@ public LocalBranchTrait() { * Our {@link hudson.model.Descriptor} */ @Extension - @Symbol(value={"localBranch", "localBranchTrait"}) // Avoid JCasC message about obsolete symbol + @Symbol(value = {"localBranch", "localBranchTrait"}) // Avoid JCasC message about obsolete symbol public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { /** * {@inheritDoc} diff --git a/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java b/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java index 0f1f9aced6..ba82311429 100644 --- a/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java @@ -25,12 +25,11 @@ package jenkins.plugins.git.traits; -import org.jenkinsci.Symbol; -import org.kohsuke.stapler.DataBoundConstructor; - import hudson.Extension; import hudson.plugins.git.extensions.impl.PruneStaleTag; import jenkins.scm.api.trait.SCMSourceTrait; +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; /** * Exposes {@link PruneStaleTag} as a {@link SCMSourceTrait}. diff --git a/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java b/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java index 1f461f8ef9..60abe47754 100644 --- a/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java @@ -178,7 +178,6 @@ public Class getScmClass() { public Class getContextClass() { return GitSCMSourceContext.class; } - } /** @@ -244,8 +243,7 @@ public FormValidation doCheckValue(@QueryParameter String value) { if (!value.startsWith("+")) { return FormValidation.warningWithMarkup( "It is recommended to ensure references are always updated by prefixing with " - + "+" - ); + + "+"); } return FormValidation.ok(); } catch (IllegalArgumentException e) { diff --git a/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java b/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java index e37fc7bc94..42750e0e55 100644 --- a/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java @@ -68,9 +68,7 @@ public class RemoteNameSCMSourceTrait extends SCMSourceTrait { @DataBoundConstructor public RemoteNameSCMSourceTrait(@CheckForNull String remoteName) { this.remoteName = validate(StringUtils.defaultIfBlank( - StringUtils.trimToEmpty(remoteName), - AbstractGitSCMSource.DEFAULT_REMOTE_NAME - )); + StringUtils.trimToEmpty(remoteName), AbstractGitSCMSource.DEFAULT_REMOTE_NAME)); } /** @@ -189,8 +187,8 @@ public String getDisplayName() { } /** - - /** + * + * /** * {@inheritDoc} */ @Override @@ -227,8 +225,9 @@ public FormValidation doCheckRemoteName(@QueryParameter String value) { return FormValidation.error("You must specify a remote name"); } if (AbstractGitSCMSource.DEFAULT_REMOTE_NAME.equals(value)) { - return FormValidation.warning("There is no need to configure a remote name of '%s' as " - + "this is the default remote name.", AbstractGitSCMSource.DEFAULT_REMOTE_NAME); + return FormValidation.warning( + "There is no need to configure a remote name of '%s' as " + "this is the default remote name.", + AbstractGitSCMSource.DEFAULT_REMOTE_NAME); } try { validate(value); @@ -237,6 +236,5 @@ public FormValidation doCheckRemoteName(@QueryParameter String value) { return FormValidation.error(e.getMessage()); } } - } } diff --git a/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java b/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java index 9c9be145a9..55eeda476f 100644 --- a/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java @@ -55,15 +55,14 @@ public class TagDiscoveryTrait extends SCMSourceTrait { * Constructor for stapler. */ @DataBoundConstructor - public TagDiscoveryTrait() { - } + public TagDiscoveryTrait() {} /** * {@inheritDoc} */ @Override protected void decorateContext(SCMSourceContext context) { - GitSCMSourceContext ctx = (GitSCMSourceContext) context; + GitSCMSourceContext ctx = (GitSCMSourceContext) context; ctx.wantTags(true); ctx.withAuthority(new TagSCMHeadAuthority()); } @@ -120,7 +119,8 @@ public Class getSourceClass() { /** * Trusts tags from the repository. */ - public static class TagSCMHeadAuthority extends SCMHeadAuthority { + public static class TagSCMHeadAuthority + extends SCMHeadAuthority { /** * {@inheritDoc} */ diff --git a/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.groovy b/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.groovy index e60e30e19a..2f8e00c935 100644 --- a/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.groovy +++ b/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.groovy @@ -3,7 +3,7 @@ package hudson.plugins.git.GitSCM def l = namespace(lib.JenkinsTagLib) // TODO handle GitSCMExtension.populateEnvironmentVariables somehow, say by optionally including GitSCMExtension/buildEnv.groovy; though GIT_{COMMITTER,AUTHOR}_{NAME,EMAIL} are only overridden by UserIdentity -['GIT_COMMIT', 'GIT_PREVIOUS_COMMIT', 'GIT_PREVIOUS_SUCCESSFUL_COMMIT', 'GIT_BRANCH', 'GIT_LOCAL_BRANCH', 'GIT_CHECKOUT_DIR', 'GIT_URL', 'GIT_COMMITTER_NAME', 'GIT_AUTHOR_NAME', 'GIT_COMMITTER_EMAIL', 'GIT_AUTHOR_EMAIL'].each {name -> +['GIT_COMMIT', 'GIT_PREVIOUS_COMMIT', 'GIT_PREVIOUS_SUCCESSFUL_COMMIT', 'GIT_BRANCH', 'GIT_LOCAL_BRANCH', 'GIT_CHECKOUT_DIR', 'GIT_URL', 'GIT_COMMITTER_NAME', 'GIT_AUTHOR_NAME', 'GIT_COMMITTER_EMAIL', 'GIT_AUTHOR_EMAIL', 'GIT_COMMIT_TITLE'].each {name -> l.buildEnvVar(name: name) { raw(_("${name}.blurb")) } diff --git a/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.properties b/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.properties index 100915c95a..94b60fe463 100644 --- a/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.properties +++ b/src/main/resources/hudson/plugins/git/GitSCM/buildEnv.properties @@ -1,6 +1,7 @@ GIT_COMMIT.blurb=The commit hash being checked out. GIT_PREVIOUS_COMMIT.blurb=The hash of the commit last built on this branch, if any. GIT_PREVIOUS_SUCCESSFUL_COMMIT.blurb=The hash of the commit last successfully built on this branch, if any. +GIT_COMMIT_TITLE.blurb=The text up to the first blank line in a commit message is treated as the commit title. GIT_BRANCH.blurb=The remote branch name, if any. GIT_LOCAL_BRANCH.blurb=The local branch name being checked out, if applicable. GIT_CHECKOUT_DIR.blurb=The directory that the repository will be checked out to. This contains the value set in Checkout to a sub-directory, if used. diff --git a/src/test/java/hudson/plugins/git/AbstractGitProject.java b/src/test/java/hudson/plugins/git/AbstractGitProject.java index fee17811b3..7ea5facd57 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitProject.java +++ b/src/test/java/hudson/plugins/git/AbstractGitProject.java @@ -23,6 +23,8 @@ */ package hudson.plugins.git; +import static org.junit.Assert.assertTrue; + import hudson.EnvVars; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; @@ -41,22 +43,15 @@ import hudson.remoting.VirtualChannel; import hudson.slaves.EnvironmentVariablesNodeProperty; import hudson.triggers.SCMTrigger; - import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; - import jenkins.MasterToSlaveFileCallable; import org.eclipse.jgit.lib.Repository; - import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.JGitTool; - -import static org.junit.Assert.assertTrue; - import org.junit.Rule; - import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import org.jvnet.hudson.test.FlagRule; import org.jvnet.hudson.test.JenkinsRule; @@ -71,14 +66,13 @@ public class AbstractGitProject extends AbstractGitRepository { public JenkinsRule jenkins = new JenkinsRule(); @Rule - public FlagRule notifyCommitAccessControl = - new FlagRule<>(() -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL, x -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = x); + public FlagRule notifyCommitAccessControl = new FlagRule<>( + () -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL, x -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = x); protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter) throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject(); - GitSCM scm = new GitSCM(remoteConfigs(), branches, - null, null, - Collections.singletonList(new DisableRemotePoll())); + GitSCM scm = + new GitSCM(remoteConfigs(), branches, null, null, Collections.singletonList(new DisableRemotePoll())); project.setScm(scm); project.getBuildersList().add(new CaptureEnvironmentBuilder()); return project; @@ -92,65 +86,120 @@ protected FreeStyleProject setupProject(String branchString, boolean authorOrCom return setupProject(branchString, authorOrCommitter, null); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir) throws Exception { + protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, String relativeTargetDir) + throws Exception { return setupProject(branchString, authorOrCommitter, relativeTargetDir, null, null, null); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, String relativeTargetDir, String excludedRegions, String excludedUsers, - String includedRegions) throws Exception { - return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, false, includedRegions); + String includedRegions) + throws Exception { + return setupProject( + branchString, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + null, + false, + includedRegions); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, String relativeTargetDir, String excludedRegions, String excludedUsers, boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, fastRemotePoll, includedRegions); + String includedRegions) + throws Exception { + return setupProject( + branchString, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + null, + fastRemotePoll, + includedRegions); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(Collections.singletonList(new BranchSpec(branchString)), - authorOrCommitter, relativeTargetDir, excludedRegions, - excludedUsers, localBranch, fastRemotePoll, + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions) + throws Exception { + return setupProject( + Collections.singletonList(new BranchSpec(branchString)), + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + localBranch, + fastRemotePoll, includedRegions); } - protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(branches, - authorOrCommitter, relativeTargetDir, excludedRegions, - excludedUsers, localBranch, fastRemotePoll, - includedRegions, null); + protected FreeStyleProject setupProject( + List branches, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions) + throws Exception { + return setupProject( + branches, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + localBranch, + fastRemotePoll, + includedRegions, + null); } - protected FreeStyleProject setupProject(String branchString, List sparseCheckoutPaths) throws Exception { - return setupProject(Collections.singletonList(new BranchSpec(branchString)), - false, null, null, - null, null, false, - null, sparseCheckoutPaths); + protected FreeStyleProject setupProject(String branchString, List sparseCheckoutPaths) + throws Exception { + return setupProject( + Collections.singletonList(new BranchSpec(branchString)), + false, + null, + null, + null, + null, + false, + null, + sparseCheckoutPaths); } - protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions, List sparseCheckoutPaths) throws Exception { + protected FreeStyleProject setupProject( + List branches, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions, + List sparseCheckoutPaths) + throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject(); - GitSCM scm = new GitSCM( - remoteConfigs(), - branches, - null, null, - Collections.emptyList()); + GitSCM scm = new GitSCM(remoteConfigs(), branches, null, null, Collections.emptyList()); scm.getExtensions().add(new DisableRemotePoll()); // don't work on a file:// repository if (relativeTargetDir != null) { scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); @@ -180,14 +229,15 @@ protected FreeStyleProject setupProject(List branches, boolean autho * @return the created project * @throws Exception on error */ - protected FreeStyleProject setupProject(List repos, List branchSpecs, - String scmTriggerSpec, boolean disableRemotePoll, EnforceGitClient enforceGitClient) throws Exception { + protected FreeStyleProject setupProject( + List repos, + List branchSpecs, + String scmTriggerSpec, + boolean disableRemotePoll, + EnforceGitClient enforceGitClient) + throws Exception { FreeStyleProject project = jenkins.createFreeStyleProject(); - GitSCM scm = new GitSCM( - repos, - branchSpecs, - null, JGitTool.MAGIC_EXENAME, - Collections.emptyList()); + GitSCM scm = new GitSCM(repos, branchSpecs, null, JGitTool.MAGIC_EXENAME, Collections.emptyList()); if (disableRemotePoll) { scm.getExtensions().add(new DisableRemotePoll()); } @@ -205,10 +255,14 @@ protected FreeStyleProject setupProject(List repos, List() { @Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { try (@SuppressWarnings("deprecation") // Local repository reference - Repository repo = Git.with(null, null).in(f).getClient().getRepository()) { + Repository repo = Git.with(null, null).in(f).getClient().getRepository()) { return repo.resolve("refs/heads/" + branch).name(); } catch (GitException e) { throw new RuntimeException(e); @@ -262,9 +329,6 @@ protected EnvVars getEnvVars(FreeStyleProject project) { } protected void setVariables(Node node, EnvironmentVariablesNodeProperty.Entry... entries) throws IOException { - node.getNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( - entries))); - + node.getNodeProperties().replaceBy(Collections.singleton(new EnvironmentVariablesNodeProperty(entries))); } } diff --git a/src/test/java/hudson/plugins/git/AbstractGitRepository.java b/src/test/java/hudson/plugins/git/AbstractGitRepository.java index b342f4008c..0a19552fa5 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitRepository.java +++ b/src/test/java/hudson/plugins/git/AbstractGitRepository.java @@ -1,23 +1,19 @@ package hudson.plugins.git; +import hudson.EnvVars; +import hudson.model.TaskListener; +import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; - -import org.junit.Before; -import org.junit.Rule; - -import hudson.EnvVars; -import hudson.model.TaskListener; -import hudson.util.StreamTaskListener; - import jenkins.plugins.git.GitSampleRepoRule; - import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; +import org.junit.Before; +import org.junit.Rule; /** * Temporary git repository for use with tests. Tests which need a git @@ -78,6 +74,6 @@ protected List remoteConfigs() throws IOException { /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java index a42e05bd46..425db3fa27 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java +++ b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java @@ -1,25 +1,26 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import com.cloudbees.plugins.credentials.CredentialsNameProvider; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.common.StandardCredentials; - import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; -import hudson.model.FreeStyleBuild; -import hudson.model.Result; -import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; +import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Node; -import hudson.plugins.git.extensions.impl.EnforceGitClient; +import hudson.model.Result; +import hudson.model.TaskListener; import hudson.plugins.git.extensions.impl.DisableRemotePoll; +import hudson.plugins.git.extensions.impl.EnforceGitClient; import hudson.plugins.git.extensions.impl.PathRestriction; import hudson.plugins.git.extensions.impl.RelativeTargetDirectory; import hudson.plugins.git.extensions.impl.SparseCheckoutPath; @@ -31,13 +32,12 @@ import hudson.tasks.Builder; import hudson.triggers.SCMTrigger; import hudson.util.StreamTaskListener; - import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; - import jenkins.MasterToSlaveFileCallable; +import jenkins.plugins.git.GitSampleRepoRule; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.util.SystemReader; @@ -46,12 +46,9 @@ import org.jenkinsci.plugins.gitclient.JGitTool; import org.junit.Before; import org.junit.Rule; -import jenkins.plugins.git.GitSampleRepoRule; import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; - -import static org.junit.Assert.*; import org.kohsuke.stapler.DataBoundConstructor; /** @@ -96,14 +93,15 @@ protected String commit(final String fileName, final PersonIdent committer, fina return testRepo.commit(fileName, committer, message); } - protected String commit(final String fileName, final String fileContent, final PersonIdent committer, final String message) - + protected String commit( + final String fileName, final String fileContent, final PersonIdent committer, final String message) throws GitException, InterruptedException { return testRepo.commit(fileName, fileContent, committer, message); } - protected String commit(final String fileName, final PersonIdent author, final PersonIdent committer, - final String message) throws GitException, InterruptedException { + protected String commit( + final String fileName, final PersonIdent author, final PersonIdent committer, final String message) + throws GitException, InterruptedException { return testRepo.commit(fileName, author, committer, message); } @@ -123,83 +121,150 @@ protected FreeStyleProject setupProject(String branchString, boolean authorOrCom return setupProject(branchString, authorOrCommitter, null); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir) throws Exception { + protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, String relativeTargetDir) + throws Exception { return setupProject(branchString, authorOrCommitter, relativeTargetDir, null, null, null); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir, - String excludedRegions, - String excludedUsers, - String includedRegions) throws Exception { - return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, false, includedRegions); + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String includedRegions) + throws Exception { + return setupProject( + branchString, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + null, + false, + includedRegions); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir, - String excludedRegions, - String excludedUsers, - boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(branchString, authorOrCommitter, relativeTargetDir, excludedRegions, excludedUsers, null, fastRemotePoll, includedRegions); + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + boolean fastRemotePoll, + String includedRegions) + throws Exception { + return setupProject( + branchString, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + null, + fastRemotePoll, + includedRegions); } - protected FreeStyleProject setupProject(String branchString, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(Collections.singletonList(new BranchSpec(branchString)), - authorOrCommitter, relativeTargetDir, excludedRegions, - excludedUsers, localBranch, fastRemotePoll, - includedRegions); + protected FreeStyleProject setupProject( + String branchString, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions) + throws Exception { + return setupProject( + Collections.singletonList(new BranchSpec(branchString)), + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + localBranch, + fastRemotePoll, + includedRegions); } protected FreeStyleProject setupProject(String branchString, StandardCredentials credential) throws Exception { - return setupProject(Collections.singletonList(new BranchSpec(branchString)), - false, null, null, - null, null, false, - null, null, credential); + return setupProject( + Collections.singletonList(new BranchSpec(branchString)), + false, + null, + null, + null, + null, + false, + null, + null, + credential); } - protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions) throws Exception { - return setupProject(branches, - authorOrCommitter, relativeTargetDir, excludedRegions, - excludedUsers, localBranch, fastRemotePoll, - includedRegions, null, null); + protected FreeStyleProject setupProject( + List branches, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions) + throws Exception { + return setupProject( + branches, + authorOrCommitter, + relativeTargetDir, + excludedRegions, + excludedUsers, + localBranch, + fastRemotePoll, + includedRegions, + null, + null); } - protected FreeStyleProject setupProject(String branchString, List sparseCheckoutPaths) throws Exception { - return setupProject(Collections.singletonList(new BranchSpec(branchString)), - false, null, null, - null, null, false, - null, sparseCheckoutPaths, null); + protected FreeStyleProject setupProject(String branchString, List sparseCheckoutPaths) + throws Exception { + return setupProject( + Collections.singletonList(new BranchSpec(branchString)), + false, + null, + null, + null, + null, + false, + null, + sparseCheckoutPaths, + null); } - protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter, - String relativeTargetDir, String excludedRegions, - String excludedUsers, String localBranch, boolean fastRemotePoll, - String includedRegions, List sparseCheckoutPaths, - StandardCredentials credential) throws Exception { + protected FreeStyleProject setupProject( + List branches, + boolean authorOrCommitter, + String relativeTargetDir, + String excludedRegions, + String excludedUsers, + String localBranch, + boolean fastRemotePoll, + String includedRegions, + List sparseCheckoutPaths, + StandardCredentials credential) + throws Exception { FreeStyleProject project = createFreeStyleProject(); - GitSCM scm = new GitSCM( - createRemoteRepositories(credential), - branches, - null, null, - Collections.emptyList()); + GitSCM scm = new GitSCM(createRemoteRepositories(credential), branches, null, null, Collections.emptyList()); if (credential != null) { project.getBuildersList().add(new HasCredentialBuilder(credential.getId())); } scm.getExtensions().add(new DisableRemotePoll()); // don't work on a file:// repository - if (relativeTargetDir!=null) + if (relativeTargetDir != null) { scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); - if (excludedUsers!=null) + } + if (excludedUsers != null) { scm.getExtensions().add(new UserExclusion(excludedUsers)); - if (excludedRegions!=null || includedRegions!=null) - scm.getExtensions().add(new PathRestriction(includedRegions,excludedRegions)); + } + if (excludedRegions != null || includedRegions != null) { + scm.getExtensions().add(new PathRestriction(includedRegions, excludedRegions)); + } scm.getExtensions().add(new SparseCheckoutPaths(sparseCheckoutPaths)); @@ -218,95 +283,114 @@ protected FreeStyleProject setupProject(List branches, boolean autho * @return the created project * @throws Exception on error */ - protected FreeStyleProject setupProject(List repos, List branchSpecs, - String scmTriggerSpec, boolean disableRemotePoll, EnforceGitClient enforceGitClient) throws Exception { + protected FreeStyleProject setupProject( + List repos, + List branchSpecs, + String scmTriggerSpec, + boolean disableRemotePoll, + EnforceGitClient enforceGitClient) + throws Exception { FreeStyleProject project = createFreeStyleProject(); - GitSCM scm = new GitSCM( - repos, - branchSpecs, - null, JGitTool.MAGIC_EXENAME, - Collections.emptyList()); - if(disableRemotePoll) scm.getExtensions().add(new DisableRemotePoll()); - if(enforceGitClient != null) scm.getExtensions().add(enforceGitClient); + GitSCM scm = new GitSCM(repos, branchSpecs, null, JGitTool.MAGIC_EXENAME, Collections.emptyList()); + if (disableRemotePoll) { + scm.getExtensions().add(new DisableRemotePoll()); + } + if (enforceGitClient != null) { + scm.getExtensions().add(enforceGitClient); + } project.setScm(scm); - if(scmTriggerSpec != null) { + if (scmTriggerSpec != null) { SCMTrigger trigger = new SCMTrigger(scmTriggerSpec); project.addTrigger(trigger); trigger.start(project, true); } - //project.getBuildersList().add(new CaptureEnvironmentBuilder()); + // project.getBuildersList().add(new CaptureEnvironmentBuilder()); project.save(); return project; } - + protected FreeStyleProject setupSimpleProject(String branchString) throws Exception { - return setupProject(branchString,false); + return setupProject(branchString, false); } - protected FreeStyleBuild build(final FreeStyleProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception { + protected FreeStyleBuild build( + final FreeStyleProject project, final Result expectedResult, final String... expectedNewlyCommittedFiles) + throws Exception { final FreeStyleBuild build = project.scheduleBuild2(0).get(); - for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { - assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); + for (final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { + assertTrue( + expectedNewlyCommittedFile + " file not found in workspace", + build.getWorkspace().child(expectedNewlyCommittedFile).exists()); } - if(expectedResult != null) { + if (expectedResult != null) { rule.assertBuildStatus(expectedResult, build); } return build; } - protected FreeStyleBuild build(final FreeStyleProject project, final String parentDir, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception { + protected FreeStyleBuild build( + final FreeStyleProject project, + final String parentDir, + final Result expectedResult, + final String... expectedNewlyCommittedFiles) + throws Exception { final FreeStyleBuild build = project.scheduleBuild2(0).get(); - for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { - assertTrue(build.getWorkspace().child(parentDir).child(expectedNewlyCommittedFile).exists()); + for (final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { + assertTrue(build.getWorkspace() + .child(parentDir) + .child(expectedNewlyCommittedFile) + .exists()); } - if(expectedResult != null) { + if (expectedResult != null) { rule.assertBuildStatus(expectedResult, build); } return build; } - - protected MatrixBuild build(final MatrixProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception { + + protected MatrixBuild build( + final MatrixProject project, final Result expectedResult, final String... expectedNewlyCommittedFiles) + throws Exception { final MatrixBuild build = project.scheduleBuild2(0).get(); - for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { - assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); + for (final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { + assertTrue( + expectedNewlyCommittedFile + " file not found in workspace", + build.getWorkspace().child(expectedNewlyCommittedFile).exists()); } - if(expectedResult != null) { + if (expectedResult != null) { rule.assertBuildStatus(expectedResult, build); } return build; } - protected EnvVars getEnvVars(FreeStyleProject project) { for (hudson.tasks.Builder b : project.getBuilders()) { if (b instanceof CaptureEnvironmentBuilder) { - return ((CaptureEnvironmentBuilder)b).getEnvVars(); + return ((CaptureEnvironmentBuilder) b).getEnvVars(); } } return new EnvVars(); } protected void setVariables(Node node, EnvironmentVariablesNodeProperty.Entry... entries) throws IOException { - node.getNodeProperties().replaceBy( - Collections.singleton(new EnvironmentVariablesNodeProperty( - entries))); - + node.getNodeProperties().replaceBy(Collections.singleton(new EnvironmentVariablesNodeProperty(entries))); } - protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException { + protected String getHeadRevision(AbstractBuild build, final String branch) + throws IOException, InterruptedException { return build.getWorkspace().act(new MasterToSlaveFileCallable() { - public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { - try { - @SuppressWarnings("deprecation") // Local repository reference - org.eclipse.jgit.lib.Repository repo = Git.with(null, null).in(f).getClient().getRepository(); - ObjectId oid = repo.resolve("refs/heads/" + branch); - return oid.name(); - } catch (GitException e) { - throw new RuntimeException(e); - } + @Override + public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { + try { + @SuppressWarnings("deprecation") // Local repository reference + org.eclipse.jgit.lib.Repository repo = + Git.with(null, null).in(f).getClient().getRepository(); + ObjectId oid = repo.resolve("refs/heads/" + branch); + return oid.name(); + } catch (GitException e) { + throw new RuntimeException(e); } - - }); + } + }); } public static class HasCredentialBuilder extends Builder { @@ -331,7 +415,8 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen build.setResult(Result.FAILURE); return false; } else { - listener.getLogger().printf("Found %s credentials with id %s%n", CredentialsNameProvider.name(credentials), id); + listener.getLogger() + .printf("Found %s credentials with id %s%n", CredentialsNameProvider.name(credentials), id); return true; } } diff --git a/src/test/java/hudson/plugins/git/BranchSpecTest.java b/src/test/java/hudson/plugins/git/BranchSpecTest.java index 58d42e83e4..eaeb0eb8cc 100644 --- a/src/test/java/hudson/plugins/git/BranchSpecTest.java +++ b/src/test/java/hudson/plugins/git/BranchSpecTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import hudson.EnvVars; import java.util.HashMap; -import static org.junit.Assert.*; import org.junit.Test; import org.jvnet.hudson.test.Issue; - public class BranchSpecTest { @Test public void testMatch() { @@ -16,45 +16,44 @@ public void testMatch() { assertFalse(l.matches("origin/something/master")); assertTrue(l.matches("master")); assertFalse(l.matches("dev")); - - + BranchSpec est = new BranchSpec("origin/*/dev"); - + assertFalse(est.matches("origintestdev")); assertTrue(est.matches("origin/test/dev")); assertFalse(est.matches("origin/test/release")); assertFalse(est.matches("origin/test/something/release")); - + BranchSpec s = new BranchSpec("origin/*"); - + assertTrue(s.matches("origin/master")); - + BranchSpec m = new BranchSpec("**/magnayn/*"); - + assertTrue(m.matches("origin/magnayn/b1")); assertTrue(m.matches("remote/origin/magnayn/b1")); assertTrue(m.matches("remotes/origin/magnayn/b1")); - + BranchSpec n = new BranchSpec("*/my.branch/*"); - + assertTrue(n.matches("origin/my.branch/b1")); assertFalse(n.matches("origin/my-branch/b1")); assertFalse(n.matches("remote/origin/my.branch/b1")); assertTrue(n.matches("remotes/origin/my.branch/b1")); - + BranchSpec o = new BranchSpec("**"); - + assertTrue(o.matches("origin/my.branch/b1")); assertTrue(o.matches("origin/my-branch/b1")); assertTrue(o.matches("remote/origin/my.branch/b1")); assertTrue(o.matches("remotes/origin/my.branch/b1")); - + BranchSpec p = new BranchSpec("*"); assertTrue(p.matches("origin/x")); assertFalse(p.matches("origin/my-branch/b1")); } - + @Test public void testMatchEnv() { HashMap envMap = new HashMap<>(); @@ -74,7 +73,6 @@ public void testMatchEnv() { assertTrue(l.matches("master", env)); assertFalse(l.matches("dev", env)); - BranchSpec est = new BranchSpec("${origin}/*/${dev}"); assertFalse(est.matches("origintestdev", env)); @@ -117,55 +115,55 @@ public void testMatchEnv() { @Test public void testEmptyName() { - BranchSpec branchSpec = new BranchSpec(""); - assertEquals("**",branchSpec.getName()); + BranchSpec branchSpec = new BranchSpec(""); + assertEquals("**", branchSpec.getName()); } @Test(expected = IllegalArgumentException.class) public void testNullName() { BranchSpec branchSpec = new BranchSpec(null); } - + @Test public void testNameTrimming() { - BranchSpec branchSpec = new BranchSpec(" master "); - assertEquals("master",branchSpec.getName()); - branchSpec.setName(" other "); - assertEquals("other",branchSpec.getName()); + BranchSpec branchSpec = new BranchSpec(" master "); + assertEquals("master", branchSpec.getName()); + branchSpec.setName(" other "); + assertEquals("other", branchSpec.getName()); } - + @Test public void testUsesRefsHeads() { - BranchSpec m = new BranchSpec("refs/heads/j*n*"); - assertTrue(m.matches("refs/heads/jenkins")); - assertTrue(m.matches("refs/heads/jane")); - assertTrue(m.matches("refs/heads/jones")); + BranchSpec m = new BranchSpec("refs/heads/j*n*"); + assertTrue(m.matches("refs/heads/jenkins")); + assertTrue(m.matches("refs/heads/jane")); + assertTrue(m.matches("refs/heads/jones")); - assertFalse(m.matches("origin/jenkins")); - assertFalse(m.matches("remote/origin/jane")); + assertFalse(m.matches("origin/jenkins")); + assertFalse(m.matches("remote/origin/jane")); } - + @Test public void testUsesJavaPatternDirectlyIfPrefixedWithColon() { - BranchSpec m = new BranchSpec(":^(?!(origin/prefix)).*"); - assertTrue(m.matches("origin")); - assertTrue(m.matches("origin/master")); - assertTrue(m.matches("origin/feature")); - - assertFalse(m.matches("origin/prefix_123")); - assertFalse(m.matches("origin/prefix")); - assertFalse(m.matches("origin/prefix-abc")); + BranchSpec m = new BranchSpec(":^(?!(origin/prefix)).*"); + assertTrue(m.matches("origin")); + assertTrue(m.matches("origin/master")); + assertTrue(m.matches("origin/feature")); + + assertFalse(m.matches("origin/prefix_123")); + assertFalse(m.matches("origin/prefix")); + assertFalse(m.matches("origin/prefix-abc")); } @Test @Issue("JENKINS-26842") public void testUsesJavaPatternWithRepetition() { - // match pattern from JENKINS-26842 - BranchSpec m = new BranchSpec(":origin/release-\\d{8}"); - assertTrue(m.matches("origin/release-20150101")); - assertFalse(m.matches("origin/release-2015010")); - assertFalse(m.matches("origin/release-201501011")); - assertFalse(m.matches("origin/release-20150101-something")); + // match pattern from JENKINS-26842 + BranchSpec m = new BranchSpec(":origin/release-\\d{8}"); + assertTrue(m.matches("origin/release-20150101")); + assertFalse(m.matches("origin/release-2015010")); + assertFalse(m.matches("origin/release-201501011")); + assertFalse(m.matches("origin/release-20150101-something")); } @Test diff --git a/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java b/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java index 4ebe2d6d8e..cfdc6d84ff 100644 --- a/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java +++ b/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java @@ -23,10 +23,11 @@ */ package hudson.plugins.git; -import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; +import org.junit.Test; + public class ChangelogToBranchOptionsTest { private final ChangelogToBranchOptions options; diff --git a/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java b/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java index e854d10232..2e38defdf2 100644 --- a/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java +++ b/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java @@ -56,7 +56,8 @@ public class CheckoutStepSnippetizerTest { private final String remoteName = ""; private final String remoteRefspec = ""; private final String credentialsId = ""; - private final UserRemoteConfig userRemoteConfig = new UserRemoteConfig(url, remoteName, remoteRefspec, credentialsId); + private final UserRemoteConfig userRemoteConfig = + new UserRemoteConfig(url, remoteName, remoteRefspec, credentialsId); private final List userRemoteConfigList = new ArrayList(List.of(userRemoteConfig)); private final String branchName = ""; private final BranchSpec branchSpec = new BranchSpec(branchName); @@ -64,9 +65,11 @@ public class CheckoutStepSnippetizerTest { private final String gitTool = null; private final GitRepositoryBrowser browser = null; private final List extensionList = new ArrayList(); - private final GitSCM databoundGit = new GitSCM(userRemoteConfigList, branchSpecList, browser, gitTool, extensionList); + private final GitSCM databoundGit = + new GitSCM(userRemoteConfigList, branchSpecList, browser, gitTool, extensionList); private final GitSCM convenienceGit = new GitSCM(url); - private final GenericSCMStep checkoutStep = new GenericSCMStep((random.nextBoolean() || true) ? databoundGit : convenienceGit); + private final GenericSCMStep checkoutStep = + new GenericSCMStep((random.nextBoolean() || true) ? databoundGit : convenienceGit); /* Defaults that should be removed from round trip */ private final String junkBranches = "branches: [[name: '**']], "; @@ -77,43 +80,46 @@ public class CheckoutStepSnippetizerTest { @Test public void checkoutSimplest() throws Exception { - tester.assertRoundTrip(checkoutStep, "checkout scmGit(" - + junkBranches - + junkExtensions - + "userRemoteConfigs: [[url: '" + url + "']])"); - tester.assertParseStep(checkoutStep, "checkout scmGit(" - + "branches: [[name: '**']], " - // Parses correctly with or without junkExtensions - + (random.nextBoolean() ? junkExtensions : "") - + remoteConfig + ")"); + tester.assertRoundTrip( + checkoutStep, + "checkout scmGit(" + junkBranches + junkExtensions + "userRemoteConfigs: [[url: '" + url + "']])"); + tester.assertParseStep( + checkoutStep, + "checkout scmGit(" + + "branches: [[name: '**']], " + // Parses correctly with or without junkExtensions + + (random.nextBoolean() ? junkExtensions : "") + + remoteConfig + ")"); } @Test public void checkoutNoPoll() throws Exception { checkoutStep.setPoll(false); - tester.assertRoundTrip(checkoutStep, "checkout poll: false, scm: scmGit(" - + junkBranches - + junkExtensions - + remoteConfig + ")"); - tester.assertParseStep(checkoutStep, "checkout poll: false, scm: scmGit(" - + "branches: [[name: '**']], " - // Parses correctly with or without junkExtensions - + (random.nextBoolean() ? junkExtensions : "") - + remoteConfig + ")"); + tester.assertRoundTrip( + checkoutStep, + "checkout poll: false, scm: scmGit(" + junkBranches + junkExtensions + remoteConfig + ")"); + tester.assertParseStep( + checkoutStep, + "checkout poll: false, scm: scmGit(" + + "branches: [[name: '**']], " + // Parses correctly with or without junkExtensions + + (random.nextBoolean() ? junkExtensions : "") + + remoteConfig + ")"); } @Test public void checkoutNoChangelog() throws Exception { checkoutStep.setChangelog(false); - tester.assertRoundTrip(checkoutStep, "checkout changelog: false, scm: scmGit(" - + junkBranches - + junkExtensions - + remoteConfig + ")"); - tester.assertParseStep(checkoutStep, "checkout changelog: false, scm: scmGit(" - + "branches: [[name: '**']], " - // Parses correctly with or without junkExtensions - + (random.nextBoolean() ? junkExtensions : "") - + remoteConfig + ")"); + tester.assertRoundTrip( + checkoutStep, + "checkout changelog: false, scm: scmGit(" + junkBranches + junkExtensions + remoteConfig + ")"); + tester.assertParseStep( + checkoutStep, + "checkout changelog: false, scm: scmGit(" + + "branches: [[name: '**']], " + // Parses correctly with or without junkExtensions + + (random.nextBoolean() ? junkExtensions : "") + + remoteConfig + ")"); } @Test @@ -123,15 +129,19 @@ public void checkoutCredentials() throws Exception { List configList = new ArrayList(List.of(config)); GitSCM gitSCM = new GitSCM(configList, branchSpecList, browser, gitTool, extensionList); GenericSCMStep step = new GenericSCMStep(gitSCM); - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + junkExtensions - + "userRemoteConfigs: [[credentialsId: '" + myCredential + "', url: '" + url + "']])"); - tester.assertParseStep(step, "checkout scmGit(" - + "branches: [[name: '**']], " - // Parses correctly with or without junkExtensions - + (random.nextBoolean() ? junkExtensions : "") - + "userRemoteConfigs: [[credentialsId: '" + myCredential + "', url: '" + url + "']])"); + tester.assertRoundTrip( + step, + "checkout scmGit(" + + junkBranches + + junkExtensions + + "userRemoteConfigs: [[credentialsId: '" + myCredential + "', url: '" + url + "']])"); + tester.assertParseStep( + step, + "checkout scmGit(" + + "branches: [[name: '**']], " + // Parses correctly with or without junkExtensions + + (random.nextBoolean() ? junkExtensions : "") + + "userRemoteConfigs: [[credentialsId: '" + myCredential + "', url: '" + url + "']])"); } @Test @@ -140,15 +150,16 @@ public void checkoutBranch() throws Exception { List branchList = new ArrayList(List.of(new BranchSpec(branch))); GitSCM gitSCM = new GitSCM(userRemoteConfigList, branchList, browser, gitTool, extensionList); GenericSCMStep step = new GenericSCMStep(gitSCM); - tester.assertRoundTrip(step, "checkout scmGit(" - + "branches: [[name: '" + branch + "']], " - + junkExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + "branches: [[name: '" + branch + "']], " - // Parses correctly with or without junkExtensions - + (random.nextBoolean() ? junkExtensions : "") - + remoteConfig + ")"); + tester.assertRoundTrip( + step, + "checkout scmGit(" + "branches: [[name: '" + branch + "']], " + junkExtensions + remoteConfig + ")"); + tester.assertParseStep( + step, + "checkout scmGit(" + + "branches: [[name: '" + branch + "']], " + // Parses correctly with or without junkExtensions + + (random.nextBoolean() ? junkExtensions : "") + + remoteConfig + ")"); } @Test @@ -158,14 +169,8 @@ public void checkoutSubmoduleSimplest() throws Exception { extensions.add(new SubmoduleOption()); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [submodule()], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -178,17 +183,12 @@ public void checkoutSubmoduleOldConstructorMinimalArgs() throws Exception { String reference = null; Integer timeout = null; boolean parentCredentials = false; - extensions.add(new SubmoduleOption(disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); + extensions.add(new SubmoduleOption( + disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [submodule()], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -201,17 +201,12 @@ public void checkoutSubmoduleOldConstructorReferenceRepo() throws Exception { String reference = "/var/cache/git-plugin.git"; // Only change from default values Integer timeout = null; boolean parentCredentials = false; - extensions.add(new SubmoduleOption(disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); + extensions.add(new SubmoduleOption( + disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [submodule(reference: '" + reference + "')], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -224,17 +219,12 @@ public void checkoutSubmoduleOldConstructorDisableSubmodules() throws Exception String reference = null; Integer timeout = null; boolean parentCredentials = false; - extensions.add(new SubmoduleOption(disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); + extensions.add(new SubmoduleOption( + disableSubmodules, recursiveSubmodules, trackingSubmodules, reference, timeout, parentCredentials)); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [submodule(disableSubmodules: true)], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -245,14 +235,8 @@ public void checkoutTimeoutCheckoutDefault() throws Exception { extensions.add(new CheckoutOption(timeout)); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [checkoutOption()], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -263,14 +247,8 @@ public void checkoutTimeoutCheckoutNonDefault() throws Exception { extensions.add(new CheckoutOption(timeout)); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [checkoutOption(" + timeout + ")], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } @Test @@ -280,13 +258,7 @@ public void checkoutLargeFileSupport() throws Exception { extensions.add(new GitLFSPull()); GenericSCMStep step = new GenericSCMStep(gitSCM); String testedExtensions = "extensions: [lfs()], "; - tester.assertRoundTrip(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); - tester.assertParseStep(step, "checkout scmGit(" - + junkBranches - + testedExtensions - + remoteConfig + ")"); + tester.assertRoundTrip(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); + tester.assertParseStep(step, "checkout scmGit(" + junkBranches + testedExtensions + remoteConfig + ")"); } } diff --git a/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java b/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java index 38c00e23bf..8bdc836738 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java @@ -3,19 +3,15 @@ import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.impl.EnforceGitClient; -public class CliGitSCMTriggerLocalPollTest extends SCMTriggerTest -{ +public class CliGitSCMTriggerLocalPollTest extends SCMTriggerTest { @Override - protected EnforceGitClient getGitClient() - { + protected EnforceGitClient getGitClient() { return new EnforceGitClient().set(GitClientType.GITCLI); } @Override - protected boolean isDisableRemotePoll() - { + protected boolean isDisableRemotePoll() { return true; } - } diff --git a/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java b/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java index 43b2db913f..9565f21d72 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java @@ -12,15 +12,12 @@ public class CliGitSCMTriggerRemotePollTest extends SCMTriggerTest { @Override - protected EnforceGitClient getGitClient() - { + protected EnforceGitClient getGitClient() { return new EnforceGitClient().set(GitClientType.GITCLI); } @Override - protected boolean isDisableRemotePoll() - { + protected boolean isDisableRemotePoll() { return false; } - } diff --git a/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java b/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java index ace2281ff4..236374ea92 100644 --- a/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java @@ -1,5 +1,9 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertTrue; + import com.cloudbees.plugins.credentials.*; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; @@ -20,10 +24,6 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - public class CredentialsUserRemoteConfigTest { @Rule @@ -39,8 +39,8 @@ public class CredentialsUserRemoteConfigTest { @Before public void enableSystemCredentialsProvider() { - SystemCredentialsProvider.getInstance().setDomainCredentialsMap( - Collections.singletonMap(Domain.global(), Collections.emptyList())); + SystemCredentialsProvider.getInstance() + .setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; @@ -99,7 +99,8 @@ private WorkflowJob createProject(boolean useCredential) throws Exception { + randomPipelineCheckoutExtras() + classEpilogue() + " )" - + "}", true)); + + "}", + true)); return p; } @@ -112,9 +113,10 @@ private WorkflowJob createProject(boolean useCredential) throws Exception { */ private String randomPipelineExtensions() { /* Valid extensions to apply to a git checkout */ - String [] extensions = { + String[] extensions = { // ancestorCommitSha1 needs to be a SHA-1 that exists in the repository - "[$class: 'BuildChooserSetting', buildChooser: [$class: 'AncestryBuildChooser', ancestorCommitSha1: '" + SHA_TO_REPLACE + "', maximumAgeInDays: 23]]", + "[$class: 'BuildChooserSetting', buildChooser: [$class: 'AncestryBuildChooser', ancestorCommitSha1: '" + + SHA_TO_REPLACE + "', maximumAgeInDays: 23]]", // Inverse build chooser will find nothing to build and fails the test // "[$class: 'BuildChooserSetting', buildChooser: [$class: 'InverseBuildChooser']]", "[$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [[path: 'src'], [path: 'Makefile']]]", @@ -241,7 +243,12 @@ private String randomPipelineCheckoutExtras() throws Exception { "phabricator(repo: 'source/tool-spacemedia', repoUrl: 'https://phabricator.wikimedia.org/source/tool-spacemedia/')", "redmine('https://www.redmine.org/projects/redmine/repository')", "rhodeCode('https://code.rhodecode.com/rhodecode-enterprise-ce')", - "viewgit(repoUrl: 'https://repo.or.cz/viewgit.git', projectName: 'viewgit-project-name-value')", // Not likely a viewgit site, but reasonable approximation + "viewgit(repoUrl: 'https://repo.or.cz/viewgit.git', projectName: 'viewgit-project-name-value')", // Not + // likely a + // viewgit + // site, + // but + // reasonable approximation // The Gitea browser is provided by the Gitea plugin, not the git plugin // "[$class: 'GiteaBrowser', repoUrl: 'https://try.gitea.io/MarkEWaite/git-plugin']", }; @@ -284,10 +291,12 @@ public void checkoutWithDifferentCredentials() throws Exception { "node {\n" + " checkout(\n" + classPrologue() - + " userRemoteConfigs: [[credentialsId: '" + notOtherCredential + "', url: $/" + sampleRepo + "/$]]\n" + + " userRemoteConfigs: [[credentialsId: '" + notOtherCredential + "', url: $/" + sampleRepo + + "/$]]\n" + classEpilogue() + " )" - + "}", true)); + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("Warning: CredentialId \"" + notOtherCredential + "\" could not be found", b); } @@ -304,10 +313,12 @@ public void checkoutWithInvalidCredentials() throws Exception { "node {\n" + " checkout(\n" + classPrologue() - + " userRemoteConfigs: [[credentialsId: '" + systemCredential + "', url: $/" + sampleRepo + "/$]]\n" + + " userRemoteConfigs: [[credentialsId: '" + systemCredential + "', url: $/" + sampleRepo + + "/$]]\n" + classEpilogue() + " )" - + "}", true)); + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("Warning: CredentialId \"" + systemCredential + "\" could not be found", b); } @@ -320,10 +331,12 @@ public void checkoutWithNoCredentialsStoredButUsed() throws Exception { "node {\n" + " checkout(\n" + classPrologue() - + " userRemoteConfigs: [[credentialsId: '" + credential + "', url: $/" + sampleRepo + "/$]]\n" + + " userRemoteConfigs: [[credentialsId: '" + credential + "', url: $/" + sampleRepo + + "/$]]\n" + classEpilogue() + " )" - + "}", true)); + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("Warning: CredentialId \"" + credential + "\" could not be found", b); } @@ -339,7 +352,8 @@ public void checkoutWithNoCredentialsSpecified() throws Exception { + " userRemoteConfigs: [[url: $/" + sampleRepo + "/$]]\n" + classEpilogue() + " )" - + "}", true)); + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("No credentials specified", b); } diff --git a/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java b/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java index 1113899fd4..833d9b5efb 100644 --- a/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java +++ b/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java @@ -23,22 +23,22 @@ */ package hudson.plugins.git; -import hudson.model.Item; -import java.util.ArrayList; -import java.util.List; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import hudson.model.Item; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + /** * @author Mark Waite */ public class GitBranchSpecifierColumnTest { - public GitBranchSpecifierColumnTest() { - } + public GitBranchSpecifierColumnTest() {} @Test public void testGetBranchSpecifierNull() { diff --git a/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java b/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java index 7686f02bd7..68f6b96cd1 100644 --- a/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java @@ -1,19 +1,19 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import hudson.EnvVars; import hudson.model.TaskListener; +import java.io.File; +import java.io.FileWriter; import org.jenkinsci.plugins.gitclient.CliGitAPIImpl; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.JGitAPIImpl; - -import java.io.File; -import java.io.FileWriter; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -26,13 +26,17 @@ public class GitChangeLogParserTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); - private final String firstMessageTruncated = "123456789 123456789 123456789 123456789 123456789 123456789 123456789 1"; + private final String firstMessageTruncated = + "123456789 123456789 123456789 123456789 123456789 123456789 123456789 1"; private final String firstMessage = firstMessageTruncated + " 345 789"; /* Test duplicate changes filtered from parsed CLI git change set list. */ @Test public void testDuplicatesFilteredCliGit() throws Exception { - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).using("Default").in(new File(".")).getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .using("Default") + .in(new File(".")) + .getClient(); assertThat(gitClient, instanceOf(CliGitAPIImpl.class)); /* JENKINS-29977 notes that CLI git impl truncates summary message - confirm default behavior retained */ generateDuplicateChanges(gitClient, firstMessageTruncated); @@ -41,7 +45,10 @@ public void testDuplicatesFilteredCliGit() throws Exception { /* Test duplicate changes filtered from parsed JGit change set list. */ @Test public void testDuplicatesFilteredJGit() throws Exception { - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).using("jgit").in(new File(".")).getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .using("jgit") + .in(new File(".")) + .getClient(); assertThat(gitClient, instanceOf(JGitAPIImpl.class)); /* JENKINS-29977 notes that JGit impl retains full summary message - confirm default behavior retained */ generateDuplicateChanges(gitClient, firstMessage); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java b/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java index 001659e7e8..f7eac114f8 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java @@ -1,13 +1,11 @@ package hudson.plugins.git; -import java.util.ArrayList; +import static org.junit.Assert.*; import hudson.model.User; - -import org.junit.Test; -import static org.junit.Assert.*; +import java.util.ArrayList; import org.junit.Rule; - +import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; public class GitChangeSetBadArgsTest { @@ -61,7 +59,8 @@ public void testFindOrCreateUserAuthorBadEmail() { public void testFindOrCreateUserCommitterBadEmail() { String committerName = "Bad Committer Test 2"; GitChangeSet changeSet = createCommitterChangeSet(committerName, DEGENERATE_EMAIL_ADDRESS); - assertEquals(User.getUnknown(), changeSet.findOrCreateUser(committerName, DEGENERATE_EMAIL_ADDRESS, false, false)); + assertEquals( + User.getUnknown(), changeSet.findOrCreateUser(committerName, DEGENERATE_EMAIL_ADDRESS, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser(null, DEGENERATE_EMAIL_ADDRESS, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser("", DEGENERATE_EMAIL_ADDRESS, false, false)); } @@ -71,7 +70,8 @@ public void testFindOrCreateUserEmptyAuthor() { String emptyAuthorName = ""; String incompleteAuthorEmail = "@test3.example.com"; GitChangeSet changeSet = createAuthorChangeSet(emptyAuthorName, incompleteAuthorEmail); - assertEquals(User.getUnknown(), changeSet.findOrCreateUser(emptyAuthorName, incompleteAuthorEmail, false, false)); + assertEquals( + User.getUnknown(), changeSet.findOrCreateUser(emptyAuthorName, incompleteAuthorEmail, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser(null, incompleteAuthorEmail, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser("", incompleteAuthorEmail, false, false)); } @@ -81,7 +81,9 @@ public void testFindOrCreateEmptyCommitter() { String emptyCommitterName = ""; String incompleteCommitterEmail = "@test4.example.com"; GitChangeSet changeSet = createCommitterChangeSet(emptyCommitterName, incompleteCommitterEmail); - assertEquals(User.getUnknown(), changeSet.findOrCreateUser(emptyCommitterName, incompleteCommitterEmail, false, false)); + assertEquals( + User.getUnknown(), + changeSet.findOrCreateUser(emptyCommitterName, incompleteCommitterEmail, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser(null, incompleteCommitterEmail, false, false)); assertEquals(User.getUnknown(), changeSet.findOrCreateUser("", incompleteCommitterEmail, false, false)); } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java b/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java index 898d0f9736..3632420570 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java @@ -1,13 +1,13 @@ package hudson.plugins.git; -import java.util.ArrayList; -import java.util.Collections; - import static hudson.plugins.git.GitChangeSet.TRUNCATE_LIMIT; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.Collections; import org.junit.Test; public class GitChangeSetBasicTest { @@ -22,8 +22,9 @@ private GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFo @Test public void testLegacyChangeSet() { - GitChangeSet gitChangeSet = GitChangeSetUtil.genChangeSet(false, true, false, GitChangeSetUtil.COMMIT_TITLE ,false); - GitChangeSetUtil.assertChangeSet( gitChangeSet ); + GitChangeSet gitChangeSet = + GitChangeSetUtil.genChangeSet(false, true, false, GitChangeSetUtil.COMMIT_TITLE, false); + GitChangeSetUtil.assertChangeSet(gitChangeSet); } @Test @@ -41,7 +42,8 @@ public void testChangeSetNoParent() { @Test public void testCommitter() { assertEquals(GitChangeSetUtil.COMMITTER_NAME, genChangeSet(false, false).getAuthorName()); - assertEquals(GitChangeSetUtil.COMMITTER_EMAIL, genChangeSet(false, false).getAuthorEmail()); + assertEquals( + GitChangeSetUtil.COMMITTER_EMAIL, genChangeSet(false, false).getAuthorEmail()); } @Test @@ -63,7 +65,8 @@ public void testGetTimestamp() { @Test public void testInvalidDate() { final String badDateString = "2015-03-03x09:22:42 -0700"; - GitChangeSet c = new GitChangeSet(Collections.singletonList("author John Doe " + badDateString), true); + GitChangeSet c = new GitChangeSet( + Collections.singletonList("author John Doe " + badDateString), true); assertEquals(badDateString, c.getDate()); assertEquals(-1L, c.getTimestamp()); } @@ -71,15 +74,18 @@ public void testInvalidDate() { @Test public void testIsoDate() { - GitChangeSet c = new GitChangeSet(Collections.singletonList("author John Doe 2015-03-03T09:22:42-0700"), true); + GitChangeSet c = new GitChangeSet( + Collections.singletonList("author John Doe 2015-03-03T09:22:42-0700"), true); assertEquals("2015-03-03T09:22:42-0700", c.getDate()); assertEquals(1425399762000L, c.getTimestamp()); - c = new GitChangeSet(Collections.singletonList("author John Doe 2015-03-03T09:22:42-07:00"), true); + c = new GitChangeSet( + Collections.singletonList("author John Doe 2015-03-03T09:22:42-07:00"), true); assertEquals("2015-03-03T09:22:42-07:00", c.getDate()); assertEquals(1425399762000L, c.getTimestamp()); - c = new GitChangeSet(Collections.singletonList("author John Doe 2015-03-03T16:22:42Z"), true); + c = new GitChangeSet( + Collections.singletonList("author John Doe 2015-03-03T16:22:42Z"), true); assertEquals("2015-03-03T16:22:42Z", c.getDate()); assertEquals(1425399762000L, c.getTimestamp()); @@ -87,7 +93,8 @@ public void testIsoDate() { assertEquals("2015-03-03T16:22:42Z", c.getDate()); assertEquals(1425399762000L, c.getTimestamp()); - c = new GitChangeSet(Collections.singletonList("author John Doe 1425374562 -0700"), true); + c = new GitChangeSet( + Collections.singletonList("author John Doe 1425374562 -0700"), true); assertEquals("2015-03-03T09:22:42-0700", c.getDate()); assertEquals(1425399762000L, c.getTimestamp()); } @@ -113,7 +120,7 @@ private GitChangeSet genChangeSetForSwedCase(boolean authorOrCommitter) { lines.add(" Tested-by: Jenkins "); lines.add(" Reviewed-by: Mister Another "); lines.add(""); - //above lines all on purpose vs specific troublesome case @ericsson. + // above lines all on purpose vs specific troublesome case @ericsson. return new GitChangeSet(lines, authorOrCommitter); } @@ -138,19 +145,20 @@ public void testSwedishTimestamp() { } @Test - public void testChangeLogTruncationWithShortMessage(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - "Lorem ipsum dolor sit amet.", - false); + public void testChangeLogTruncationWithShortMessage() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "Lorem ipsum dolor sit amet.", false); String msg = changeSet.getMsg(); - assertThat("Title is correct ", msg, containsString("Lorem ipsum dolor sit amet.") ); + assertThat("Title is correct ", msg, containsString("Lorem ipsum dolor sit amet.")); assertThat("Title length is correct ", msg.length(), lessThanOrEqualTo(TRUNCATE_LIMIT)); } @Test - public void testChangeLogTruncationWithNewLine(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - "Lorem ipsum dolor sit amet, "+System.lineSeparator()+"consectetur adipiscing elit.", + public void testChangeLogTruncationWithNewLine() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, + "Lorem ipsum dolor sit amet, " + System.lineSeparator() + "consectetur adipiscing elit.", false); String msg = changeSet.getMsg(); assertThat(msg, is("Lorem ipsum dolor sit amet,")); @@ -158,72 +166,88 @@ public void testChangeLogTruncationWithNewLine(){ } @Test - public void testChangeLogRetainSummaryWithoutNewLine(){ - String originalCommitMessage = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - originalCommitMessage, - true); + public void testChangeLogRetainSummaryWithoutNewLine() { + String originalCommitMessage = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, originalCommitMessage, true); assertThat(changeSet.getMsg(), is(originalCommitMessage)); } @Test - public void testChangeLogDoNotRetainSummaryWithoutNewLine(){ - String msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - msg, - false); + public void testChangeLogDoNotRetainSummaryWithoutNewLine() { + String msg = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, msg, false); assertThat(changeSet.getMsg(), is("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus")); } @Test - public void testChangeLogNoTruncationWithNewLine(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - "Lorem ipsum dolor sit amet, consectetur "+System.lineSeparator()+" adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit", + public void testChangeLogNoTruncationWithNewLine() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, + "Lorem ipsum dolor sit amet, consectetur " + System.lineSeparator() + + " adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit", true); String msg = changeSet.getMsg(); - assertThat("Title is correct ", msg, is("Lorem ipsum dolor sit amet, consectetur") ); + assertThat("Title is correct ", msg, is("Lorem ipsum dolor sit amet, consectetur")); } @Test - public void testChangeLogEdgeCaseNotTruncating(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, + public void testChangeLogEdgeCaseNotTruncating() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", false); String msg = changeSet.getMsg(); - assertThat( msg.length(), lessThanOrEqualTo( TRUNCATE_LIMIT )); - assertThat( msg, is("[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2") ); + assertThat(msg.length(), lessThanOrEqualTo(TRUNCATE_LIMIT)); + assertThat(msg, is("[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2")); } @Test - public void testChangeLogEdgeCaseTruncating(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, + public void testChangeLogEdgeCaseTruncating() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", true); String msg = changeSet.getMsg(); - assertThat( msg, is("[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5") ); + assertThat(msg, is("[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5")); } @Test - public void testChangeLogEdgeCaseTruncatingAndNewLine(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, - "[JENKINS-012345] 8901 34567 " + System.lineSeparator() + "90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", + public void testChangeLogEdgeCaseTruncatingAndNewLine() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, + "[JENKINS-012345] 8901 34567 " + System.lineSeparator() + + "90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", true); String msg = changeSet.getMsg(); - assertThat( msg, is("[JENKINS-012345] 8901 34567") ); + assertThat(msg, is("[JENKINS-012345] 8901 34567")); } @Test - public void testLongString(){ - GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, + public void testLongString() { + GitChangeSet changeSet = GitChangeSetUtil.genChangeSet( + true, + false, + true, "12345678901234567890123456789012345678901234567890123456789012345678901234567890", false); String msg = changeSet.getMsg(); - assertThat( msg, is("12345678901234567890123456789012345678901234567890123456789012345678901234567890") ); + assertThat(msg, is("12345678901234567890123456789012345678901234567890123456789012345678901234567890")); } @Test - public void stringSplitter(){ - String msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; + public void stringSplitter() { + String msg = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; assertThat(GitChangeSet.splitString(msg, 15), is("Lorem ipsum")); assertThat(GitChangeSet.splitString(msg, 16), is("Lorem ipsum")); assertThat(GitChangeSet.splitString(msg, 17), is("Lorem ipsum dolor")); @@ -233,23 +257,27 @@ public void stringSplitter(){ assertThat(GitChangeSet.splitString(msg, 21), is("Lorem ipsum dolor sit")); assertThat(GitChangeSet.splitString(msg, 22), is("Lorem ipsum dolor sit")); - msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum."; - assertThat(GitChangeSet.splitString(msg, TRUNCATE_LIMIT), + msg = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum."; + assertThat( + GitChangeSet.splitString(msg, TRUNCATE_LIMIT), is("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus")); } @Test - public void splitingWithBrackets(){ - assertThat(GitChangeSet.splitString("[task] Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 25), is("[task] Lorem ipsum dolor")); + public void splitingWithBrackets() { + assertThat( + GitChangeSet.splitString("[task] Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 25), + is("[task] Lorem ipsum dolor")); } @Test - public void splitingEmptyString(){ + public void splitingEmptyString() { assertThat(GitChangeSet.splitString("", 25), is("")); } @Test - public void splitingNullString(){ + public void splitingNullString() { assertThat(GitChangeSet.splitString(null, 25), is("")); } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java b/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java index b813156066..7599cd3fc3 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java @@ -1,16 +1,16 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import java.util.ArrayList; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; public class GitChangeSetEmptyTest { private GitChangeSet changeSet = null; - public GitChangeSetEmptyTest() { - } + public GitChangeSetEmptyTest() {} @Before public void createEmptyChangeSet() { @@ -98,5 +98,4 @@ public void testEquals() { assertEquals(changeSet, changeSet); assertNotEquals(changeSet, GitChangeSetUtil.genChangeSet(true, true)); } - } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java b/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java index 77e78c5477..0706e7e248 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java @@ -1,11 +1,12 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/src/test/java/hudson/plugins/git/GitChangeSetListTest.java b/src/test/java/hudson/plugins/git/GitChangeSetListTest.java index b2fb32f864..094180f5b0 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetListTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetListTest.java @@ -23,18 +23,18 @@ */ package hudson.plugins.git; -import hudson.model.Run; -import hudson.scm.RepositoryBrowser; -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; - -import org.junit.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; + +import hudson.model.Run; +import hudson.scm.RepositoryBrowser; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.junit.Before; +import org.junit.Test; public class GitChangeSetListTest { diff --git a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java index 53bf18397a..61f08d807c 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java @@ -1,37 +1,32 @@ package hudson.plugins.git; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - -import org.eclipse.jgit.lib.ObjectId; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; import hudson.EnvVars; import hudson.FilePath; import hudson.model.TaskListener; import hudson.util.StreamTaskListener; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import jenkins.plugins.git.GitSampleRepoRule; +import org.eclipse.jgit.lib.ObjectId; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import jenkins.plugins.git.GitSampleRepoRule; - @RunWith(Parameterized.class) public class GitChangeSetPluginHistoryTest { @@ -65,11 +60,13 @@ public class GitChangeSetPluginHistoryTest { "edf066f3", }; - public GitChangeSetPluginHistoryTest(GitClient git, boolean authorOrCommitter, String sha1String) throws IOException, InterruptedException { + public GitChangeSetPluginHistoryTest(GitClient git, boolean authorOrCommitter, String sha1String) + throws IOException, InterruptedException { this.sha1 = ObjectId.fromString(sha1String); StringWriter stringWriter = new StringWriter(); git.changelog().includes(sha1).max(1).to(stringWriter).execute(); - List changeLogStrings = new ArrayList<>(Arrays.asList(stringWriter.toString().split("\n"))); + List changeLogStrings = + new ArrayList<>(Arrays.asList(stringWriter.toString().split("\n"))); changeSet = new GitChangeSet(changeLogStrings, authorOrCommitter); } @@ -97,13 +94,16 @@ private static List getNonMergeChanges() throws IOException { @Parameterized.Parameters(name = "{2}-{1}") public static Collection generateData() throws IOException, InterruptedException { List args = new ArrayList<>(); - String[] implementations = new String[]{"git", "jgit"}; + String[] implementations = new String[] {"git", "jgit"}; boolean[] choices = {true, false}; for (final String implementation : implementations) { EnvVars envVars = new EnvVars(); TaskListener listener = StreamTaskListener.fromStdout(); - GitClient git = Git.with(listener, envVars).in(new FilePath(new File("."))).using(implementation).getClient(); + GitClient git = Git.with(listener, envVars) + .in(new FilePath(new File("."))) + .using(implementation) + .getClient(); List allNonMergeChanges = getNonMergeChanges(); int count = allNonMergeChanges.size() / 10; /* 10% of all changes */ diff --git a/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java b/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java index e0b67e4785..493ed57a4c 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java @@ -1,12 +1,5 @@ package hudson.plugins.git; -import hudson.scm.EditType; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import org.junit.Before; -import org.junit.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; @@ -15,6 +8,14 @@ import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + +import hudson.scm.EditType; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -65,40 +66,42 @@ public void testChangeSetDetails() { Collection actualPaths = changeSet.getPaths(); assertEquals(6, actualPaths.size()); for (GitChangeSet.Path path : actualPaths) { - if (null != path.getPath()) switch (path.getPath()) { - case "src/test/add.file": - assertEquals(EditType.ADD, path.getEditType()); - assertNull(path.getSrc()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); - break; - case "src/test/deleted.file": - assertEquals(EditType.DELETE, path.getEditType()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - assertNull(path.getDst()); - break; - case "src/test/modified.file": - assertEquals(EditType.EDIT, path.getEditType()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/renamedFrom.file": - assertEquals(EditType.DELETE, path.getEditType()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/renamedTo.file": - assertEquals(EditType.ADD, path.getEditType()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/copyOf.file": - assertEquals(EditType.ADD, path.getEditType()); - assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); - assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); - break; - default: - fail("Unrecognized path."); - break; + if (null != path.getPath()) { + switch (path.getPath()) { + case "src/test/add.file": + assertEquals(EditType.ADD, path.getEditType()); + assertNull(path.getSrc()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + break; + case "src/test/deleted.file": + assertEquals(EditType.DELETE, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertNull(path.getDst()); + break; + case "src/test/modified.file": + assertEquals(EditType.EDIT, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/renamedFrom.file": + assertEquals(EditType.DELETE, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/renamedTo.file": + assertEquals(EditType.ADD, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/copyOf.file": + assertEquals(EditType.ADD, path.getEditType()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + break; + default: + fail("Unrecognized path."); + break; + } } } } @@ -126,12 +129,16 @@ public void testGetAffectedFiles() { @Test public void testGetAuthorName() { - assertEquals(useAuthorName ? GitChangeSetUtil.AUTHOR_NAME : GitChangeSetUtil.COMMITTER_NAME, changeSet.getAuthorName()); + assertEquals( + useAuthorName ? GitChangeSetUtil.AUTHOR_NAME : GitChangeSetUtil.COMMITTER_NAME, + changeSet.getAuthorName()); } @Test public void testGetDate() { - assertEquals(useAuthorName ? GitChangeSetUtil.AUTHOR_DATE_FORMATTED : GitChangeSetUtil.COMMITTER_DATE_FORMATTED, changeSet.getDate()); + assertEquals( + useAuthorName ? GitChangeSetUtil.AUTHOR_DATE_FORMATTED : GitChangeSetUtil.COMMITTER_DATE_FORMATTED, + changeSet.getDate()); } @Test @@ -152,7 +159,9 @@ public void testGetRevision() { @Test public void testGetComment() { String changeComment = changeSet.getComment(); - assertTrue("Comment '" + changeComment + "' does not start with '" + GitChangeSetUtil.COMMENT + "'", changeComment.startsWith(GitChangeSetUtil.COMMENT)); + assertTrue( + "Comment '" + changeComment + "' does not start with '" + GitChangeSetUtil.COMMENT + "'", + changeComment.startsWith(GitChangeSetUtil.COMMENT)); } @Test @@ -176,8 +185,7 @@ public void testChangeSetExceptionMessage() { final String expectedLineContent = "commit "; ArrayList lines = new ArrayList<>(); lines.add(expectedLineContent); - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> new GitChangeSet(lines, true)); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new GitChangeSet(lines, true)); assertThat(e.getMessage(), containsString("Commit has no ID[" + expectedLineContent + "]")); } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTest.java index 974a31010d..cd1ce04936 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTest.java @@ -1,26 +1,25 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; + import hudson.model.User; import hudson.tasks.Mailer; import hudson.tasks.Mailer.UserProperty; +import java.io.IOException; +import java.util.Collections; +import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.MockedStatic; import org.springframework.security.authentication.DisabledException; -import java.io.IOException; -import java.util.Collections; -import java.util.Random; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.times; - public class GitChangeSetTest { @Rule @@ -35,7 +34,8 @@ public void testFindOrCreateUser() { final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = false; - User user = committerCS.findOrCreateUser(GitChangeSetUtil.AUTHOR_NAME, email, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = committerCS.findOrCreateUser( + GitChangeSetUtil.AUTHOR_NAME, email, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertNotNull(user); UserProperty property = user.getProperty(Mailer.UserProperty.class); @@ -45,8 +45,10 @@ public void testFindOrCreateUser() { assertNotNull(address); assertEquals(email, address); - assertEquals(User.getUnknown(), committerCS.findOrCreateUser(null, email, false, useExistingAccountBasedOnEmail)); - assertEquals(User.getUnknown(), committerCS.findOrCreateUser(null, email, true, useExistingAccountBasedOnEmail)); + assertEquals( + User.getUnknown(), committerCS.findOrCreateUser(null, email, false, useExistingAccountBasedOnEmail)); + assertEquals( + User.getUnknown(), committerCS.findOrCreateUser(null, email, true, useExistingAccountBasedOnEmail)); } @Test @@ -56,7 +58,8 @@ public void testFindOrCreateUserNullAuthorEmail() { final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = "ada"; final String csAuthorEmail = null; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user, is(User.getUnknown())); } @@ -67,7 +70,8 @@ public void testFindOrCreateUserEmptyAuthorEmail() { final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = "babbage"; final String csAuthorEmail = ""; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user, is(User.getUnknown())); } @@ -78,7 +82,8 @@ public void testFindOrCreateUserEmptyAuthorEmailDoNotCreateAccountBasedOnEmail() final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = "babbage-do-not-create"; final String csAuthorEmail = ""; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user, is(User.getUnknown())); } @@ -89,7 +94,8 @@ public void testFindOrCreateUserEmptyAuthorDoNotCreateAccountBasedOnEmail() { final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = ""; final String csAuthorEmail = "babbage-empty-author@example.com"; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user, is(User.getUnknown())); } @@ -100,7 +106,8 @@ public void testFindOrCreateUserBadAuthorEmailDoNotCreateAccountBasedOnEmail() { final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = "babbage-do-not-create"; final String csAuthorEmail = "@"; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user, is(User.getUnknown())); } @@ -111,7 +118,8 @@ public void testFindOrCreateUserOKAuthorEmailDoNotCreateAccountBasedOnEmail() { final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); final String csAuthor = "babbage-will-be-created"; final String csAuthorEmail = csAuthor + "@"; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user.getFullName(), is(csAuthor)); } @@ -122,7 +130,8 @@ public void testFindOrCreateUserBlankAuthorEmail() { final boolean useExistingAccountBasedOnEmail = false; final String csAuthor = "candide"; final String csAuthorEmail = " "; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user.getFullName(), is(csAuthor)); } @@ -133,7 +142,8 @@ public void testFindOrCreateUserBlankAuthorEmailUseExistingAccountBasedOnEmail() final boolean useExistingAccountBasedOnEmail = true; final String csAuthor = "cosimo"; final String csAuthorEmail = " "; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user.getFullName(), is(csAuthor)); } @@ -144,7 +154,8 @@ public void testFindOrCreateUserValidAuthorEmailUseExistingAccountBasedOnEmail() final boolean useExistingAccountBasedOnEmail = true; final String csAuthor = "dante"; final String csAuthorEmail = "alighieri@example.com"; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user.getFullName(), is(csAuthor)); } @@ -155,39 +166,36 @@ public void testFindOrCreateUserUseExistingAuthorEmailUseExistingAccountBasedOnE final boolean useExistingAccountBasedOnEmail = true; final String csAuthor = "ecco"; final String csAuthorEmail = "umberto@example.com"; - User user = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(user.getFullName(), is(csAuthor)); /* Confirm that second search returns user created by first search */ - User existing = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User existing = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertThat(existing, is(user)); } - @Test - public void testFindOrCreateUserHandlesAuthenticationException() { + @Test + public void testFindOrCreateUserHandlesAuthenticationException() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); // TODO this only test one code path, there are several code paths using User.get() final boolean createAccountBasedOnEmail = false; final boolean useExistingAccountBasedOnEmail = true; final String csAuthor = "disabled_user"; - final String csAuthorEmail = "disabled_user@example.com"; + final String csAuthorEmail = "disabled_user@example.com"; try (MockedStatic user = mockStatic(User.class)) { user.when(() -> User.get("disabled_user", createAccountBasedOnEmail, Collections.emptyMap())) - .thenThrow(new DisabledException("The user \"disabled_user\" is administratively disabled")); + .thenThrow(new DisabledException("The user \"disabled_user\" is administratively disabled")); - User actual = changeset.findOrCreateUser(csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User actual = changeset.findOrCreateUser( + csAuthor, csAuthorEmail, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertEquals(User.getUnknown(), actual); - user.verify( - () -> User.get("disabled_user", createAccountBasedOnEmail, Collections.emptyMap()), - times(1) - ); - user.verify( - User::getUnknown, - times(2) - ); + user.verify(() -> User.get("disabled_user", createAccountBasedOnEmail, Collections.emptyMap()), times(1)); + user.verify(User::getUnknown, times(2)); } - } + } @Test @Deprecated // Test deprecated User.get() @@ -206,7 +214,8 @@ public void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { existingUser.setFullName(existingUserFullName); existingUser.addProperty(new Mailer.UserProperty(email)); - User user = committerCS.findOrCreateUser(GitChangeSetUtil.COMMITTER_NAME, email, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); + User user = committerCS.findOrCreateUser( + GitChangeSetUtil.COMMITTER_NAME, email, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertNotNull(user); assertEquals(user.getId(), existingUserId); assertEquals(user.getFullName(), existingUserFullName); @@ -218,8 +227,10 @@ public void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { assertNotNull(address); assertEquals(email, address); - assertEquals(User.getUnknown(), committerCS.findOrCreateUser(null, email, false, useExistingAccountBasedOnEmail)); - assertEquals(User.getUnknown(), committerCS.findOrCreateUser(null, email, true, useExistingAccountBasedOnEmail)); + assertEquals( + User.getUnknown(), committerCS.findOrCreateUser(null, email, false, useExistingAccountBasedOnEmail)); + assertEquals( + User.getUnknown(), committerCS.findOrCreateUser(null, email, true, useExistingAccountBasedOnEmail)); } @Test diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java index 90b6083228..dc25003340 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java @@ -1,12 +1,13 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java index f036d89ee1..228604ef54 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java @@ -1,5 +1,10 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + +import hudson.model.TaskListener; +import hudson.plugins.git.util.GitUtilsTest; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; @@ -12,20 +17,13 @@ import java.util.List; import java.util.Random; import java.util.UUID; - -import hudson.plugins.git.util.GitUtilsTest; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; - -import hudson.model.TaskListener; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; @@ -59,8 +57,8 @@ public class GitChangeSetTruncateTest { private static class TestData { - final public String testDataCommitSummary; - final public String testDataTruncatedSummary; + public final String testDataCommitSummary; + public final String testDataTruncatedSummary; TestData(String commitSummary, String truncatedSummary) { this.testDataCommitSummary = commitSummary; @@ -70,25 +68,29 @@ private static class TestData { // 1 2 3 4 5 6 7 // 1234567890123456789012345678901234567890123456789012345678901234567890 - private final static String SEVENTY_CHARS = "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0"; - private final static String EIGHTY_CHARS = "12345678901234567890123456789012345678901234567890123456789012345678901234567890"; - - private final static TestData[] TEST_DATA = { - new TestData(EIGHTY_CHARS, EIGHTY_CHARS), // surprising that longer than 72 is returned - new TestData(EIGHTY_CHARS + " A B C", EIGHTY_CHARS), // surprising that longer than 72 is returned - new TestData(SEVENTY_CHARS, SEVENTY_CHARS), - new TestData(SEVENTY_CHARS + " 2", SEVENTY_CHARS + " 2"), - new TestData(SEVENTY_CHARS + " 2 4", SEVENTY_CHARS + " 2"), - new TestData(SEVENTY_CHARS + " 23", SEVENTY_CHARS), - new TestData(SEVENTY_CHARS + " 2&4", SEVENTY_CHARS), - new TestData(SEVENTY_CHARS + "1", SEVENTY_CHARS + "1"), - new TestData(SEVENTY_CHARS + "1 3", SEVENTY_CHARS + "1"), - new TestData(SEVENTY_CHARS + "1 <4", SEVENTY_CHARS + "1"), - new TestData(SEVENTY_CHARS + "1 3 5", SEVENTY_CHARS + "1"), - new TestData(SEVENTY_CHARS + "1;", SEVENTY_CHARS + "1;"), - new TestData(SEVENTY_CHARS + "1; 4", SEVENTY_CHARS + "1;"), - new TestData(SEVENTY_CHARS + " " + SEVENTY_CHARS, SEVENTY_CHARS), - new TestData(SEVENTY_CHARS + " " + SEVENTY_CHARS, SEVENTY_CHARS + " ") // surprising that trailing space is preserved + private static final String SEVENTY_CHARS = + "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0"; + private static final String EIGHTY_CHARS = + "12345678901234567890123456789012345678901234567890123456789012345678901234567890"; + + private static final TestData[] TEST_DATA = { + new TestData(EIGHTY_CHARS, EIGHTY_CHARS), // surprising that longer than 72 is returned + new TestData(EIGHTY_CHARS + " A B C", EIGHTY_CHARS), // surprising that longer than 72 is returned + new TestData(SEVENTY_CHARS, SEVENTY_CHARS), + new TestData(SEVENTY_CHARS + " 2", SEVENTY_CHARS + " 2"), + new TestData(SEVENTY_CHARS + " 2 4", SEVENTY_CHARS + " 2"), + new TestData(SEVENTY_CHARS + " 23", SEVENTY_CHARS), + new TestData(SEVENTY_CHARS + " 2&4", SEVENTY_CHARS), + new TestData(SEVENTY_CHARS + "1", SEVENTY_CHARS + "1"), + new TestData(SEVENTY_CHARS + "1 3", SEVENTY_CHARS + "1"), + new TestData(SEVENTY_CHARS + "1 <4", SEVENTY_CHARS + "1"), + new TestData(SEVENTY_CHARS + "1 3 5", SEVENTY_CHARS + "1"), + new TestData(SEVENTY_CHARS + "1;", SEVENTY_CHARS + "1;"), + new TestData(SEVENTY_CHARS + "1; 4", SEVENTY_CHARS + "1;"), + new TestData(SEVENTY_CHARS + " " + SEVENTY_CHARS, SEVENTY_CHARS), + new TestData( + SEVENTY_CHARS + " " + SEVENTY_CHARS, + SEVENTY_CHARS + " ") // surprising that trailing space is preserved }; public GitChangeSetTruncateTest(String gitImpl, String commitSummary, String truncatedSummary) throws Exception { @@ -96,11 +98,14 @@ public GitChangeSetTruncateTest(String gitImpl, String commitSummary, String tru this.commitSummary = commitSummary; this.truncatedSummary = truncatedSummary; GitClient gitClient = Git.with(TaskListener.NULL, GitUtilsTest.getConfigNoSystemEnvsVars()) - .in(repoRoot).using(gitImpl).getClient(); + .in(repoRoot) + .using(gitImpl) + .getClient(); final ObjectId head = commitOneFile(gitClient, commitSummary); StringWriter changelogStringWriter = new StringWriter(); gitClient.changelog().includes(head).to(changelogStringWriter).execute(); - List changeLogList = Arrays.asList(changelogStringWriter.toString().split("\n")); + List changeLogList = + Arrays.asList(changelogStringWriter.toString().split("\n")); changeSet = new GitChangeSet(changeLogList, random.nextBoolean()); changeSetFullSummary = new GitChangeSet(changeLogList, random.nextBoolean(), true); changeSetTruncatedSummary = new GitChangeSet(changeLogList, random.nextBoolean(), false); @@ -127,7 +132,9 @@ public static void createRepo() throws Exception { String initialImpl = random.nextBoolean() ? "git" : "jgit"; GitClient gitClient = Git.with(TaskListener.NULL, GitUtilsTest.getConfigNoSystemEnvsVars()) - .in(repoRoot).using(initialImpl).getClient(); + .in(repoRoot) + .using(initialImpl) + .getClient(); gitClient.init_().workspace(repoRoot.getAbsolutePath()).execute(); String[] expectedResult = {""}; CliGitCommand gitCmd = new CliGitCommand(gitClient, "config", "user.name", "ChangeSet Truncation Test"); @@ -143,7 +150,8 @@ private ObjectId commitOneFile(GitClient gitClient, final String commitSummary) String path = "One-File.txt"; String content = String.format("A random UUID: %s\n", UUID.randomUUID()); /* randomize whether commit message is single line or multi-line */ - String commitMessageBody = random.nextBoolean() ? "\n\n" + "committing " + path + " with content:\n\n" + content : ""; + String commitMessageBody = + random.nextBoolean() ? "\n\n" + "committing " + path + " with content:\n\n" + content : ""; String commitMessage = commitSummary + commitMessageBody; createFile(path, content); gitClient.add(path); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java index d498e8b278..19eb1176d9 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java @@ -1,22 +1,19 @@ package hudson.plugins.git; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import hudson.EnvVars; import hudson.FilePath; import hudson.model.TaskListener; import hudson.scm.EditType; import hudson.util.StreamTaskListener; - -import org.eclipse.jgit.lib.ObjectId; - import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import junit.framework.TestCase; +import org.eclipse.jgit.lib.ObjectId; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; /** Utility class to support GitChangeSet testing. */ public class GitChangeSetUtil { @@ -42,11 +39,17 @@ public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLe return genChangeSet(authorOrCommitter, useLegacyFormat, hasParent, COMMIT_TITLE); } - public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFormat, boolean hasParent, String commitTitle) { - return genChangeSet(authorOrCommitter, useLegacyFormat, hasParent, commitTitle, false); + public static GitChangeSet genChangeSet( + boolean authorOrCommitter, boolean useLegacyFormat, boolean hasParent, String commitTitle) { + return genChangeSet(authorOrCommitter, useLegacyFormat, hasParent, commitTitle, false); } - public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFormat, boolean hasParent, String commitTitle, boolean truncate) { + public static GitChangeSet genChangeSet( + boolean authorOrCommitter, + boolean useLegacyFormat, + boolean hasParent, + String commitTitle, + boolean truncate) { ArrayList lines = new ArrayList<>(); lines.add("Some header junk we should ignore..."); lines.add("header line 2"); @@ -68,11 +71,16 @@ public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLe lines.add(" create mode 100644 some/file1"); lines.add(" delete mode 100644 other/file2"); } - lines.add(":000000 123456 0000000000000000000000000000000000000000 123abc456def789abc012def345abc678def901a A\tsrc/test/add.file"); - lines.add(":123456 000000 123abc456def789abc012def345abc678def901a 0000000000000000000000000000000000000000 D\tsrc/test/deleted.file"); - lines.add(":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 M\tsrc/test/modified.file"); - lines.add(":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 R012\tsrc/test/renamedFrom.file\tsrc/test/renamedTo.file"); - lines.add(":000000 123456 bc234def567abc890def123abc456def789abc01 123abc456def789abc012def345abc678def901a C100\tsrc/test/original.file\tsrc/test/copyOf.file"); + lines.add( + ":000000 123456 0000000000000000000000000000000000000000 123abc456def789abc012def345abc678def901a A\tsrc/test/add.file"); + lines.add( + ":123456 000000 123abc456def789abc012def345abc678def901a 0000000000000000000000000000000000000000 D\tsrc/test/deleted.file"); + lines.add( + ":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 M\tsrc/test/modified.file"); + lines.add( + ":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 R012\tsrc/test/renamedFrom.file\tsrc/test/renamedTo.file"); + lines.add( + ":000000 123456 bc234def567abc890def123abc456def789abc01 123abc456def789abc012def345abc678def901a C100\tsrc/test/original.file\tsrc/test/copyOf.file"); return new GitChangeSet(lines, authorOrCommitter, truncate); } @@ -80,7 +88,8 @@ static void assertChangeSet(GitChangeSet changeSet) { TestCase.assertEquals("123abc456def", changeSet.getId()); TestCase.assertEquals("Commit title.", changeSet.getMsg()); TestCase.assertEquals("Commit title.\nCommit extended description.\n", changeSet.getComment()); - TestCase.assertEquals("Commit title.\nCommit extended description.\n".replace("\n", "
"), changeSet.getCommentAnnotated()); + TestCase.assertEquals( + "Commit title.\nCommit extended description.\n".replace("\n", "
"), changeSet.getCommentAnnotated()); HashSet expectedAffectedPaths = new HashSet<>(7); expectedAffectedPaths.add("src/test/add.file"); expectedAffectedPaths.add("src/test/deleted.file"); @@ -92,48 +101,54 @@ static void assertChangeSet(GitChangeSet changeSet) { Collection actualPaths = changeSet.getPaths(); TestCase.assertEquals(6, actualPaths.size()); for (GitChangeSet.Path path : actualPaths) { - if (null != path.getPath()) switch (path.getPath()) { - case "src/test/add.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertNull(path.getSrc()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); - break; - case "src/test/deleted.file": - TestCase.assertEquals(EditType.DELETE, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertNull(path.getDst()); - break; - case "src/test/modified.file": - TestCase.assertEquals(EditType.EDIT, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/renamedFrom.file": - TestCase.assertEquals(EditType.DELETE, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/renamedTo.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); - break; - case "src/test/copyOf.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); - break; - default: - TestCase.fail("Unrecognized path."); - break; + if (null != path.getPath()) { + switch (path.getPath()) { + case "src/test/add.file": + TestCase.assertEquals(EditType.ADD, path.getEditType()); + TestCase.assertNull(path.getSrc()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + break; + case "src/test/deleted.file": + TestCase.assertEquals(EditType.DELETE, path.getEditType()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + TestCase.assertNull(path.getDst()); + break; + case "src/test/modified.file": + TestCase.assertEquals(EditType.EDIT, path.getEditType()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/renamedFrom.file": + TestCase.assertEquals(EditType.DELETE, path.getEditType()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/renamedTo.file": + TestCase.assertEquals(EditType.ADD, path.getEditType()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + break; + case "src/test/copyOf.file": + TestCase.assertEquals(EditType.ADD, path.getEditType()); + TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); + TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + break; + default: + TestCase.fail("Unrecognized path."); + break; + } } } } - public static GitChangeSet genChangeSet(ObjectId sha1, String gitImplementation, boolean authorOrCommitter) throws IOException, InterruptedException { + public static GitChangeSet genChangeSet(ObjectId sha1, String gitImplementation, boolean authorOrCommitter) + throws IOException, InterruptedException { EnvVars envVars = new EnvVars(); TaskListener listener = StreamTaskListener.fromStdout(); - GitClient git = Git.with(listener, envVars).in(new FilePath(new File("."))).using(gitImplementation).getClient(); + GitClient git = Git.with(listener, envVars) + .in(new FilePath(new File("."))) + .using(gitImplementation) + .getClient(); return new GitChangeSet(git.showRevision(sha1), authorOrCommitter); } } diff --git a/src/test/java/hudson/plugins/git/GitHooksTest.java b/src/test/java/hudson/plugins/git/GitHooksTest.java index 2f02ea157c..383be4dcdc 100644 --- a/src/test/java/hudson/plugins/git/GitHooksTest.java +++ b/src/test/java/hudson/plugins/git/GitHooksTest.java @@ -1,9 +1,26 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsIterableContaining.hasItem; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import hudson.FilePath; import hudson.model.Label; import hudson.slaves.DumbSlave; import hudson.tools.ToolProperty; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitHooksConfiguration; import org.eclipse.jgit.util.SystemReader; @@ -21,34 +38,16 @@ import org.jvnet.hudson.test.BuildWatcher; import org.jvnet.hudson.test.LoggerRule; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsIterableContaining.hasItem; -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.StringStartsWith.startsWith; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - public class GitHooksTest extends AbstractGitTestCase { @Rule public LoggerRule lr = new LoggerRule(); + @ClassRule public static BuildWatcher watcher = new BuildWatcher(); - private static final String JENKINS_URL = System.getenv("JENKINS_URL") != null - ? System.getenv("JENKINS_URL") - : "http://localhost:8080/"; + private static final String JENKINS_URL = + System.getenv("JENKINS_URL") != null ? System.getenv("JENKINS_URL") : "http://localhost:8080/"; @BeforeClass public static void setGitDefaults() throws Exception { @@ -62,10 +61,10 @@ public void setGitTool() throws IOException { lr.record(GitHooksConfiguration.class.getName(), Level.ALL).capture(1024); GitTool tool = new GitTool("my-git", "git", Collections.>emptyList()); rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); - //Jenkins 2.308 changes the default label to "built-in" causing test failures when testing with newer core + // Jenkins 2.308 changes the default label to "built-in" causing test failures when testing with newer core // e.g. java 17 testing rule.jenkins.setLabelString("master"); - rule.jenkins.setNumExecutors(3); //In case this changes in the future as well. + rule.jenkins.setNumExecutors(3); // In case this changes in the future as well. } @After @@ -88,19 +87,15 @@ public void testPipelineFromScm() throws Exception { GitHooksConfiguration.get().setAllowedOnAgents(true); final DumbSlave agent = rule.createOnlineSlave(Label.get("somewhere")); commit("test.txt", "Test", johnDoe, "First"); - String jenkinsfile = lines( - "node('somewhere') {", - " checkout scm", - " echo 'Hello Pipeline'", - "}" - ); + String jenkinsfile = lines("node('somewhere') {", " checkout scm", " echo 'Hello Pipeline'", "}"); commit("Jenkinsfile", jenkinsfile, johnDoe, "Jenkinsfile"); final WorkflowJob job = rule.createProject(WorkflowJob.class); final GitSCM scm = new GitSCM( this.createRemoteRepositories(), Collections.singletonList(new BranchSpec("master")), - null, "my-git", Collections.emptyList() - ); + null, + "my-git", + Collections.emptyList()); CpsScmFlowDefinition definition = new CpsScmFlowDefinition(scm, "Jenkinsfile"); definition.setLightweight(false); job.setDefinition(definition); @@ -115,7 +110,7 @@ public void testPipelineFromScm() throws Exception { final File postCheckoutOutput1 = new File(tf.newFolder(), "svn-git-fun-post-checkout-1"); final File postCheckoutOutput2 = new File(tf.newFolder(), "svn-git-fun-post-checkout-2"); - //Add hook on agent workspace + // Add hook on agent workspace FilePath hook = jobWorkspace.child(".git/hooks/post-checkout"); createHookScriptAt(postCheckoutOutput1, hook); @@ -126,7 +121,7 @@ public void testPipelineFromScm() throws Exception { commit("test.txt", "Second", johnDoe, "Second"); commit("Jenkinsfile", "/*2*/\n" + jenkinsfile, johnDoe, "Jenkinsfile"); - //Allowed + // Allowed Thread.sleep(TimeUnit.SECONDS.toMillis(2)); Instant before = Instant.now().minus(2, ChronoUnit.SECONDS); run = rule.buildAndAssertSuccess(job); @@ -141,7 +136,7 @@ public void testPipelineFromScm() throws Exception { commit("test.txt", "Third", johnDoe, "Third"); commit("Jenkinsfile", "/*3*/\n" + jenkinsfile, johnDoe, "Jenkinsfile"); - //Denied + // Denied GitHooksConfiguration.get().setAllowedOnController(false); GitHooksConfiguration.get().setAllowedOnAgents(false); run = rule.buildAndAssertSuccess(job); @@ -156,7 +151,7 @@ public void testPipelineFromScm() throws Exception { commit("test.txt", "Four", johnDoe, "Four"); commit("Jenkinsfile", "/*4*/\n" + jenkinsfile, johnDoe, "Jenkinsfile"); - //Allowed On Agent + // Allowed On Agent GitHooksConfiguration.get().setAllowedOnController(false); GitHooksConfiguration.get().setAllowedOnAgents(true); Thread.sleep(TimeUnit.SECONDS.toMillis(2)); @@ -171,7 +166,7 @@ public void testPipelineFromScm() throws Exception { commit("test.txt", "Five", johnDoe, "Five"); commit("Jenkinsfile", "/*5*/\n" + jenkinsfile, johnDoe, "Jenkinsfile"); - //Denied + // Denied GitHooksConfiguration.get().setAllowedOnController(false); GitHooksConfiguration.get().setAllowedOnAgents(false); run = rule.buildAndAssertSuccess(job); @@ -180,19 +175,26 @@ public void testPipelineFromScm() throws Exception { assertFalse(postCheckoutOutput2.exists()); } - private void createHookScriptAt(final File postCheckoutOutput, final FilePath hook) throws IOException, InterruptedException { + private void createHookScriptAt(final File postCheckoutOutput, final FilePath hook) + throws IOException, InterruptedException { final String nl = System.lineSeparator(); StringBuilder scriptContent = new StringBuilder("#!/bin/sh -v").append(nl); - scriptContent.append("date +%s > \"") - .append(postCheckoutOutput.getAbsolutePath().replace("\\", "\\\\")) // Git shell processes escapes, needs extra escapes - .append('"').append(nl); + scriptContent + .append("date +%s > \"") + .append(postCheckoutOutput + .getAbsolutePath() + .replace("\\", "\\\\")) // Git shell processes escapes, needs extra escapes + .append('"') + .append(nl); hook.write(scriptContent.toString(), Charset.defaultCharset().name()); hook.chmod(0777); } - private void checkFileOutput(final File postCheckoutOutput, final Instant before, final Instant after) throws IOException { + private void checkFileOutput(final File postCheckoutOutput, final Instant before, final Instant after) + throws IOException { assertTrue("Output file should exist", postCheckoutOutput.exists()); - final String s = Files.readString(postCheckoutOutput.toPath(), Charset.defaultCharset()).trim(); + final String s = Files.readString(postCheckoutOutput.toPath(), Charset.defaultCharset()) + .trim(); final Instant when = Instant.ofEpochSecond(Integer.parseInt(s)); assertTrue("Sometime else", when.isAfter(before) && when.isBefore(after)); Files.delete(postCheckoutOutput.toPath()); @@ -267,23 +269,25 @@ private WorkflowJob setupAndRunPipelineCheckout(String node) throws Exception { final WorkflowJob job = rule.createProject(WorkflowJob.class); final String uri = testRepo.gitDir.getAbsolutePath().replace("\\", "/"); - job.setDefinition(new CpsFlowDefinition(lines( - "node('" + node + "') {", - " checkout([$class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: '" + uri + "']]])", - " if (!fileExists('.git/hooks/post-checkout')) {", - " writeFile file: '.git/hooks/post-checkout', text: \"#!/bin/sh\\necho h4xor3d\"", - " if (isUnix()) {", - " sh 'chmod +x .git/hooks/post-checkout'", - " }", - " } else {", - " if (isUnix()) {", - " sh 'git checkout -B test origin/master'", - " } else {", - " bat 'git.exe checkout -B test origin/master'", - " }", - " }", - "}") - , true)); + job.setDefinition(new CpsFlowDefinition( + lines( + "node('" + node + "') {", + " checkout([$class: 'GitSCM', branches: [[name: '*/master']], userRemoteConfigs: [[url: '" + + uri + "']]])", + " if (!fileExists('.git/hooks/post-checkout')) {", + " writeFile file: '.git/hooks/post-checkout', text: \"#!/bin/sh\\necho h4xor3d\"", + " if (isUnix()) {", + " sh 'chmod +x .git/hooks/post-checkout'", + " }", + " } else {", + " if (isUnix()) {", + " sh 'git checkout -B test origin/master'", + " } else {", + " bat 'git.exe checkout -B test origin/master'", + " }", + " }", + "}"), + true)); WorkflowRun run = rule.buildAndAssertSuccess(job); rule.assertLogNotContains("h4xor3d", run); final String commitFile2 = "commitFile2"; @@ -309,6 +313,6 @@ private static String lines(String... lines) { /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; + return java.io.File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/hudson/plugins/git/GitPublisherTest.java b/src/test/java/hudson/plugins/git/GitPublisherTest.java index dda4ed87a1..5069d3ddad 100644 --- a/src/test/java/hudson/plugins/git/GitPublisherTest.java +++ b/src/test/java/hudson/plugins/git/GitPublisherTest.java @@ -23,6 +23,15 @@ */ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + import hudson.FilePath; import hudson.Launcher; import hudson.matrix.Axis; @@ -40,13 +49,6 @@ import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.StreamTaskListener; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.util.SystemReader; -import org.jenkinsci.plugins.gitclient.JGitTool; -import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.jvnet.hudson.test.Issue; - import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -55,29 +57,25 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; - import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitToolChooser; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; +import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - +import org.jenkinsci.plugins.gitclient.JGitTool; +import org.jenkinsci.plugins.gitclient.MergeCommand; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.jvnet.hudson.test.Issue; /** * Tests for {@link GitPublisher} - * + * * @author Kohsuke Kawaguchi */ public class GitPublisherTest extends AbstractGitProject { @@ -100,32 +98,41 @@ public void testMatrixBuild() throws Exception { commitNewFile("a"); MatrixProject mp = jenkins.createProject(MatrixProject.class, "xyz"); - mp.setAxes(new AxisList(new Axis("VAR","a","b"))); + mp.setAxes(new AxisList(new Axis("VAR", "a", "b"))); mp.setScm(new GitSCM(testGitDir.getAbsolutePath())); - mp.getPublishersList().add(new GitPublisher( - Collections.singletonList(new TagToPush("origin","foo","message",true, false)), - Collections.emptyList(), - Collections.emptyList(), - true, true, false) { - @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - run.incrementAndGet(); - try { - return super.perform(build, launcher, listener); - } finally { - // until the 3rd one (which is the last one), we shouldn't create a tag - if (run.get()<3) - assertFalse(existsTag("foo")); - } - } - - @Override - public BuildStepDescriptor getDescriptor() { - return (BuildStepDescriptor)Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake - } - - private Object writeReplace() { return new NullSCM(); } - }); + mp.getPublishersList() + .add( + new GitPublisher( + Collections.singletonList(new TagToPush("origin", "foo", "message", true, false)), + Collections.emptyList(), + Collections.emptyList(), + true, + true, + false) { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) + throws InterruptedException, IOException { + run.incrementAndGet(); + try { + return super.perform(build, launcher, listener); + } finally { + // until the 3rd one (which is the last one), we shouldn't create a tag + if (run.get() < 3) { + assertFalse(existsTag("foo")); + } + } + } + + @Override + public BuildStepDescriptor getDescriptor() { + return (BuildStepDescriptor) + Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake + } + + private Object writeReplace() { + return new NullSCM(); + } + }); MatrixBuild b = jenkins.buildAndAssertSuccess(mp); @@ -134,7 +141,7 @@ public BuildStepDescriptor getDescriptor() { assertTrue(containsTagMessage("foo", "message")); // twice for MatrixRun, which is to be ignored, then once for matrix completion - assertEquals(3,run.get()); + assertEquals(3, run.get()); } @Test @@ -149,19 +156,19 @@ public void GitPublisherFreestylePushBranchWithJGit() throws Exception { GitToolChooser.putRepositorySizeCache(testGitDir.getAbsolutePath(), 37 + random.nextInt(900)); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, - Collections.emptyList()); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, Collections.emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); // create initial commit and then run the build against it: commitNewFile("commitFileBase"); @@ -174,9 +181,11 @@ public void GitPublisherFreestylePushBranchWithJGit() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); /* Confirm that JGit was used and that the branch push message was logged */ - assertThat(build1.getLog(50), - hasItems("The recommended git tool is: jgit", // JGit recommended by git tool chooser - "Pushing HEAD to branch integration at repo origin")); + assertThat( + build1.getLog(50), + hasItems( + "The recommended git tool is: jgit", // JGit recommended by git tool chooser + "Pushing HEAD to branch integration at repo origin")); assertTrue(build1.getWorkspace().child(commitFile1).exists()); /* Confirm the branch was pushed */ @@ -193,45 +202,55 @@ public void GitPublisherFailWithJGit() throws Exception { List repoList = new ArrayList<>(); repoList.add(new UserRemoteConfig(testGitDir.getAbsolutePath(), null, null, null)); - GitTool tool = new JGitTool(Collections.emptyList()); //testGitDir.getAbsolutePath() + GitTool tool = new JGitTool(Collections.emptyList()); // testGitDir.getAbsolutePath() jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); MatrixProject mp = jenkins.createProject(MatrixProject.class, "xyz"); - mp.setAxes(new AxisList(new Axis("VAR","a","b"))); - mp.setScm(new GitSCM(repoList, + mp.setAxes(new AxisList(new Axis("VAR", "a", "b"))); + mp.setScm(new GitSCM( + repoList, Collections.singletonList(new BranchSpec("")), - null, tool.getName(), Collections.emptyList())); - mp.getPublishersList().add(new GitPublisher( - Collections.singletonList(new TagToPush("origin","foo","message",true, false)), - Collections.emptyList(), - Collections.emptyList(), - true, true, false) { - @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - run.incrementAndGet(); - try { - return super.perform(build, launcher, listener); - } finally { - // until the 3rd one (which is the last one), we shouldn't create a tag - if (run.get()<3) - assertFalse(existsTag("foo")); - } - } - - @Override - public BuildStepDescriptor getDescriptor() { - return (BuildStepDescriptor)Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake - } - - private Object writeReplace() { return new NullSCM(); } - }); + null, + tool.getName(), + Collections.emptyList())); + mp.getPublishersList() + .add( + new GitPublisher( + Collections.singletonList(new TagToPush("origin", "foo", "message", true, false)), + Collections.emptyList(), + Collections.emptyList(), + true, + true, + false) { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) + throws InterruptedException, IOException { + run.incrementAndGet(); + try { + return super.perform(build, launcher, listener); + } finally { + // until the 3rd one (which is the last one), we shouldn't create a tag + if (run.get() < 3) { + assertFalse(existsTag("foo")); + } + } + } + + @Override + public BuildStepDescriptor getDescriptor() { + return (BuildStepDescriptor) + Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake + } + + private Object writeReplace() { + return new NullSCM(); + } + }); MatrixBuild b = jenkins.buildAndAssertSuccess(mp); /* I don't understand why the log reports pushing tag to repo origin but the tag is not pushed */ - assertThat(b.getLog(50), - hasItems("remote: Counting objects", - "Pushing tag foo to repo origin")); + assertThat(b.getLog(50), hasItems("remote: Counting objects", "Pushing tag foo to repo origin")); /* JGit implementation includes PushCommand, but it fails to push the tag */ assertFalse(existsTag("foo")); } @@ -241,19 +260,19 @@ public void testMergeAndPush() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, - Collections.emptyList()); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, Collections.emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); // create initial commit and then run the build against it: commitNewFile("commitFileBase"); @@ -268,7 +287,6 @@ public void testMergeAndPush() throws Exception { String sha1 = getHeadRevision(build1, "integration"); assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); - } @Issue("JENKINS-12402") @@ -277,19 +295,21 @@ public void testMergeAndPushFF() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, - Collections.emptyList()); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, MergeCommand.GitPluginFastForwardMode.FF))); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, Collections.emptyList()); + scm.getExtensions() + .add(new PreBuildMerge( + new UserMergeOptions("origin", "integration", null, MergeCommand.GitPluginFastForwardMode.FF))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); // create initial commit and then run the build against it: commitNewFile("commitFileBase"); @@ -297,7 +317,10 @@ public void testMergeAndPushFF() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("the integration branch should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals( + "the integration branch should be at HEAD", + shaIntegration, + testGitClient.revParse(Constants.HEAD).name()); // create a new branch and build, this results in a fast-forward merge testGitClient.checkout("master"); @@ -318,12 +341,12 @@ public void testMergeAndPushFF() throws Exception { assertTrue(build2.getWorkspace().child("commitFile1").exists()); shaIntegration = getHeadRevision(build2, "integration"); String shaHead = testGitClient.revParse(Constants.HEAD).name(); - assertEquals("the integration branch and branch1 should line up",shaIntegration, shaBranch1); - assertEquals("the integration branch should be at HEAD",shaIntegration, shaHead); + assertEquals("the integration branch and branch1 should line up", shaIntegration, shaBranch1); + assertEquals("the integration branch should be at HEAD", shaIntegration, shaHead); // integration should have master as the parent commit List revList = testGitClient.revList("integration^1"); ObjectId integrationParent = revList.get(0); - assertEquals("Fast-forward merge should have had master as a parent",master,integrationParent); + assertEquals("Fast-forward merge should have had master as a parent", master, integrationParent); // create a second branch off of master, so as to force a merge commit and to test // that --ff gracefully falls back to a merge commit @@ -350,9 +373,11 @@ public void testMergeAndPushFF() throws Exception { assertTrue(build1.getWorkspace().child(commitFile2).exists()); // the integration branch should have branch1 and branch2 as parents revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have branch1 as a parent",revList.get(0).name(),shaBranch1); + assertEquals( + "Integration should have branch1 as a parent", revList.get(0).name(), shaBranch1); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch2 as a parent",revList.get(0).name(),shaBranch2); + assertEquals( + "Integration should have branch2 as a parent", revList.get(0).name(), shaBranch2); } @Issue("JENKINS-12402") @@ -361,19 +386,21 @@ public void testMergeAndPushNoFF() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, - Collections.emptyList()); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, MergeCommand.GitPluginFastForwardMode.NO_FF))); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, Collections.emptyList()); + scm.getExtensions() + .add(new PreBuildMerge(new UserMergeOptions( + "origin", "integration", null, MergeCommand.GitPluginFastForwardMode.NO_FF))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); // create initial commit and then run the build against it: commitNewFile("commitFileBase"); @@ -381,7 +408,10 @@ public void testMergeAndPushNoFF() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("integration branch should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals( + "integration branch should be at HEAD", + shaIntegration, + testGitClient.revParse(Constants.HEAD).name()); // create a new branch and build // This would be a fast-forward merge, but we're calling for --no-ff and that should work @@ -406,9 +436,10 @@ public void testMergeAndPushNoFF() throws Exception { // assertTrue(build2.getWorkspace().child("commitFile1").exists()); List revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have master as a parent",revList.get(0),master); + assertEquals("Integration should have master as a parent", revList.get(0), master); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch1 as a parent",revList.get(0).name(),shaBranch1); + assertEquals( + "Integration should have branch1 as a parent", revList.get(0).name(), shaBranch1); // create a second branch off of master, so as to test that --no-ff is published as expected testGitClient.checkout("master"); @@ -434,13 +465,18 @@ public void testMergeAndPushNoFF() throws Exception { // |/ // * a5dda1a (master) Initial Commit // - assertTrue("commitFile1 should exist in the workspace",build1.getWorkspace().child(commitFile1).exists()); - assertTrue("commitFile2 should exist in the workspace",build1.getWorkspace().child(commitFile2).exists()); + assertTrue( + "commitFile1 should exist in the workspace", + build1.getWorkspace().child(commitFile1).exists()); + assertTrue( + "commitFile2 should exist in the workspace", + build1.getWorkspace().child(commitFile2).exists()); // the integration branch should have branch1 and branch2 as parents revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have the first merge commit as a parent",revList.get(0),mergeCommit); + assertEquals("Integration should have the first merge commit as a parent", revList.get(0), mergeCommit); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch2 as a parent",revList.get(0).name(),shaBranch2); + assertEquals( + "Integration should have branch2 as a parent", revList.get(0).name(), shaBranch2); } @Issue("JENKINS-12402") @@ -449,19 +485,21 @@ public void testMergeAndPushFFOnly() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, - Collections.emptyList()); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, MergeCommand.GitPluginFastForwardMode.FF_ONLY))); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, Collections.emptyList()); + scm.getExtensions() + .add(new PreBuildMerge(new UserMergeOptions( + "origin", "integration", null, MergeCommand.GitPluginFastForwardMode.FF_ONLY))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); // create initial commit and then run the build against it: commitNewFile("commitFileBase"); @@ -469,7 +507,10 @@ public void testMergeAndPushFFOnly() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("integration should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals( + "integration should be at HEAD", + shaIntegration, + testGitClient.revParse(Constants.HEAD).name()); // create a new branch and build // This merge can work with --ff-only @@ -489,15 +530,17 @@ public void testMergeAndPushFFOnly() throws Exception { // * f4d190c (HEAD, integration, branch1) Commit number 1 // * f787536 (master) Initial Commit // - assertTrue("commitFile1 should exist in the workspace",build2.getWorkspace().child("commitFile1").exists()); + assertTrue( + "commitFile1 should exist in the workspace", + build2.getWorkspace().child("commitFile1").exists()); shaIntegration = getHeadRevision(build2, "integration"); String shaHead = testGitClient.revParse(Constants.HEAD).name(); - assertEquals("integration and branch1 should line up",shaIntegration, shaBranch1); - assertEquals("integration and head should line up",shaIntegration, shaHead); + assertEquals("integration and branch1 should line up", shaIntegration, shaBranch1); + assertEquals("integration and head should line up", shaIntegration, shaHead); // integration should have master as the parent commit List revList = testGitClient.revList("integration^1"); ObjectId integrationParent = revList.get(0); - assertEquals("Fast-forward merge should have had master as a parent",master,integrationParent); + assertEquals("Fast-forward merge should have had master as a parent", master, integrationParent); // create a second branch off of master, so as to force a merge commit // but the publish will fail as --ff-only cannot work with a parallel branch @@ -516,49 +559,71 @@ public void testMergeAndPushFFOnly() throws Exception { // | * 79c49b2 (integration, branch1) Commit number 1 // |/ // * ebffeb3 (master) Initial Commit - assertFalse("commitFile1 should not exist in the workspace",build2.getWorkspace().child("commitFile1").exists()); - assertTrue("commitFile2 should exist in the workspace",build2.getWorkspace().child("commitFile2").exists()); + assertFalse( + "commitFile1 should not exist in the workspace", + build2.getWorkspace().child("commitFile1").exists()); + assertTrue( + "commitFile2 should exist in the workspace", + build2.getWorkspace().child("commitFile2").exists()); revList = testGitClient.revList("branch2^1"); - assertEquals("branch2 should have master as a parent",revList.get(0),master); - assertThrows("branch2 should have no other parent than master", NullPointerException.class, () -> testGitClient.revList("branch2^2")); + assertEquals("branch2 should have master as a parent", revList.get(0), master); + assertThrows( + "branch2 should have no other parent than master", + NullPointerException.class, + () -> testGitClient.revList("branch2^2")); } @Issue("JENKINS-24786") @Test - public void testPushEnvVarsInRemoteConfig() throws Exception{ - FreeStyleProject project = setupSimpleProject("master"); + public void testPushEnvVarsInRemoteConfig() throws Exception { + FreeStyleProject project = setupSimpleProject("master"); // create second (bare) test repository as target TaskListener listener = StreamTaskListener.fromStderr(); TestGitRepo testTargetRepo = new TestGitRepo("target", tmpFolder.newFolder("push_env_vars"), listener); - testTargetRepo.git.init_().workspace(testTargetRepo.gitDir.getAbsolutePath()).bare(true).execute(); - testTargetRepo.commit("lostTargetFile", new PersonIdent("John Doe", "john@example.com"), "Initial Target Commit"); + testTargetRepo + .git + .init_() + .workspace(testTargetRepo.gitDir.getAbsolutePath()) + .bare(true) + .execute(); + testTargetRepo.commit( + "lostTargetFile", new PersonIdent("John Doe", "john@example.com"), "Initial Target Commit"); // add second test repository as remote repository with environment variables List remoteRepositories = remoteConfigs(); - remoteRepositories.add(new UserRemoteConfig("$TARGET_URL", "$TARGET_NAME", "+refs/heads/$TARGET_BRANCH:refs/remotes/$TARGET_NAME/$TARGET_BRANCH", null)); + remoteRepositories.add(new UserRemoteConfig( + "$TARGET_URL", + "$TARGET_NAME", + "+refs/heads/$TARGET_BRANCH:refs/remotes/$TARGET_NAME/$TARGET_BRANCH", + null)); GitSCM scm = new GitSCM( remoteRepositories, Collections.singletonList(new BranchSpec("origin/master")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); // add parameters for remote repository configuration project.addProperty(new ParametersDefinitionProperty( - new StringParameterDefinition("TARGET_URL", testTargetRepo.gitDir.getAbsolutePath()), - new StringParameterDefinition("TARGET_NAME", "target"), - new StringParameterDefinition("TARGET_BRANCH", "master"))); + new StringParameterDefinition("TARGET_URL", testTargetRepo.gitDir.getAbsolutePath()), + new StringParameterDefinition("TARGET_NAME", "target"), + new StringParameterDefinition("TARGET_BRANCH", "master"))); String tag_name = "test-tag"; String note_content = "Test Note"; - project.getPublishersList().add(new GitPublisher( - Collections.singletonList(new TagToPush("$TARGET_NAME", tag_name, "", false, false)), - Collections.singletonList(new BranchToPush("$TARGET_NAME", "$TARGET_BRANCH")), - Collections.singletonList(new NoteToPush("$TARGET_NAME", note_content, Constants.R_NOTES_COMMITS, false)), - true, false, true)); + project.getPublishersList() + .add(new GitPublisher( + Collections.singletonList(new TagToPush("$TARGET_NAME", tag_name, "", false, false)), + Collections.singletonList(new BranchToPush("$TARGET_NAME", "$TARGET_BRANCH")), + Collections.singletonList( + new NoteToPush("$TARGET_NAME", note_content, Constants.R_NOTES_COMMITS, false)), + true, + false, + true)); commitNewFile("commitFile"); testGitClient.tag(tag_name, "Comment"); @@ -569,18 +634,18 @@ public void testPushEnvVarsInRemoteConfig() throws Exception{ // check if everything reached target repository assertEquals(expectedCommit, testTargetRepo.git.revParse("master")); assertTrue(existsTagInRepo(testTargetRepo.git, tag_name)); - } @Issue("JENKINS-24082") @Test public void testForcePush() throws Exception { - FreeStyleProject project = setupSimpleProject("master"); + FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( remoteConfigs(), Collections.singletonList(new BranchSpec("master")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); @@ -588,7 +653,9 @@ public void testForcePush() throws Exception { Collections.emptyList(), Collections.singletonList(new BranchToPush("origin", "otherbranch")), Collections.emptyList(), - true, true, true); + true, + true, + true); project.getPublishersList().add(forcedPublisher); // Create a commit on the master branch in the test repo @@ -613,10 +680,14 @@ public void testForcePush() throws Exception { // build will merge and push to "otherbranch" in test repo // Without force, this would fail assertEquals(otherCommit, testGitClient.revParse("otherbranch")); // not merged yet - assertTrue("otherCommit not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit)); + assertTrue( + "otherCommit not in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit)); build(project, Result.SUCCESS, "commitFile2"); assertEquals(masterCommit2, testGitClient.revParse("otherbranch")); // merge done - assertFalse("otherCommit in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit)); + assertFalse( + "otherCommit in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit)); // Commit to otherbranch in test repo so that next merge will fail testGitClient.checkout("otherbranch"); @@ -635,16 +706,22 @@ public void testForcePush() throws Exception { Collections.emptyList(), Collections.singletonList(new BranchToPush("origin", "otherbranch")), Collections.emptyList(), - true, true, false); + true, + true, + false); project.getPublishersList().add(unforcedPublisher); // build will attempts to merge and push to "otherbranch" in test repo. // Without force, will fail assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); // not merged yet - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue( + "otherCommit2 not in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit2)); build(project, Result.FAILURE, "commitFile3"); assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); // still not merged - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue( + "otherCommit2 not in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit2)); // Remove unforcedPublisher, add forcedPublisher project.getPublishersList().remove(unforcedPublisher); @@ -658,47 +735,51 @@ public void testForcePush() throws Exception { // build will merge and push to "otherbranch" in test repo. assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); assertTrue("otherCommit2 not in test repo", testGitClient.isCommitInRepo(otherCommit2)); - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue( + "otherCommit2 not in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit2)); build(project, Result.SUCCESS, "commitFile4"); assertEquals(masterCommit4, testGitClient.revParse("otherbranch")); assertEquals(masterCommit3, testGitClient.revParse("otherbranch^")); - assertFalse("otherCommit2 in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertFalse( + "otherCommit2 in otherbranch", + testGitClient.revList("otherbranch").contains(otherCommit2)); } /* Fix push to remote when skipTag is enabled */ @Issue("JENKINS-17769") @Test public void testMergeAndPushWithSkipTagEnabled() throws Exception { - FreeStyleProject project = setupSimpleProject("master"); + FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, new ArrayList<>()); + remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, new ArrayList<>()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); scm.getExtensions().add(new LocalBranch("integration")); project.setScm(scm); + project.getPublishersList() + .add(new GitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); - project.getPublishersList().add(new GitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); - - // create initial commit and then run the build against it: - commitNewFile("commitFileBase"); - testGitClient.branch("integration"); - build(project, Result.SUCCESS, "commitFileBase"); + // create initial commit and then run the build against it: + commitNewFile("commitFileBase"); + testGitClient.branch("integration"); + build(project, Result.SUCCESS, "commitFileBase"); - testGitClient.checkout(null, "topic1"); - final String commitFile1 = "commitFile1"; - commitNewFile(commitFile1); - final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertTrue(build1.getWorkspace().child(commitFile1).exists()); + testGitClient.checkout(null, "topic1"); + final String commitFile1 = "commitFile1"; + commitNewFile(commitFile1); + final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); + assertTrue(build1.getWorkspace().child(commitFile1).exists()); - String sha1 = getHeadRevision(build1, "integration"); - assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); + String sha1 = getHeadRevision(build1, "integration"); + assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); } @Test @@ -708,7 +789,8 @@ public void testRebaseBeforePush() throws Exception { GitSCM scm = new GitSCM( remoteConfigs(), Collections.singletonList(new BranchSpec("master")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); @@ -716,10 +798,7 @@ public void testRebaseBeforePush() throws Exception { btp.setRebaseBeforePush(true); GitPublisher rebasedPublisher = new GitPublisher( - Collections.emptyList(), - Collections.singletonList(btp), - Collections.emptyList(), - true, true, true); + Collections.emptyList(), Collections.singletonList(btp), Collections.emptyList(), true, true, true); project.getPublishersList().add(rebasedPublisher); project.getBuildersList().add(new LongRunningCommit(testGitDir)); @@ -739,7 +818,6 @@ public void testRebaseBeforePush() throws Exception { // * 64e71e7 (origin/master) Added a file named commitFile1 // * b2578eb init - // as we have set "rebaseBeforePush" to true we expect all files to be present after the build. FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1", "commitFile2"); } @@ -750,7 +828,7 @@ public void testMergeAndPushWithCharacteristicEnvVar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); /* - * JOB_NAME seemed like the more obvious choice, but when run from a + * JOB_NAME seemed like the more obvious choice, but when run from a * multi-configuration job, the value of JOB_NAME includes an equals * sign. That makes log parsing and general use of the variable more * difficult. JENKINS_SERVER_COOKIE is a characteristic env var which @@ -788,14 +866,12 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal List scmExtensions = new ArrayList<>(); scmExtensions.add(new PreBuildMerge(new UserMergeOptions("origin", envReference, null, null))); scmExtensions.add(new LocalBranch(envReference)); - GitSCM scm = new GitSCM( - remoteConfigs(), - Collections.singletonList(new BranchSpec("*")), - null, null, scmExtensions); + GitSCM scm = + new GitSCM(remoteConfigs(), Collections.singletonList(new BranchSpec("*")), null, null, scmExtensions); project.setScm(scm); String tagNameReference = envReference + "-tag"; // ${BRANCH_NAME}-tag - String tagNameValue = envValue + "-tag"; // master-tag + String tagNameValue = envValue + "-tag"; // master-tag String tagMessageReference = envReference + " tag message"; String noteReference = "note for " + envReference; String noteValue = "note for " + envValue; @@ -803,7 +879,9 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal Collections.singletonList(new TagToPush("origin", tagNameReference, tagMessageReference, false, true)), Collections.singletonList(new BranchToPush("origin", envReference)), Collections.singletonList(new NoteToPush("origin", noteReference, Constants.R_NOTES_COMMITS, false)), - true, true, true); + true, + true, + true); assertTrue(publisher.isForcePush()); assertTrue(publisher.isPushBranches()); assertTrue(publisher.isPushMerge()); @@ -829,7 +907,9 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal String build0HeadBranch = getHeadRevision(build0, envValue); assertEquals(build0HeadBranch, initialCommit.getName()); assertTrue(tagNameValue + " not in " + testGitClient, testGitClient.tagExists(tagNameValue)); - assertTrue(tagNameValue + " not in build", build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists()); + assertTrue( + tagNameValue + " not in build", + build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists()); // Create a topic branch in the source repository and commit to topic branch String topicBranch = envValue + "-topic1"; @@ -845,12 +925,13 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); FilePath myWorkspace = build1.getWorkspace(); assertTrue(myWorkspace.child(commitFile1).exists()); - assertTrue("Tag " + tagNameValue + " not in build", myWorkspace.child(".git/refs/tags/" + tagNameValue).exists()); + assertTrue( + "Tag " + tagNameValue + " not in build", + myWorkspace.child(".git/refs/tags/" + tagNameValue).exists()); String build1Head = getHeadRevision(build1, envValue); assertEquals(build1Head, testGitClient.revParse(Constants.HEAD).name()); assertEquals("Wrong head commit in build1", topicCommit.getName(), build1Head); - } private boolean existsTag(String tag) throws InterruptedException { @@ -879,7 +960,7 @@ private boolean hasBranch(String branchName) throws GitException, InterruptedExc /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; + return java.io.File.pathSeparatorChar == ';'; } } @@ -892,9 +973,11 @@ class LongRunningCommit extends Builder { } @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) + throws InterruptedException, IOException { - TestGitRepo workspaceGit = new TestGitRepo("workspace", new File(build.getWorkspace().getRemote()), listener); + TestGitRepo workspaceGit = + new TestGitRepo("workspace", new File(build.getWorkspace().getRemote()), listener); TestGitRepo remoteGit = new TestGitRepo("remote", this.remoteGitDir, listener); // simulate an external commit and push to the remote during the build of our project. diff --git a/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java b/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java index e3c7fef5ee..1a7be1f435 100644 --- a/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java +++ b/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java @@ -23,24 +23,24 @@ */ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.model.AbstractBuild; import hudson.model.TaskListener; import hudson.plugins.git.util.BuildData; import org.eclipse.jgit.lib.ObjectId; -import org.junit.Test; import org.junit.Before; +import org.junit.Test; import org.mockito.Mockito; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; public class GitRevisionTokenMacroTest { private GitRevisionTokenMacro tokenMacro; - public GitRevisionTokenMacroTest() { - } + public GitRevisionTokenMacroTest() {} @Before public void createTokenMacro() { @@ -101,6 +101,8 @@ public void testEvaluateMockBuildDataLength() throws Exception { AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getAction(BuildData.class)).thenReturn(buildData); tokenMacro.length = 8; - assertThat(tokenMacro.evaluate(build, TaskListener.NULL, "GIT_REVISION"), is(revision.getSha1String().substring(0, 8))); + assertThat( + tokenMacro.evaluate(build, TaskListener.NULL, "GIT_REVISION"), + is(revision.getSha1String().substring(0, 8))); } } diff --git a/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java b/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java index 044c55b2fe..2699a1cc78 100644 --- a/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java @@ -23,6 +23,9 @@ */ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.plugins.git.browser.BitbucketWeb; import hudson.plugins.git.browser.GitLab; import hudson.plugins.git.browser.GitRepositoryBrowser; @@ -30,9 +33,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -44,9 +44,7 @@ public class GitSCMBrowserTest { private final Class expectedClass; private final String expectedURI; - public GitSCMBrowserTest(String gitURI, - Class expectedClass, - String expectedURI) { + public GitSCMBrowserTest(String gitURI, Class expectedClass, String expectedURI) { this.gitURI = gitURI; this.expectedClass = expectedClass; this.expectedURI = expectedURI; @@ -78,7 +76,6 @@ private static String expectedURL(String url) { return "https://github.com/" + REPO_PATH + "/"; } return null; - } @Parameterized.Parameters(name = "{0}") diff --git a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java index 4358fa3405..ce1d9f3490 100644 --- a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java @@ -1,5 +1,13 @@ package hudson.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; @@ -32,15 +40,6 @@ import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.RandomOrder; import jenkins.security.MasterToSlaveCallable; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; - import org.eclipse.jgit.util.SystemReader; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -71,6 +70,7 @@ public static void setGitDefaults() throws Exception { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -110,9 +110,8 @@ public void testConfigRoundtripURLPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); - GitSCM scm = new GitSCM(createRepoList(url), - Collections.singletonList(new BranchSpec("")), - browser, null, null); + GitSCM scm = + new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("")), browser, null, null); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm, p.getScm()); @@ -141,9 +140,8 @@ public void testConfigRoundtripExtensionsPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); - GitSCM scm = new GitSCM(createRepoList(url), - Collections.singletonList(new BranchSpec("*/master")), - browser, null, null); + GitSCM scm = new GitSCM( + createRepoList(url), Collections.singletonList(new BranchSpec("*/master")), browser, null, null); p.setScm(scm); /* Assert that no extensions are loaded initially */ @@ -228,7 +226,8 @@ public String call() throws IOException { try { return c.actOnProject(new BuildChooserContext.ContextCallable, String>() { @Override - public String invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { + public String invoke(Job param, VirtualChannel channel) + throws IOException, InterruptedException { assertTrue(channel instanceof Channel); assertNotNull(Jenkins.getInstanceOrNull()); return param.toString(); @@ -249,7 +248,8 @@ public void testMergeFailedWithAgent() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); @@ -266,16 +266,22 @@ public void testMergeFailedWithAgent() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); rule.buildAndAssertStatus(Result.FAILURE, project); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test @@ -287,7 +293,8 @@ public void testMergeWithAgent() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); @@ -304,7 +311,9 @@ public void testMergeWithAgent() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -312,24 +321,29 @@ public void testMergeWithAgent() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test public void testMergeWithMatrixBuild() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - //Create a matrix project and a couple of axes + // Create a matrix project and a couple of axes MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR", "a", "b"))); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); @@ -346,7 +360,9 @@ public void testMergeWithMatrixBuild() throws Exception { final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -354,11 +370,15 @@ public void testMergeWithMatrixBuild() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test @@ -442,19 +462,25 @@ public void testBasicWithAgent() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } /** diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index f9c1d12c04..f551e81182 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -1,5 +1,20 @@ package hudson.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; +import static org.jvnet.hudson.test.LoggerRule.recorded; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; @@ -8,7 +23,6 @@ import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import com.gargoylesoftware.htmlunit.html.HtmlPage; - import hudson.EnvVars; import hudson.FilePath; import hudson.Functions; @@ -34,26 +48,6 @@ import hudson.util.LogTaskListener; import hudson.util.RingBufferLogHandler; import hudson.util.StreamTaskListener; - -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.PersonIdent; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.util.SystemReader; -import org.jenkinsci.plugins.tokenmacro.TokenMacro; -import org.jenkinsci.plugins.gitclient.*; -import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; -import org.jenkinsci.plugins.workflow.job.WorkflowJob; -import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.LoggerRule; -import org.jvnet.hudson.test.MockAuthorizationStrategy; -import org.jvnet.hudson.test.TestExtension; - -import static org.jvnet.hudson.test.LoggerRule.recorded; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -63,42 +57,41 @@ import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.*; -import static java.util.concurrent.TimeUnit.SECONDS; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.stream.Collectors; - +import jenkins.model.Jenkins; +import jenkins.plugins.git.CliGitCommand; +import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.RandomOrder; +import org.apache.commons.io.FileUtils; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.lib.PersonIdent; +import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.transport.RemoteConfig; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.JenkinsRule; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import org.eclipse.jgit.util.SystemReader; +import org.jenkinsci.plugins.gitclient.*; +import org.jenkinsci.plugins.tokenmacro.TokenMacro; +import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; +import org.jenkinsci.plugins.workflow.job.WorkflowJob; +import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; import org.junit.rules.Stopwatch; import org.junit.rules.TestName; import org.junit.runner.OrderWith; - +import org.jvnet.hudson.test.Issue; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.LoggerRule; +import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.TestExtension; import org.mockito.Mockito; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import jenkins.model.Jenkins; -import jenkins.plugins.git.CliGitCommand; -import jenkins.plugins.git.GitSampleRepoRule; -import jenkins.plugins.git.RandomOrder; /** * Tests for {@link GitSCM}. @@ -116,6 +109,7 @@ public class GitSCMTest extends AbstractGitTestCase { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -139,13 +133,12 @@ public static void setGitDefaults() throws Exception { @Before public void enableSystemCredentialsProvider() throws Exception { - SystemCredentialsProvider.getInstance().setDomainCredentialsMap( - Collections.singletonMap(Domain.global(), Collections.emptyList())); + SystemCredentialsProvider.getInstance() + .setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; break; - } } assertThat("The system credentials provider is enabled", store, notNullValue()); @@ -174,9 +167,10 @@ public void testAddGitTagAction() throws Exception { } assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject project = setupSimpleProject("master"); - List remoteConfigs = GitSCM.createRepoList("https://github.com/jenkinsci/git-plugin", "github"); - project.setScm(new GitSCM(remoteConfigs, - Collections.singletonList(new BranchSpec("master")), false, null, null, null, null)); + List remoteConfigs = + GitSCM.createRepoList("https://github.com/jenkinsci/git-plugin", "github"); + project.setScm(new GitSCM( + remoteConfigs, Collections.singletonList(new BranchSpec("master")), false, null, null, null, null)); GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); @@ -221,13 +215,18 @@ public void manageShouldAccessGlobalConfig() throws Exception { final String MANAGER = "manager"; rule.jenkins.setSecurityRealm(rule.createDummySecurityRealm()); rule.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() - // Read access - .grant(Jenkins.READ).everywhere().to(USER) - - // Read and Manage - .grant(Jenkins.READ).everywhere().to(MANAGER) - .grant(Jenkins.MANAGE).everywhere().to(MANAGER) - ); + // Read access + .grant(Jenkins.READ) + .everywhere() + .to(USER) + + // Read and Manage + .grant(Jenkins.READ) + .everywhere() + .to(MANAGER) + .grant(Jenkins.MANAGE) + .everywhere() + .to(MANAGER)); try (ACLContext c = ACL.as(User.getById(USER, true))) { Collection descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified(); @@ -235,8 +234,9 @@ public void manageShouldAccessGlobalConfig() throws Exception { } try (ACLContext c = ACL.as(User.getById(MANAGER, true))) { Collection descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified(); - Optional found = - descriptors.stream().filter(descriptor -> descriptor instanceof GitSCM.DescriptorImpl).findFirst(); + Optional found = descriptors.stream() + .filter(descriptor -> descriptor instanceof GitSCM.DescriptorImpl) + .findFirst(); assertTrue("Global configuration should be accessible to MANAGE users", found.isPresent()); } } @@ -294,37 +294,47 @@ public void testBasic() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test @Issue("JENKINS-56176") public void testBasicRemotePoll() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); -// FreeStyleProject project = setupProject("master", true, false); + // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; String sha1String = commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); @@ -332,7 +342,9 @@ public void testBasicRemotePoll() throws Exception { assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // JENKINS-56176 token macro expansion broke when BuildData was no longer updated assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION,length=7}"), is(sha1String.substring(0, 7))); assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION}"), is(sha1String)); @@ -342,7 +354,8 @@ public void testBasicRemotePoll() throws Exception { @Test public void testBranchSpecWithRemotesMaster() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); + FreeStyleProject projectMasterBranch = + setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); @@ -362,19 +375,22 @@ public void testBranchSpecWithRemotesMaster() throws Exception { public void testSpecificRefspecs() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); List repos = new ArrayList<>(); - repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); + repos.add(new UserRemoteConfig( + testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Set CloneOption to honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); - ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); + ((GitSCM) projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); /* Set CloneOption to honor refspec on initial clone */ - FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); + FreeStyleProject projectWithFoo = + setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); CloneOption cloneOptionFoo = new CloneOption(false, null, null); cloneOptionFoo.setHonorRefspec(true); - ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo); + ((GitSCM) projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo); // create initial commit final String commitFile1 = "commitFile1"; @@ -395,10 +411,12 @@ public void testSpecificRefspecs() throws Exception { public void testAvoidRedundantFetch() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); List repos = new ArrayList<>(); - repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/*:refs/remotes/*", null)); + repos.add(new UserRemoteConfig( + testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/*:refs/remotes/*", null)); /* Without honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); @@ -426,10 +444,12 @@ public void testAvoidRedundantFetch() throws Exception { public void testAvoidRedundantFetchWithoutHonorRefSpec() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); List repos = new ArrayList<>(); - repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); + repos.add(new UserRemoteConfig( + testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); /* Without honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); @@ -475,10 +495,11 @@ public void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refSpec, null)); /* With honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); CloneOption cloneOptionMaster = new CloneOption(false, null, null); cloneOptionMaster.setHonorRefspec(true); - ((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); + ((GitSCM) projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster); // create initial commit final String commitFile1 = "commitFile1"; @@ -497,8 +518,14 @@ public void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { final List buildLog = build.getLog(50); assertThat("master branch was fetched: " + buildLog, fetchHeadContents, not(containsString("branch 'master'"))); assertThat("foo branch was not fetched: " + buildLog, fetchHeadContents, containsString("branch 'foo'")); - assertThat("master branch SHA1 '" + commitFile1SHA1a + "' fetched " + buildLog, fetchHeadContents, not(containsString(commitFile1SHA1a))); - assertThat("foo branch SHA1 '" + commitFile1SHA1b + "' was not fetched " + buildLog, fetchHeadContents, containsString(commitFile1SHA1b)); + assertThat( + "master branch SHA1 '" + commitFile1SHA1a + "' fetched " + buildLog, + fetchHeadContents, + not(containsString(commitFile1SHA1a))); + assertThat( + "foo branch SHA1 '" + commitFile1SHA1b + "' was not fetched " + buildLog, + fetchHeadContents, + containsString(commitFile1SHA1b)); assertRedundantFetchIsSkipped(build, refSpec); assertThat(build.getResult(), is(Result.FAILURE)); @@ -513,7 +540,8 @@ public void testAvoidRedundantFetchWithNullRefspec() throws Exception { repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", nullRefspec, null)); /* Without honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); @@ -548,7 +576,8 @@ public void testRetainRedundantFetch() throws Exception { repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refspec, null)); /* Without honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); if (random.nextBoolean()) { /* Randomly enable shallow clone, should not alter test assertions */ CloneOption cloneOptionMaster = new CloneOption(false, null, null); @@ -571,9 +600,9 @@ public void testRetainRedundantFetch() throws Exception { } /* - * When "Preserve second fetch during checkout" is checked in during configuring Jenkins, - * the second fetch should be retained - */ + * When "Preserve second fetch during checkout" is checked in during configuring Jenkins, + * the second fetch should be retained + */ @Test @Issue("JENKINS-49757") public void testRetainRedundantFetchIfSecondFetchIsAllowed() throws Exception { @@ -583,7 +612,8 @@ public void testRetainRedundantFetchIfSecondFetchIsAllowed() throws Exception { repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refspec, null)); /* Without honor refspec on initial clone */ - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); GitSCM scm = (GitSCM) projectWithMaster.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); @@ -618,12 +648,15 @@ private void assertRedundantFetchIsUsed(FreeStyleBuild build, String refSpec) th } // Checks if the second fetch is being avoided - private void assertRedundantFetchCount(FreeStyleBuild build, String refSpec, int expectedFetchCount) throws IOException { + private void assertRedundantFetchCount(FreeStyleBuild build, String refSpec, int expectedFetchCount) + throws IOException { List values = build.getLog(Integer.MAX_VALUE); - //String fetchArg = " > git fetch --tags --force --progress -- " + testRepo.gitDir.getAbsolutePath() + argRefSpec + " # timeout=10"; + // String fetchArg = " > git fetch --tags --force --progress -- " + testRepo.gitDir.getAbsolutePath() + + // argRefSpec + " # timeout=10"; Pattern fetchPattern = Pattern.compile(".* git.* fetch .*"); - List fetchCommands = values.stream().filter(fetchPattern.asPredicate()).collect(Collectors.toList()); + List fetchCommands = + values.stream().filter(fetchPattern.asPredicate()).collect(Collectors.toList()); // After the fix, git fetch is called exactly once assertThat("Fetch commands were: " + fetchCommands, fetchCommands, hasSize(expectedFetchCount)); @@ -634,7 +667,7 @@ private FilePath returnFile(FreeStyleBuild build) throws IOException, Interrupte List files = build.getProject().getWorkspace().list(); FilePath resultFile = null; for (FilePath s : files) { - if(s.getName().equals(".git")) { + if (s.getName().equals(".git")) { resultFile = s.child("FETCH_HEAD"); } } @@ -654,9 +687,12 @@ private FilePath returnFile(FreeStyleBuild build) throws IOException, Interrupte public void testSpecificRefspecsWithoutCloneOption() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); List repos = new ArrayList<>(); - repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); - FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); - FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); + repos.add(new UserRemoteConfig( + testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); + FreeStyleProject projectWithMaster = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject projectWithFoo = + setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null); // create initial commit final String commitFile1 = "commitFile1"; @@ -678,18 +714,24 @@ public void testSpecificRefspecsWithoutCloneOption() throws Exception { */ @Test @Issue("JENKINS-38608") - public void testAddFirstRepositoryWithNullRepoURL() throws Exception{ + public void testAddFirstRepositoryWithNullRepoURL() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(null, null, null, null)); - FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject project = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleBuild build = build(project, Result.FAILURE); // Before JENKINS-38608 fix - assertThat("Build log reports 'Null value not allowed'", - build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL"))); + assertThat( + "Build log reports 'Null value not allowed'", + build.getLog(175), + not(hasItem("Null value not allowed as an environment variable: GIT_URL"))); // After JENKINS-38608 fix - assertThat("Build log did not report empty string in job definition", - build.getLog(175), hasItem("FATAL: Git repository URL 1 is an empty string in job definition. Checkout requires a valid repository URL")); + assertThat( + "Build log did not report empty string in job definition", + build.getLog(175), + hasItem( + "FATAL: Git repository URL 1 is an empty string in job definition. Checkout requires a valid repository URL")); } /** @@ -701,36 +743,43 @@ public void testAddFirstRepositoryWithNullRepoURL() throws Exception{ */ @Test @Issue("JENKINS-38608") - public void testAddSecondRepositoryWithNullRepoURL() throws Exception{ + public void testAddSecondRepositoryWithNullRepoURL() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); String repoURL = "https://example.com/non-empty/repo/url"; List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(repoURL, null, null, null)); repos.add(new UserRemoteConfig(null, null, null, null)); - FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); + FreeStyleProject project = + setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); FreeStyleBuild build = build(project, Result.FAILURE); // Before JENKINS-38608 fix - assertThat("Build log reports 'Null value not allowed'", - build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL_2"))); + assertThat( + "Build log reports 'Null value not allowed'", + build.getLog(175), + not(hasItem("Null value not allowed as an environment variable: GIT_URL_2"))); // After JENKINS-38608 fix - assertThat("Build log did not report empty string in job definition for URL 2", - build.getLog(175), hasItem("FATAL: Git repository URL 2 is an empty string in job definition. Checkout requires a valid repository URL")); + assertThat( + "Build log did not report empty string in job definition for URL 2", + build.getLog(175), + hasItem( + "FATAL: Git repository URL 2 is an empty string in job definition. Checkout requires a valid repository URL")); } @Test public void testBranchSpecWithRemotesHierarchical() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); - FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); - // create initial commit - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - // create hierarchical branch, delete master branch, and build - git.branch("rel-1/xy"); - git.checkout("rel-1/xy"); - git.deleteBranch("master"); - build(projectMasterBranch, Result.FAILURE); - build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); + FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); + FreeStyleProject projectHierarchicalBranch = + setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); + // create initial commit + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + // create hierarchical branch, delete master branch, and build + git.branch("rel-1/xy"); + git.checkout("rel-1/xy"); + git.deleteBranch("master"); + build(projectMasterBranch, Result.FAILURE); + build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); } @Test @@ -742,7 +791,7 @@ public void testBranchSpecUsingTagWithSlash() throws Exception { commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag"); testRepo.git.tag("path/tag", "tag with a slash in the tag name"); build(projectMasterBranch, Result.SUCCESS, commitFile1); - } + } @Test public void testBasicIncludedRegion() throws Exception { @@ -754,28 +803,36 @@ public void testBasicIncludedRegion() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); + assertFalse( + "scm polling detected commit2 change, which should not have been included", + project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit3 change", + project.poll(listener).hasChanges()); - //... and build it... + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); - + PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } /** @@ -786,7 +843,7 @@ public void testBasicIncludedRegion() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -811,7 +868,8 @@ public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded region. - assertFalse("Polling should report no changes, because they are in the excluded region.", + assertFalse( + "Polling should report no changes, because they are in the excluded region.", project.poll(listener).hasChanges()); } @@ -823,7 +881,7 @@ public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -848,7 +906,8 @@ public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded directory. - assertFalse("Polling should see no changes, because they are in the excluded directory.", + assertFalse( + "Polling should see no changes, because they are in the excluded directory.", project.poll(listener).hasChanges()); } @@ -860,7 +919,7 @@ public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -877,7 +936,10 @@ public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.included"; - commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); + commit( + fileToMerge, + johnDoe, + "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); @@ -886,7 +948,8 @@ public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { mergeCommand.execute(); // Should return true, because our commit falls within the included region. - assertTrue("Polling should report changes, because they fall within the included region.", + assertTrue( + "Polling should report changes, because they fall within the included region.", project.poll(listener).hasChanges()); } @@ -898,7 +961,7 @@ public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -915,7 +978,10 @@ public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "included/should-be-processed"; - commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); + commit( + fileToMerge, + johnDoe, + "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); @@ -925,7 +991,8 @@ public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { // When this test passes, project.poll(listener).hasChanges()) should return // true, because our commit falls within the included region. - assertTrue("Polling should report changes, because they are in the included directory.", + assertTrue( + "Polling should report changes, because they are in the included directory.", project.poll(listener).hasChanges()); } @@ -937,7 +1004,7 @@ public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -963,7 +1030,8 @@ public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our commit falls outside the included region. - assertFalse("Polling should ignore the change, because it falls outside the included region.", + assertFalse( + "Polling should ignore the change, because it falls outside the included region.", project.poll(listener).hasChanges()); } @@ -975,7 +1043,7 @@ public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -1001,7 +1069,8 @@ public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception mergeCommand.execute(); // Should return false, because our commit falls outside of the included directory - assertFalse("Polling should ignore the change, because it falls outside the included directory.", + assertFalse( + "Polling should ignore the change, because it falls outside the included directory.", project.poll(listener).hasChanges()); } @@ -1014,7 +1083,7 @@ public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -1031,7 +1100,10 @@ public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); final String fileToMerge = "fileToMerge.should-be-processed"; - commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); + commit( + fileToMerge, + johnDoe, + "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); @@ -1040,7 +1112,8 @@ public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded region - assertTrue("Polling should process the change, because it falls outside the excluded region.", + assertTrue( + "Polling should process the change, because it falls outside the excluded region.", project.poll(listener).hasChanges()); } @@ -1053,7 +1126,7 @@ public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -1071,7 +1144,10 @@ public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exceptio testRepo.git.checkoutBranch(branchToMerge, "HEAD~"); // Create this new file outside of our excluded directory final String fileToMerge = "directory-to-include/file-should-be-processed"; - commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); + commit( + fileToMerge, + johnDoe, + "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge); ObjectId branchSHA = git.revParse("HEAD"); testRepo.git.checkoutBranch("master", "refs/heads/master"); @@ -1080,7 +1156,8 @@ public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exceptio mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded directory - assertTrue("SCM polling should process the change, because it falls outside the excluded directory.", + assertTrue( + "SCM polling should process the change, because it falls outside the excluded directory.", project.poll(listener).hasChanges()); } @@ -1094,32 +1171,39 @@ public void testIncludedRegionWithDeeperCommits() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); - + assertFalse( + "scm polling detected commit2 change, which should not have been included", + project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - + final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit3 change", + project.poll(listener).hasChanges()); - //... and build it... + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); - + PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test @@ -1132,16 +1216,22 @@ public void testBasicExcludedRegion() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); + assertFalse( + "scm polling detected commit2 change, which should have been excluded", + project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit3 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); @@ -1152,7 +1242,9 @@ public void testBasicExcludedRegion() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } private int findLogLineStartsWith(List buildLog, String initialString) { @@ -1169,8 +1261,8 @@ private int findLogLineStartsWith(List buildLog, String initialString) { @Test public void testCleanBeforeCheckout() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); - ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); + FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); + ((GitSCM) p.getScm()).getExtensions().add(new CleanBeforeCheckout()); /* First build should not clean, since initial clone is always clean */ final String commitFile1 = "commitFile1"; @@ -1200,21 +1292,33 @@ public void testExcludedRegionMultiCommit() throws Exception { build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); - assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); - assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after initial build", + clientProject.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after initial build", + serverProject.poll(listener).hasChanges()); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); - assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); - assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any changes in client project", + clientProject.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect changes in server project", + serverProject.poll(listener).hasChanges()); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); - assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); - assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect changes in client project", + clientProject.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect changes in server project", + serverProject.poll(listener).hasChanges()); } /* @@ -1303,15 +1407,21 @@ public void testBasicExcludedUser() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); + assertFalse( + "scm polling detected commit2 change, which should have been excluded", + project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit3 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); @@ -1322,36 +1432,46 @@ public void testBasicExcludedUser() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); - + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test public void testBasicInSubdir() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject project = setupSimpleProject("master"); - ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); + ((GitSCM) project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... - final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, - commitFile2); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... + final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); - assertTrue("The workspace should have a 'subdir' subdirectory, but does not.", build2.getWorkspace().child("subdir").exists()); - assertTrue("The 'subdir' subdirectory should contain commitFile2, but does not.", build2.getWorkspace().child("subdir").child(commitFile2).exists()); + assertTrue( + "The workspace should have a 'subdir' subdirectory, but does not.", + build2.getWorkspace().child("subdir").exists()); + assertTrue( + "The 'subdir' subdirectory should contain commitFile2, but does not.", + build2.getWorkspace().child("subdir").child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Issue("HUDSON-7547") @@ -1369,19 +1489,25 @@ public void testBasicWithAgentNoExecutorsOnMaster() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test @@ -1395,21 +1521,29 @@ public void testAuthorOrCommitterFalse() throws Exception { commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final Set secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); - assertEquals("Did not get the committer as the change author with authorOrCommitter==false", - janeDoe.getName(), secondCulprits.iterator().next().getFullName()); + assertEquals( + "Did not get the committer as the change author with authorOrCommitter==false", + janeDoe.getName(), + secondCulprits.iterator().next().getFullName()); } @Test @@ -1417,28 +1551,36 @@ public void testAuthorOrCommitterTrue() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); - ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); + ((GitSCM) project.getScm()).getExtensions().add(new AuthorInChangelog()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final Set secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); - assertEquals("Did not get the author as the change author with authorOrCommitter==true", - johnDoe.getName(), secondCulprits.iterator().next().getFullName()); + assertEquals( + "Did not get the author as the change author with authorOrCommitter==true", + johnDoe.getName(), + secondCulprits.iterator().next().getFullName()); } @Test @@ -1451,12 +1593,14 @@ public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - //now create and checkout a new branch: + // now create and checkout a new branch: git.checkout(Constants.HEAD, "untracked"); - //.. and commit to it: + // .. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect commit2 change because it is not in the branch we are tracking.", + project.poll(listener).hasChanges()); } private String checkoutString(FreeStyleProject project, String envVar) { @@ -1501,7 +1645,9 @@ public void testNodeOverrideGit() throws Exception { String gitExe = scm.getGitExe(agent, TaskListener.NULL); assertEquals("/usr/bin/git", gitExe); - ToolLocationNodeProperty nodeGitLocation = new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(gitToolDescriptor, "Default", "C:\\Program Files\\Git\\bin\\git.exe")); + ToolLocationNodeProperty nodeGitLocation = + new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + gitToolDescriptor, "Default", "C:\\Program Files\\Git\\bin\\git.exe")); agent.setNodeProperties(Collections.singletonList(nodeGitLocation)); gitExe = scm.getGitExe(agent, TaskListener.NULL); @@ -1527,15 +1673,17 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // actual data. build(project, Result.FAILURE); // fail, because there's nothing to be checked out here - //now create and checkout a new branch: + // now create and checkout a new branch: final String tmpBranch = "tmp"; git.branch(tmpBranch); git.checkout(tmpBranch); // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); - build(project, Result.FAILURE); // fail, because there's nothing to be checked out here + assertFalse( + "scm polling should not detect any more changes since mytag is untouched right now", + project.poll(listener).hasChanges()); + build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch git.tag(mytag, "mytag initial"); @@ -1544,9 +1692,13 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" - assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect commit2 change in 'mytag'", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after last build", + project.poll(listener).hasChanges()); // now, create tmp branch again against mytag: git.checkout(mytag); @@ -1554,17 +1706,24 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes since mytag is untouched right now", + project.poll(listener).hasChanges()); - // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: + // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the + // change up: git.tag(mytag, "mytag moved"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: - assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect commit3 change in 'mytag'", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile3); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after last build", + project.poll(listener).hasChanges()); } /* @@ -1588,9 +1747,13 @@ public void testMultipleBranchBuild() throws Exception { commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect changes in 'master' branch", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after last build", + project.poll(listener).hasChanges()); // now jump back... git.checkout(fork); @@ -1600,17 +1763,20 @@ public void testMultipleBranchBuild() throws Exception { commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); - assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect changes in 'fork' branch", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS, forkFile1, forkFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after last build", + project.poll(listener).hasChanges()); } @Test public void testMultipleBranchesWithTags() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - List branchSpecs = Arrays.asList( - new BranchSpec("refs/tags/v*"), - new BranchSpec("refs/remotes/origin/non-existent")); + List branchSpecs = + Arrays.asList(new BranchSpec("refs/tags/v*"), new BranchSpec("refs/remotes/origin/non-existent")); FreeStyleProject project = setupProject(branchSpecs, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: @@ -1634,7 +1800,7 @@ public void testMultipleBranchesWithTags() throws Exception { freeStyleBuild = build(project, Result.SUCCESS); ObjectId tag = git.revParse(Constants.R_TAGS + v1); - GitSCM scm = (GitSCM)project.getScm(); + GitSCM scm = (GitSCM) project.getScm(); BuildData buildData = scm.getBuildData(freeStyleBuild); assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1()); @@ -1655,9 +1821,10 @@ public void testSubmoduleFixup() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); File repo = secondRepo.getRoot(); FilePath moduleWs = new FilePath(repo); - org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); + org.jenkinsci.plugins.gitclient.GitClient moduleRepo = + Git.with(listener, new EnvVars()).in(repo).getClient(); - {// first we create a Git repository with submodule + { // first we create a Git repository with submodule moduleRepo.init(); moduleWs.child("a").touch(0); moduleRepo.add("a"); @@ -1672,32 +1839,31 @@ public void testSubmoduleFixup() throws Exception { FreeStyleProject d = createFreeStyleProject(); u.setScm(new GitSCM(workDir.getPath())); - u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS, - new GitRevisionBuildParameters()))); + u.getPublishersList() + .add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig( + d.getName(), ResultCondition.SUCCESS, new GitRevisionBuildParameters()))); d.setScm(new GitSCM(workDir.getPath())); rule.jenkins.rebuildDependencyGraph(); - FreeStyleBuild ub = rule.buildAndAssertSuccess(u); - for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop + // wait only up to 10 sec to avoid infinite loop + for (int i = 0; (d.getLastBuild() == null || d.getLastBuild().isBuilding()) && i < 100; i++) { Thread.sleep(100); + } FreeStyleBuild db = d.getLastBuild(); - assertNotNull("downstream build didn't happen",db); + assertNotNull("downstream build didn't happen", db); db = rule.waitForCompletion(db); rule.assertBuildStatusSuccess(db); } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) - static public void assertCulprits(String assertMsg, Set actual, PersonIdent[] expected) - { - List fullNames = - actual.stream().map(User::getFullName).collect(Collectors.toList()); + public static void assertCulprits(String assertMsg, Set actual, PersonIdent[] expected) { + List fullNames = actual.stream().map(User::getFullName).collect(Collectors.toList()); - for(PersonIdent p : expected) - { + for (PersonIdent p : expected) { assertTrue(assertMsg, fullNames.contains(p.getName())); } } @@ -1708,9 +1874,10 @@ public void testHideCredentials() throws Exception { FreeStyleProject project = setupSimpleProject("master"); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); // setup global config - List remoteConfigs = GitSCM.createRepoList("https://github.com/jenkinsci/git-plugin", "github"); - project.setScm(new GitSCM(remoteConfigs, - Collections.singletonList(new BranchSpec("master")), false, null, null, null, null)); + List remoteConfigs = + GitSCM.createRepoList("https://github.com/jenkinsci/git-plugin", "github"); + project.setScm(new GitSCM( + remoteConfigs, Collections.singletonList(new BranchSpec("master")), false, null, null, null, null)); GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); @@ -1737,10 +1904,8 @@ public void testHideCredentials() throws Exception { build(project, Result.SUCCESS); logLines = project.getLastBuild().getLog(100); assertThat(logLines, not(hasItem("using credential github"))); - } - @Test public void testEmailCommitter() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -1753,23 +1918,30 @@ public void testEmailCommitter() throws Exception { descriptor.setCreateAccountBasedOnEmail(true); assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail()); - assertFalse("Wrong initial value for use existing user if same e-mail already found", scm.isUseExistingAccountWithSameEmail()); + assertFalse( + "Wrong initial value for use existing user if same e-mail already found", + scm.isUseExistingAccountWithSameEmail()); descriptor.setUseExistingAccountWithSameEmail(true); - assertTrue("Use existing user if same e-mail already found is not set", scm.isUseExistingAccountWithSameEmail()); + assertTrue( + "Use existing user if same e-mail already found is not set", scm.isUseExistingAccountWithSameEmail()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com"); commit(commitFile2, jeffDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); @@ -1781,7 +1953,7 @@ public void testEmailCommitter() throws Exception { rule.assertBuildStatusSuccess(build); } - + @Issue("JENKINS-59868") @Test public void testNonExistentWorkingDirectoryPoll() throws Exception { @@ -1792,9 +1964,10 @@ public void testNonExistentWorkingDirectoryPoll() throws Exception { final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( - ((GitSCM)project.getScm()).getUserRemoteConfigs(), + ((GitSCM) project.getScm()).getUserRemoteConfigs(), Collections.singletonList(new BranchSpec("master")), - null, null, + null, + null, // configure GitSCM with the DisableRemotePoll extension to ensure that polling use the workspace Collections.singletonList(new DisableRemotePoll()))); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); @@ -1810,10 +1983,13 @@ public void testNonExistentWorkingDirectoryPoll() throws Exception { // Make sure that polling returns BUILD_NOW and properly log the reason FilePath filePath = build1.getWorkspace(); - assertThat(project.getScm().compareRemoteRevisionWith(project, new Launcher.LocalLauncher(taskListener), - filePath, taskListener, null), is(PollingResult.BUILD_NOW)); - assertTrue(pollLogHandler.getView().stream().anyMatch(m -> - m.getMessage().contains("[poll] Working Directory does not exist"))); + assertThat( + project.getScm() + .compareRemoteRevisionWith( + project, new Launcher.LocalLauncher(taskListener), filePath, taskListener, null), + is(PollingResult.BUILD_NOW)); + assertTrue(pollLogHandler.getView().stream() + .anyMatch(m -> m.getMessage().contains("[poll] Working Directory does not exist"))); } // Disabled - consistently fails, needs more analysis @@ -1828,10 +2004,7 @@ public void testFetchFromMultipleRepositories() throws Exception { remotes.addAll(secondTestRepo.remoteConfigs()); project.setScm(new GitSCM( - remotes, - Collections.singletonList(new BranchSpec("master")), - null, null, - Collections.emptyList())); + remotes, Collections.singletonList(new BranchSpec("master")), null, null, Collections.emptyList())); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; @@ -1842,17 +2015,23 @@ public void testFetchFromMultipleRepositories() throws Exception { SCMRevisionState baseline = project.poll(listener).baseline; Change change = project.poll(listener).change; SCMRevisionState remote = project.poll(listener).remote; - String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote); + String assertionMessage = MessageFormat.format( + "polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", + baseline, change, remote); assertFalse(assertionMessage, project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); - //... and build it... + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); + // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } private void branchSpecWithMultipleRepositories(String branchName) throws Exception { @@ -1868,10 +2047,7 @@ private void branchSpecWithMultipleRepositories(String branchName) throws Except commit(commitFile1, johnDoe, "Commit number 1"); project.setScm(new GitSCM( - remotes, - Collections.singletonList(new BranchSpec(branchName)), - null, null, - Collections.emptyList())); + remotes, Collections.singletonList(new BranchSpec(branchName)), null, null, Collections.emptyList())); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); rule.assertBuildStatusSuccess(build); @@ -1901,14 +2077,18 @@ public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception GitSCM gitSCM = new GitSCM( remotes, Collections.singletonList(new BranchSpec("origin/master")), - null, null, + null, + null, Collections.emptyList()); project.setScm(gitSCM); /* Check that polling would force build through * compareRemoteRevisionWith by detecting no last build */ FilePath filePath = new FilePath(new File(".")); - assertThat(gitSCM.compareRemoteRevisionWith(project, new Launcher.LocalLauncher(listener), filePath, listener, null), is(PollingResult.BUILD_NOW)); + assertThat( + gitSCM.compareRemoteRevisionWith( + project, new Launcher.LocalLauncher(listener), filePath, listener, null), + is(PollingResult.BUILD_NOW)); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1"); @@ -1919,10 +2099,12 @@ public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs()); } BuildChooser buildChooser = gitSCM.getBuildChooser(); - Collection candidateRevisions = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); + Collection candidateRevisions = buildChooser.getCandidateRevisions( + false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertEquals(1, candidateRevisions.size()); gitSCM.setBuildChooser(buildChooser); // Should be a no-op - Collection candidateRevisions2 = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); + Collection candidateRevisions2 = buildChooser.getCandidateRevisions( + false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertThat(candidateRevisions2, is(candidateRevisions)); } @@ -1946,9 +2128,12 @@ public void testMerge() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions() + .add(new PreBuildMerge(new UserMergeOptions( + "origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); @@ -1963,7 +2148,9 @@ public void testMerge() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -1971,11 +2158,15 @@ public void testMerge() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Issue("JENKINS-20392") @@ -1987,9 +2178,12 @@ public void testMergeChangelog() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions() + .add(new PreBuildMerge(new UserMergeOptions( + "origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); @@ -2011,7 +2205,10 @@ public void testMergeChangelog() throws Exception { assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; - assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); + assertEquals( + "Changelog should contain commit number 2", + commitMessage, + singleChange.getComment().trim()); } @Test @@ -2022,10 +2219,13 @@ public void testMergeFailed() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions() + .add(new PreBuildMerge( + new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); // create initial commit and then run the build against it: @@ -2039,56 +2239,69 @@ public void testMergeFailed() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue( + "scm polling did not detect commit2 change", + project.poll(listener).hasChanges()); rule.buildAndAssertStatus(Result.FAILURE, project); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } - + @Issue("JENKINS-25191") @Test public void testMultipleMergeFailed() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupSimpleProject("master"); - - GitSCM scm = new GitSCM( - createRemoteRepositories(), - Collections.singletonList(new BranchSpec("master")), - null, null, - Collections.emptyList()); - project.setScm(scm); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); - scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); + FreeStyleProject project = setupSimpleProject("master"); + + GitSCM scm = new GitSCM( + createRemoteRepositories(), + Collections.singletonList(new BranchSpec("master")), + null, + null, + Collections.emptyList()); + project.setScm(scm); + scm.getExtensions() + .add(new PreBuildMerge( + new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions() + .add(new PreBuildMerge( + new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); - - commit("dummyFile", johnDoe, "Initial Commit"); - testRepo.git.branch("integration1"); - testRepo.git.branch("integration2"); - build(project, Result.SUCCESS); - - final String commitFile = "commitFile"; - testRepo.git.checkoutBranch("integration1","master"); - commit(commitFile,"abc", johnDoe, "merge conflict with integration2"); - - testRepo.git.checkoutBranch("integration2","master"); - commit(commitFile,"cde", johnDoe, "merge conflict with integration1"); - - final FreeStyleBuild build = build(project, Result.FAILURE); - - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + + commit("dummyFile", johnDoe, "Initial Commit"); + testRepo.git.branch("integration1"); + testRepo.git.branch("integration2"); + build(project, Result.SUCCESS); + + final String commitFile = "commitFile"; + testRepo.git.checkoutBranch("integration1", "master"); + commit(commitFile, "abc", johnDoe, "merge conflict with integration2"); + + testRepo.git.checkoutBranch("integration2", "master"); + commit(commitFile, "cde", johnDoe, "merge conflict with integration1"); + + final FreeStyleBuild build = build(project, Result.FAILURE); + + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); } @Test public void testEnvironmentVariableExpansion() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject project = createFreeStyleProject(); - project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); + project.setScm(new GitSCM("${CAT}" + testRepo.gitDir.getPath())); // create initial commit and then run the build against it: commit("a.txt", johnDoe, "Initial Commit"); @@ -2109,8 +2322,9 @@ public void testEnvironmentVariableExpansion() throws Exception { @TestExtension("testEnvironmentVariableExpansion") public static class SupplySomeEnvVars extends EnvironmentContributor { @Override - public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { - envs.put("CAT",""); + public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) + throws IOException, InterruptedException { + envs.put("CAT", ""); } } @@ -2120,7 +2334,8 @@ public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) thro @Test public void testDataCompatibility1() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); + FreeStyleProject p = (FreeStyleProject) + rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); @@ -2149,46 +2364,65 @@ public void testCheckoutReturnsLatestValues() throws Exception { WorkflowJob p = rule.jenkins.createProject(WorkflowJob.class, "pipeline-checkout-3-tags"); p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " def tokenBranch = ''\n" + - " def tokenRevision = ''\n" + - " def checkout1 = checkout([$class: 'GitSCM', branches: [[name: 'git-1.1']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + - " echo \"checkout1: ${checkout1}\"\n" + - " tokenBranch = tm '${GIT_BRANCH}'\n" + - " tokenRevision = tm '${GIT_REVISION}'\n" + - " echo \"token1: ${tokenBranch}\"\n" + - " echo \"revision1: ${tokenRevision}\"\n" + - " def checkout2 = checkout([$class: 'GitSCM', branches: [[name: 'git-2.0.2']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + - " echo \"checkout2: ${checkout2}\"\n" + - " tokenBranch = tm '${GIT_BRANCH,all=true}'\n" + - " tokenRevision = tm '${GIT_REVISION,length=8}'\n" + - " echo \"token2: ${tokenBranch}\"\n" + - " echo \"revision2: ${tokenRevision}\"\n" + - " def checkout3 = checkout([$class: 'GitSCM', branches: [[name: 'git-3.0.0']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + - " echo \"checkout3: ${checkout3}\"\n" + - " tokenBranch = tm '${GIT_BRANCH,fullName=true}'\n" + - " tokenRevision = tm '${GIT_REVISION,length=6}'\n" + - " echo \"token3: ${tokenBranch}\"\n" + - " echo \"revision3: ${tokenRevision}\"\n" + - "}", true)); + "node {\n" + " def tokenBranch = ''\n" + + " def tokenRevision = ''\n" + + " def checkout1 = checkout([$class: 'GitSCM', branches: [[name: 'git-1.1']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + + " echo \"checkout1: ${checkout1}\"\n" + + " tokenBranch = tm '${GIT_BRANCH}'\n" + + " tokenRevision = tm '${GIT_REVISION}'\n" + + " echo \"token1: ${tokenBranch}\"\n" + + " echo \"revision1: ${tokenRevision}\"\n" + + " def checkout2 = checkout([$class: 'GitSCM', branches: [[name: 'git-2.0.2']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + + " echo \"checkout2: ${checkout2}\"\n" + + " tokenBranch = tm '${GIT_BRANCH,all=true}'\n" + + " tokenRevision = tm '${GIT_REVISION,length=8}'\n" + + " echo \"token2: ${tokenBranch}\"\n" + + " echo \"revision2: ${tokenRevision}\"\n" + + " def checkout3 = checkout([$class: 'GitSCM', branches: [[name: 'git-3.0.0']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]])\n" + + " echo \"checkout3: ${checkout3}\"\n" + + " tokenBranch = tm '${GIT_BRANCH,fullName=true}'\n" + + " tokenRevision = tm '${GIT_REVISION,length=6}'\n" + + " echo \"token3: ${tokenBranch}\"\n" + + " echo \"revision3: ${tokenRevision}\"\n" + + "}", + true)); WorkflowRun b = rule.buildAndAssertSuccess(p); - + String log = b.getLog(); // The getLineStartsWith is to ease reading the test failure, to avoid Hamcrest shows all the log - assertThat(getLineStartsWith(log, "checkout1:"), containsString("checkout1: [GIT_BRANCH:git-1.1, GIT_COMMIT:82db9509c068f60c41d7a4572c0114cc6d23cd0d, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); - assertThat(getLineStartsWith(log, "checkout2:"), containsString("checkout2: [GIT_BRANCH:git-2.0.2, GIT_COMMIT:377a0fdbfbf07f70a3e9a566d749b2a185909c33, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); - assertThat(getLineStartsWith(log, "checkout3:"), containsString("checkout3: [GIT_BRANCH:git-3.0.0, GIT_COMMIT:858dee578b79ac6683419faa57a281ccb9d347aa, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); + assertThat( + getLineStartsWith(log, "checkout1:"), + containsString( + "checkout1: [GIT_BRANCH:git-1.1, GIT_COMMIT:82db9509c068f60c41d7a4572c0114cc6d23cd0d, GIT_COMMIT_TITLE:[maven-release-plugin] prepare release git-1.1, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); + assertThat( + getLineStartsWith(log, "checkout2:"), + containsString( + "checkout2: [GIT_BRANCH:git-2.0.2, GIT_COMMIT:377a0fdbfbf07f70a3e9a566d749b2a185909c33, GIT_COMMIT_TITLE:[maven-release-plugin] prepare release git-2.0.2, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); + assertThat( + getLineStartsWith(log, "checkout3:"), + containsString( + "checkout3: [GIT_BRANCH:git-3.0.0, GIT_COMMIT:858dee578b79ac6683419faa57a281ccb9d347aa, GIT_COMMIT_TITLE:[maven-release-plugin] prepare release git-3.0.0, GIT_URL:https://github.com/jenkinsci/git-plugin.git]")); assertThat(getLineStartsWith(log, "token1:"), containsString("token1: git-1.1")); - assertThat(getLineStartsWith(log, "token2:"), containsString("token2: git-1.1")); // Unexpected but current behavior - assertThat(getLineStartsWith(log, "token3:"), containsString("token3: git-1.1")); // Unexpected but current behavior - assertThat(getLineStartsWith(log, "revision1:"), containsString("revision1: 82db9509c068f60c41d7a4572c0114cc6d23cd0d")); - assertThat(getLineStartsWith(log, "revision2:"), containsString("revision2: 82db9509")); // Unexpected but current behavior - should be 377a0fdb - assertThat(getLineStartsWith(log, "revision3:"), containsString("revision3: 82db95")); // Unexpected but current behavior - should be 858dee + assertThat( + getLineStartsWith(log, "token2:"), + containsString("token2: git-1.1")); // Unexpected but current behavior + assertThat( + getLineStartsWith(log, "token3:"), + containsString("token3: git-1.1")); // Unexpected but current behavior + assertThat( + getLineStartsWith(log, "revision1:"), + containsString("revision1: 82db9509c068f60c41d7a4572c0114cc6d23cd0d")); + assertThat( + getLineStartsWith(log, "revision2:"), + containsString("revision2: 82db9509")); // Unexpected but current behavior - should be 377a0fdb + assertThat( + getLineStartsWith(log, "revision3:"), + containsString("revision3: 82db95")); // Unexpected but current behavior - should be 858dee } private String getLineStartsWith(String text, String startOfLine) { try (Scanner scanner = new Scanner(text)) { - while(scanner.hasNextLine()) { + while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith(startOfLine)) { return line; @@ -2197,7 +2431,7 @@ private String getLineStartsWith(String text, String startOfLine) { } return ""; } - + @Test public void testPleaseDontContinueAnyway() throws Exception { /* Wastes time waiting for the build to fail */ @@ -2208,7 +2442,7 @@ public void testPleaseDontContinueAnyway() throws Exception { } assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); // create an empty repository with some commits - testRepo.commit("a","foo",johnDoe, "added"); + testRepo.commit("a", "foo", johnDoe, "added"); FreeStyleProject p = createFreeStyleProject(); p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath())); @@ -2231,22 +2465,24 @@ public void testCheckoutToSpecificBranch() throws Exception { p.setScm(oldGit); FreeStyleBuild b = rule.buildAndAssertSuccess(p); - GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); + GitClient gc = Git.with(StreamTaskListener.fromStdout(), null) + .in(b.getWorkspace()) + .getClient(); gc.withRepository((RepositoryCallback) (repo, channel) -> { Ref head = repo.findRef("HEAD"); - assertTrue("Detached HEAD",head.isSymbolic()); + assertTrue("Detached HEAD", head.isSymbolic()); Ref t = head.getTarget(); - assertEquals(t.getName(),"refs/heads/master"); + assertEquals(t.getName(), "refs/heads/master"); return null; }); } - + /** - * Verifies that if project specifies LocalBranch with value of "**" + * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated - * pom.xml to remote branch as + * pom.xml to remote branch as *
      * git push origin localbranch:localbranch
      * 
@@ -2254,24 +2490,24 @@ public void testCheckoutToSpecificBranch() throws Exception { */ @Test public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupSimpleProject("master"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = setupSimpleProject("master"); - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - GitSCM git = (GitSCM)project.getScm(); - git.getExtensions().add(new LocalBranch("**")); - FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + GitSCM git = (GitSCM) project.getScm(); + git.getExtensions().add(new LocalBranch("**")); + FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); - assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); + assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); + assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** - * Verifies that if project specifies LocalBranch with null value (empty string) + * Verifies that if project specifies LocalBranch with null value (empty string) * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated - * pom.xml to remote branch as + * pom.xml to remote branch as *
      * git push origin localbranch:localbranch
      * 
@@ -2279,17 +2515,17 @@ public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { */ @Test public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupSimpleProject("master"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = setupSimpleProject("master"); - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - GitSCM git = (GitSCM)project.getScm(); - git.getExtensions().add(new LocalBranch("")); - FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + GitSCM git = (GitSCM) project.getScm(); + git.getExtensions().add(new LocalBranch("")); + FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); - assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); + assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); + assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /* @@ -2298,33 +2534,33 @@ public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { */ @Test public void testCheckoutSansLocalBranchExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupSimpleProject("master"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = setupSimpleProject("master"); - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); + assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertNull("GIT_LOCAL_BRANCH", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } - + /* * Verifies that GIT_CHECKOUT_DIR is set to "checkoutDir" if RelativeTargetDirectory extension * is configured. */ @Test public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupProject("master", false, "checkoutDir"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = setupProject("master", false, "checkoutDir"); - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - GitSCM git = (GitSCM)project.getScm(); - git.getExtensions().add(new RelativeTargetDirectory("checkoutDir")); - FreeStyleBuild build1 = build(project, "checkoutDir", Result.SUCCESS, commitFile1); + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + GitSCM git = (GitSCM) project.getScm(); + git.getExtensions().add(new RelativeTargetDirectory("checkoutDir")); + FreeStyleBuild build1 = build(project, "checkoutDir", Result.SUCCESS, commitFile1); - assertEquals("GIT_CHECKOUT_DIR", "checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); + assertEquals("GIT_CHECKOUT_DIR", "checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); } /* @@ -2333,15 +2569,16 @@ public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { */ @Test public void testCheckoutSansRelativeTargetDirectoryExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = setupSimpleProject("master"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = setupSimpleProject("master"); - final String commitFile1 = "commitFile1"; - commit(commitFile1, johnDoe, "Commit number 1"); - FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, "Commit number 1"); + FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertNull("GIT_CHECKOUT_DIR", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); } + @Test public void testCheckoutFailureIsRetryable() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); @@ -2383,7 +2620,9 @@ public void testSparseCheckoutAfterNormalCheckout() throws Exception { assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - ((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Collections.singletonList(new SparseCheckoutPath("titi")))); + ((GitSCM) project.getScm()) + .getExtensions() + .add(new SparseCheckoutPaths(Collections.singletonList(new SparseCheckoutPath("titi")))); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); @@ -2416,7 +2655,6 @@ public void testNormalCheckoutAfterSparseCheckout() throws Exception { assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - } @Test @@ -2428,7 +2666,8 @@ public void testPolling_environmentValueInBranchSpec() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); @@ -2439,17 +2678,16 @@ public void testPolling_environmentValueInBranchSpec() throws Exception { // build the project build(project, Result.SUCCESS); - assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); + assertFalse( + "No changes to git since last build, thus no new build is expected", + project.poll(listener).hasChanges()); } public void baseTestPolling_parentHead(List extensions) throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( - createRemoteRepositories(), - Collections.singletonList(new BranchSpec("**")), - null, null, - extensions); + createRemoteRepositories(), Collections.singletonList(new BranchSpec("**")), null, null, extensions); project.setScm(scm); // commit something in order to create an initial base version in git @@ -2457,7 +2695,7 @@ public void baseTestPolling_parentHead(List extensions) throws git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); - assertTrue("polling should detect changes",project.poll(listener).hasChanges()); + assertTrue("polling should detect changes", project.poll(listener).hasChanges()); // build the project build(project, Result.SUCCESS); @@ -2467,7 +2705,7 @@ public void baseTestPolling_parentHead(List extensions) throws */ assertEquals("Wrong number of builds", 1, project.getBuilds().size()); - assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); + assertFalse("polling should not detect changes", project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") @@ -2492,21 +2730,24 @@ public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Excep GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); - project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); + project.addProperty( + new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); // Initial commit to master commit("file1", johnDoe, "Initial Commit"); - + // Create the branches git.branch("trackedbranch"); git.branch("manualbranch"); - + final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch"); final Action[] actions = {new ParametersAction(branchParam)}; - FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); + FreeStyleBuild build = + project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); @@ -2517,10 +2758,11 @@ public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Excep git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); - assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); - + assertTrue( + "A change should be detected in tracked branch", + project.poll(listener).hasChanges()); } - + private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; @@ -2529,19 +2771,23 @@ public FakeParametersAction(StringParameterValue params) { this.m_forwardingAction = new ParametersAction(params); } + @Override @Deprecated public void buildEnvVars(AbstractBuild ab, EnvVars ev) { this.m_forwardingAction.buildEnvVars(ab, ev); } + @Override public String getIconFileName() { return this.m_forwardingAction.getIconFileName(); } + @Override public String getDisplayName() { return this.m_forwardingAction.getDisplayName(); } + @Override public String getUrlName() { return this.m_forwardingAction.getUrlName(); } @@ -2550,37 +2796,39 @@ public List getParameters() { return this.m_forwardingAction.getParameters(); } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - } + private void writeObject(java.io.ObjectOutputStream out) throws IOException {} - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - } + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {} - private void readObjectNoData() throws ObjectStreamException { - } + private void readObjectNoData() throws ObjectStreamException {} } @Test - public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject project = createFreeStyleProject(); - List remoteConfigs = new ArrayList<>(); - remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); - remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); - GitSCM scm = new GitSCM(remoteConfigs, - Collections.singletonList(new BranchSpec("origin/master")), false, - Collections.emptyList(), null, null, - Collections.emptyList()); - project.setScm(scm); - commit("commitFile1", johnDoe, "Commit number 1"); + public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject project = createFreeStyleProject(); + List remoteConfigs = new ArrayList<>(); + remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); + remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); + GitSCM scm = new GitSCM( + remoteConfigs, + Collections.singletonList(new BranchSpec("origin/master")), + false, + Collections.emptyList(), + null, + null, + Collections.emptyList()); + project.setScm(scm); + commit("commitFile1", johnDoe, "Commit number 1"); - FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserIdCause()).get(); + FreeStyleBuild first_build = + project.scheduleBuild2(0, new Cause.UserIdCause()).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); - first_build.getWorkspace().deleteContents(); - PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); - assertFalse(pollingResult.hasChanges()); - } + first_build.getWorkspace().deleteContents(); + PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); + assertFalse(pollingResult.hasChanges()); + } @Issue("JENKINS-24467") @Test @@ -2591,7 +2839,8 @@ public void testPolling_environmentValueAsEnvironmentContributingAction() throws GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); @@ -2606,7 +2855,8 @@ public void testPolling_environmentValueAsEnvironmentContributingAction() throws // SECURITY-170 - have to use ParametersDefinitionProperty project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); - FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); + FreeStyleBuild first_build = + project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); @@ -2626,8 +2876,14 @@ public void testPolling_environmentValueAsEnvironmentContributingAction() throws * @param git git SCM * @throws Exception on error */ - private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, - String expectedScmName, int ordinal, GitSCM git, ObjectId... priorCommits) throws Exception { + private int notifyAndCheckScmName( + FreeStyleProject project, + ObjectId commit, + String expectedScmName, + int ordinal, + GitSCM git, + ObjectId... priorCommits) + throws Exception { StringBuilder priorCommitIDs = new StringBuilder(); for (ObjectId priorCommit : priorCommits) { priorCommitIDs.append(" ").append(priorCommit); @@ -2636,9 +2892,14 @@ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, final Build build = project.getLastBuild(); final BuildData buildData = git.getBuildData(build); - assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData - .getLastBuiltRevision().getSha1()); - assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData.getLastBuild(commit).getSHA1()); + assertEquals( + "Expected SHA1 != built SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, + commit, + buildData.getLastBuiltRevision().getSha1()); + assertEquals( + "Expected SHA1 != retrieved SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, + commit, + buildData.getLastBuild(commit).getSHA1()); assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit)); assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName()); @@ -2646,15 +2907,15 @@ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, return build.getNumber(); } - private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, - String expectedScmName, GitSCM git) throws Exception { + private void checkNumberedBuildScmName( + FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); } /* A null pointer exception was detected because the plugin failed to - * write a branch name to the build data, so there was a SHA1 recorded + * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ @Test @@ -2697,129 +2958,129 @@ public void testNoNullPointerExceptionWithNullBranch() throws Exception { @Test @Deprecated // Testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchStarStar() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); - /* This is the null that causes NPE */ - Branch branch = new Branch("origin/master", sha1); + /* This is the null that causes NPE */ + Branch branch = new Branch("origin/master", sha1); - List branchList = new ArrayList<>(); - branchList.add(branch); + List branchList = new ArrayList<>(); + branchList.add(branch); - Revision revision = new Revision(sha1, branchList); + Revision revision = new Revision(sha1, branchList); + + /* BuildData mock that will use the Revision with null branch name */ + BuildData buildData = Mockito.mock(BuildData.class); + Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); + Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); - /* BuildData mock that will use the Revision with null branch name */ - BuildData buildData = Mockito.mock(BuildData.class); - Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); - Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); + /* List of build data that will be returned by the mocked BuildData */ + List buildDataList = new ArrayList<>(); + buildDataList.add(buildData); - /* List of build data that will be returned by the mocked BuildData */ - List buildDataList = new ArrayList<>(); - buildDataList.add(buildData); + /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ + AbstractBuild build = Mockito.mock(AbstractBuild.class); + Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); - /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ - AbstractBuild build = Mockito.mock(AbstractBuild.class); - Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); + final FreeStyleProject project = setupProject("*/*", false); + GitSCM scm = (GitSCM) project.getScm(); + scm.getExtensions().add(new LocalBranch("**")); - final FreeStyleProject project = setupProject("*/*", false); - GitSCM scm = (GitSCM) project.getScm(); - scm.getExtensions().add(new LocalBranch("**")); + EnvVars env = new EnvVars(); + scm.buildEnvVars(build, env); // NPE here before fix applied - EnvVars env = new EnvVars(); - scm.buildEnvVars(build, env); // NPE here before fix applied - - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); + assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); - /* Verify mocks were called as expected */ - verify(buildData, times(1)).getLastBuiltRevision(); - verify(buildData, times(1)).hasBeenReferenced(anyString()); - verify(build, times(1)).getActions(BuildData.class); + /* Verify mocks were called as expected */ + verify(buildData, times(1)).getLastBuiltRevision(); + verify(buildData, times(1)).hasBeenReferenced(anyString()); + verify(build, times(1)).getActions(BuildData.class); } @Test @Deprecated // Testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchNull() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); - /* This is the null that causes NPE */ - Branch branch = new Branch("origin/master", sha1); + /* This is the null that causes NPE */ + Branch branch = new Branch("origin/master", sha1); - List branchList = new ArrayList<>(); - branchList.add(branch); + List branchList = new ArrayList<>(); + branchList.add(branch); + + Revision revision = new Revision(sha1, branchList); - Revision revision = new Revision(sha1, branchList); + /* BuildData mock that will use the Revision with null branch name */ + BuildData buildData = Mockito.mock(BuildData.class); + Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); + Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); - /* BuildData mock that will use the Revision with null branch name */ - BuildData buildData = Mockito.mock(BuildData.class); - Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); - Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); + /* List of build data that will be returned by the mocked BuildData */ + List buildDataList = new ArrayList<>(); + buildDataList.add(buildData); - /* List of build data that will be returned by the mocked BuildData */ - List buildDataList = new ArrayList<>(); - buildDataList.add(buildData); + /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ + AbstractBuild build = Mockito.mock(AbstractBuild.class); + Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); - /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ - AbstractBuild build = Mockito.mock(AbstractBuild.class); - Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); + final FreeStyleProject project = setupProject("*/*", false); + GitSCM scm = (GitSCM) project.getScm(); + scm.getExtensions().add(new LocalBranch("")); - final FreeStyleProject project = setupProject("*/*", false); - GitSCM scm = (GitSCM) project.getScm(); - scm.getExtensions().add(new LocalBranch("")); + EnvVars env = new EnvVars(); + scm.buildEnvVars(build, env); // NPE here before fix applied - EnvVars env = new EnvVars(); - scm.buildEnvVars(build, env); // NPE here before fix applied - - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); + assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); - /* Verify mocks were called as expected */ - verify(buildData, times(1)).getLastBuiltRevision(); - verify(buildData, times(1)).hasBeenReferenced(anyString()); - verify(build, times(1)).getActions(BuildData.class); + /* Verify mocks were called as expected */ + verify(buildData, times(1)).getLastBuiltRevision(); + verify(buildData, times(1)).hasBeenReferenced(anyString()); + verify(build, times(1)).getActions(BuildData.class); } @Test @Deprecated // testing deprecated buildEnvVars public void testBuildEnvVarsLocalBranchNotSet() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); - /* This is the null that causes NPE */ - Branch branch = new Branch("origin/master", sha1); + /* This is the null that causes NPE */ + Branch branch = new Branch("origin/master", sha1); - List branchList = new ArrayList<>(); - branchList.add(branch); + List branchList = new ArrayList<>(); + branchList.add(branch); + + Revision revision = new Revision(sha1, branchList); - Revision revision = new Revision(sha1, branchList); + /* BuildData mock that will use the Revision with null branch name */ + BuildData buildData = Mockito.mock(BuildData.class); + Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); + Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); - /* BuildData mock that will use the Revision with null branch name */ - BuildData buildData = Mockito.mock(BuildData.class); - Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); - Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); + /* List of build data that will be returned by the mocked BuildData */ + List buildDataList = new ArrayList<>(); + buildDataList.add(buildData); - /* List of build data that will be returned by the mocked BuildData */ - List buildDataList = new ArrayList<>(); - buildDataList.add(buildData); + /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ + AbstractBuild build = Mockito.mock(AbstractBuild.class); + Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); - /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ - AbstractBuild build = Mockito.mock(AbstractBuild.class); - Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); + final FreeStyleProject project = setupProject("*/*", false); + GitSCM scm = (GitSCM) project.getScm(); - final FreeStyleProject project = setupProject("*/*", false); - GitSCM scm = (GitSCM) project.getScm(); + EnvVars env = new EnvVars(); + scm.buildEnvVars(build, env); // NPE here before fix applied - EnvVars env = new EnvVars(); - scm.buildEnvVars(build, env); // NPE here before fix applied - - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); + assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertNull("GIT_LOCAL_BRANCH", env.get("GIT_LOCAL_BRANCH")); - /* Verify mocks were called as expected */ - verify(buildData, times(1)).getLastBuiltRevision(); - verify(buildData, times(1)).hasBeenReferenced(anyString()); - verify(build, times(1)).getActions(BuildData.class); + /* Verify mocks were called as expected */ + verify(buildData, times(1)).getLastBuiltRevision(); + verify(buildData, times(1)).hasBeenReferenced(anyString()); + verify(build, times(1)).getActions(BuildData.class); } @Test @@ -2892,7 +3153,8 @@ public void testBuildEnvironmentVariablesMultipleRemotes() throws Exception { GitSCM scm = new GitSCM( userRemoteConfigs, Collections.singletonList(new BranchSpec(branch.getName())), - null, null, + null, + null, Collections.emptyList()); project.setScm(scm); @@ -2916,10 +3178,21 @@ public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); - Run run = rule.buildAndAssertSuccess(p); + Run run = rule.buildAndAssertSuccess(p); rule.waitForMessage("Commit message: \"test commit\"", run); } + @Test + public void testCommitMessageIsEnvVar() throws Exception { + String title = "test commit"; + sampleRepo.init(); + sampleRepo.write("file", "v1"); + sampleRepo.git("commit", "--all", "--message", title); + FreeStyleProject p = setupSimpleProject("master"); + Run run = rule.buildAndAssertSuccess(p); + assertEquals("Commit message should be an env var", title, getEnvVars(p).get(GitSCM.GIT_COMMIT_TITLE)); + } + /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for build data consistency. @@ -2930,18 +3203,24 @@ public void testCommitMessageIsPrintedToLogs() throws Exception { * @param git git SCM * @throws Exception on error */ - private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit, - String expectedBranch, int ordinal, GitSCM git) throws Exception { + private void notifyAndCheckBranch( + FreeStyleProject project, ObjectId commit, String expectedBranch, int ordinal, GitSCM git) + throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final BuildData buildData = git.getBuildData(project.getLastBuild()); - final Collection builtBranches = buildData.lastBuild.getRevision().getBranches(); - assertEquals("Commit " + ordinal + " should be built", commit, buildData - .getLastBuiltRevision().getSha1()); + final Collection builtBranches = + buildData.lastBuild.getRevision().getBranches(); + assertEquals( + "Commit " + ordinal + " should be built", + commit, + buildData.getLastBuiltRevision().getSha1()); final String expectedBranchString = "origin/" + expectedBranch; assertFalse("Branches should be detected for the build", builtBranches.isEmpty()); - assertEquals(expectedBranch + " branch should be detected", expectedBranchString, - builtBranches.iterator().next().getName()); + assertEquals( + expectedBranch + " branch should be detected", + expectedBranchString, + builtBranches.iterator().next().getName()); assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH)); } @@ -2957,14 +3236,16 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); - final String notificationPath = rule.getURL().toExternalForm() - + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; + final String notificationPath = rule.getURL().toExternalForm() + "git/notifyCommit?url=" + + testRepo.gitDir.toString() + "&sha1=" + commit1; final URL notifyUrl = new URL(notificationPath); String notifyContent; try (final InputStream is = notifyUrl.openStream()) { notifyContent = new String(is.readAllBytes(), StandardCharsets.UTF_8); } - assertThat(notifyContent, containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString())); + assertThat( + notifyContent, + containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString())); if ((project.getLastBuild().getNumber() == initialBuildNumber) && (rule.jenkins.getQueue().isEmpty())) { @@ -2982,8 +3263,10 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws } private void setupJGit(GitSCM git) { - git.gitTool="jgit"; - rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.emptyList())); + git.gitTool = "jgit"; + rule.jenkins + .getDescriptorByType(GitTool.DescriptorImpl.class) + .setInstallations(new JGitTool(Collections.emptyList())); } /** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */ @@ -3008,7 +3291,7 @@ private boolean cleanupIsUnreliable() { /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; + return java.io.File.pathSeparatorChar == ';'; } private StandardCredentials createCredential(CredentialsScope scope, String id) { diff --git a/src/test/java/hudson/plugins/git/GitSCMUnitTest.java b/src/test/java/hudson/plugins/git/GitSCMUnitTest.java index c94836e3a4..74a93c31dd 100644 --- a/src/test/java/hudson/plugins/git/GitSCMUnitTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMUnitTest.java @@ -23,9 +23,15 @@ */ package hudson.plugins.git; +import static hudson.plugins.git.GitSCM.createRepoList; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import hudson.AbortException; import hudson.EnvVars; -import static hudson.plugins.git.GitSCM.createRepoList; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; import hudson.plugins.git.opt.PreBuildMergeOptions; @@ -41,12 +47,7 @@ import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import org.jvnet.hudson.test.Issue; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; public class GitSCMUnitTest { @@ -54,8 +55,7 @@ public class GitSCMUnitTest { private final GitSCM gitSCM = new GitSCM(gitDir); private final String repoURL = "https://github.com/jenkinsci/git-plugin"; - public GitSCMUnitTest() { - } + public GitSCMUnitTest() {} @Test @Deprecated @@ -87,13 +87,22 @@ public void testCreateRepoList() { assertUserRemoteConfigListEquals(remoteConfigList, expectedRemoteConfigList); } - private void assertUserRemoteConfigListEquals(List remoteConfigList, List expectedRemoteConfigList) { + private void assertUserRemoteConfigListEquals( + List remoteConfigList, List expectedRemoteConfigList) { /* UserRemoteConfig lacks an equals method - ugh */ assertThat(remoteConfigList.toString(), is(expectedRemoteConfigList.toString())); - assertThat(remoteConfigList.get(0).getUrl(), is(expectedRemoteConfigList.get(0).getUrl())); - assertThat(remoteConfigList.get(0).getName(), is(expectedRemoteConfigList.get(0).getName())); - assertThat(remoteConfigList.get(0).getRefspec(), is(expectedRemoteConfigList.get(0).getRefspec())); - assertThat(remoteConfigList.get(0).getCredentialsId(), is(expectedRemoteConfigList.get(0).getCredentialsId())); + assertThat( + remoteConfigList.get(0).getUrl(), + is(expectedRemoteConfigList.get(0).getUrl())); + assertThat( + remoteConfigList.get(0).getName(), + is(expectedRemoteConfigList.get(0).getName())); + assertThat( + remoteConfigList.get(0).getRefspec(), + is(expectedRemoteConfigList.get(0).getRefspec())); + assertThat( + remoteConfigList.get(0).getCredentialsId(), + is(expectedRemoteConfigList.get(0).getCredentialsId())); assertThat(remoteConfigList.size(), is(1)); } @@ -222,36 +231,48 @@ public void testRequiresWorkspaceForPolling() { @Test public void testRequiresWorkspaceForPollingSingleBranch() { /* Force single-branch use case */ - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertFalse(bigGitSCM.requiresWorkspaceForPolling()); } @Test public void testRequiresWorkspaceForPollingSingleBranchWithRemoteName() { /* Force single-branch use case */ - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("origin/master")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertFalse(bigGitSCM.requiresWorkspaceForPolling()); } @Test public void testRequiresWorkspaceForPollingSingleBranchWithWildcardRemoteName() { /* Force single-branch use case */ - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("*/master")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertFalse(bigGitSCM.requiresWorkspaceForPolling()); } @Test public void testRequiresWorkspaceForPollingSingleBranchWithWildcardSuffix() { /* Force single-branch use case */ - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master*")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertTrue(bigGitSCM.requiresWorkspaceForPolling()); } @@ -261,9 +282,7 @@ public void testRequiresWorkspaceForPollingMultiBranch() { List branches = new ArrayList<>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec("origin/master")); - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), - branches, - null, null, Collections.emptyList()); + GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), branches, null, null, Collections.emptyList()); assertTrue(bigGitSCM.requiresWorkspaceForPolling()); } @@ -272,9 +291,12 @@ public void testRequiresWorkspaceForPollingEmptyBranchName() { /* Multi-branch use case */ EnvVars env = new EnvVars(); env.put("A", ""); - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("${A}")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertFalse(bigGitSCM.requiresWorkspaceForPolling(env)); } @@ -292,9 +314,12 @@ public void testIsDoGenerateSubmoduleConfigurations() { @Test @Deprecated public void testIsDoGenerateSubmoduleConfigurationsTrue() { - GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM bigGitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); assertFalse(bigGitSCM.isDoGenerateSubmoduleConfigurations()); } @@ -308,7 +333,9 @@ public void testGetBranches() { private void assertBranchSpecListEquals(List branchList, List expectedBranchList) { int expectedIndex = 0; for (BranchSpec branchSpec : branchList) { - assertThat(branchSpec.getName(), is(expectedBranchList.get(expectedIndex++).getName())); + assertThat( + branchSpec.getName(), + is(expectedBranchList.get(expectedIndex++).getName())); } assertThat(branchList.size(), is(expectedBranchList.size())); } @@ -344,9 +371,12 @@ public void testSetDoGenerateSubmoduleConfigurations() { @Issue("JENKINS-68562") @Test public void testAbortIfSourceIsLocal() { - GitSCM gitSCM = new GitSCM(createRepoList(repoURL, null), + GitSCM gitSCM = new GitSCM( + createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); try { gitSCM.abortIfSourceIsLocal(); } catch (AbortException e) { diff --git a/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java b/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java index 2f64477128..81d0f423fd 100644 --- a/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java @@ -1,21 +1,19 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; - import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; - import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - /** * Check that no crumb is required for successful calls to notifyCommit. */ @@ -60,7 +58,8 @@ public GitStatusCrumbExclusionTest() throws Exception { branchArgument = "branches=origin/some-branch-name"; branchArgumentBytes = branchArgument.getBytes(StandardCharsets.UTF_8); - notifyCommitApiToken = "token=" + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + notifyCommitApiToken = "token=" + + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); notifyCommitApiTokenBytes = notifyCommitApiToken.getBytes(StandardCharsets.UTF_8); } @@ -256,7 +255,8 @@ public void testGETValidPathMandatoryArgument() throws Exception { @Test public void testGETValidPathMandatoryAndOptionalArgument() throws Exception { - URL getURL = new URL(notifyCommitURL + "?" + urlArgument + separator + branchArgument + separator + notifyCommitApiToken); + URL getURL = new URL( + notifyCommitURL + "?" + urlArgument + separator + branchArgument + separator + notifyCommitApiToken); HttpURLConnection connectionGET = (HttpURLConnection) getURL.openConnection(); connectionGET.setRequestMethod("GET"); connectionGET.connect(); diff --git a/src/test/java/hudson/plugins/git/GitStatusTest.java b/src/test/java/hudson/plugins/git/GitStatusTest.java index 1b078b0069..3739d32519 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTest.java @@ -1,5 +1,9 @@ package hudson.plugins.git; +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import hudson.model.Action; import hudson.model.Cause; import hudson.model.FreeStyleBuild; @@ -19,25 +23,20 @@ import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.*; -import org.eclipse.jgit.transport.URIish; import java.util.logging.Level; import java.util.logging.Logger; -import org.kohsuke.stapler.HttpResponses; -import org.mockito.Mockito; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import static org.junit.Assert.*; +import javax.servlet.http.HttpServletRequest; +import org.eclipse.jgit.transport.URIish; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.WithoutJenkins; - -import javax.servlet.http.HttpServletRequest; import org.kohsuke.stapler.HttpResponse; +import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; +import org.mockito.Mockito; public class GitStatusTest extends AbstractGitProject { @@ -60,7 +59,8 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (jenkins.jenkins != null) { - this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -103,7 +103,8 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); jenkins.waitForCompletion(run); } catch (InterruptedException ex) { - Logger.getLogger(GitStatusTest.class.getName()).log(Level.SEVERE, "Interrupted waiting for GitStatusTest job", ex); + Logger.getLogger(GitStatusTest.class.getName()) + .log(Level.SEVERE, "Interrupted waiting for GitStatusTest job", ex); } }); } @@ -195,7 +196,8 @@ public void testDoNotifyCommitWithTwoBranches() throws Exception { SCMTrigger bTopicTrigger = setupProjectWithTrigger("b", "topic", false); SCMTrigger bFeatureTrigger = setupProjectWithTrigger("b", "feature/def", false); - this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master,topic,feature/def", null, notifyCommitApiToken); + this.gitStatus.doNotifyCommit( + requestWithNoParameter, "a", "master,topic,feature/def", null, notifyCommitApiToken); Mockito.verify(aMasterTrigger).run(); Mockito.verify(aTopicTrigger).run(); Mockito.verify(aFeatureTrigger).run(); @@ -290,7 +292,8 @@ public void testDoNotifyCommitWithTwoBranchesAndAdditionalUnsafeParameter() thro doNotifyCommitWithTwoBranchesAndAdditionalParameter(false, "does,not,include,param"); } - private void doNotifyCommitWithTwoBranchesAndAdditionalParameter(final boolean allowed, String safeParameters) throws Exception { + private void doNotifyCommitWithTwoBranchesAndAdditionalParameter(final boolean allowed, String safeParameters) + throws Exception { if (allowed) { GitStatus.setAllowNotifyCommitParameters(true); } @@ -327,7 +330,8 @@ private void doNotifyCommitWithTwoBranchesAndAdditionalParameter(final boolean a @Test public void testDoNotifyCommitBranchWithRegex() throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", ":[^/]*/awesome-feature", false); - this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); + this.gitStatus.doNotifyCommit( + requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } @@ -335,25 +339,29 @@ public void testDoNotifyCommitBranchWithRegex() throws Exception { @Test public void testDoNotifyCommitBranchWithWildcard() throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", "origin/feature/*", false); - this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); + this.gitStatus.doNotifyCommit( + requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } private void assertAdditionalParameters(Collection actions) { - for (Action action: actions) { + for (Action action : actions) { if (action instanceof ParametersAction) { final List parameters = ((ParametersAction) action).getParameters(); assertEquals(2, parameters.size()); for (ParameterValue value : parameters) { - assertTrue((value.getName().equals("paramKey1") && value.getValue().equals("paramValue1")) - || (value.getName().equals("paramKey2") && value.getValue().equals("paramValue2"))); + assertTrue((value.getName().equals("paramKey1") + && value.getValue().equals("paramValue1")) + || (value.getName().equals("paramKey2") + && value.getValue().equals("paramValue2"))); } } } } - private SCMTrigger setupProjectWithTrigger(String url, String branchString, boolean ignoreNotifyCommit) throws Exception { + private SCMTrigger setupProjectWithTrigger(String url, String branchString, boolean ignoreNotifyCommit) + throws Exception { SCMTrigger trigger = Mockito.mock(SCMTrigger.class); Mockito.doReturn(ignoreNotifyCommit).when(trigger).isIgnorePostCommitHooks(); setupProject(url, branchString, trigger); @@ -365,16 +373,19 @@ private void setupProject(String url, String branchString, SCMTrigger trigger) t GitSCM git = new GitSCM( Collections.singletonList(new UserRemoteConfig(url, null, null, null)), Collections.singletonList(new BranchSpec(branchString)), - null, null, + null, + null, Collections.emptyList()); project.setScm(git); - if (trigger != null) project.addTrigger(trigger); + if (trigger != null) { + project.addTrigger(trigger); + } } @WithoutJenkins @Test public void testLooselyMatches() throws URISyntaxException { - String[] equivalentRepoURLs = new String[]{ + String[] equivalentRepoURLs = new String[] { "https://example.com/jenkinsci/git-plugin", "https://example.com/jenkinsci/git-plugin/", "https://example.com/jenkinsci/git-plugin.git", @@ -404,7 +415,9 @@ public void testLooselyMatches() throws URISyntaxException { URIish badURLHostname = new URIish(equivalentRepoURLs[0].replace("example.com", "bitbucket.org")); for (URIish lhs : uris) { - assertFalse(lhs + " matches trailing slashes " + badURLTrailingSlashes, GitStatus.looselyMatches(lhs, badURLTrailingSlashes)); + assertFalse( + lhs + " matches trailing slashes " + badURLTrailingSlashes, + GitStatus.looselyMatches(lhs, badURLTrailingSlashes)); assertFalse(lhs + " matches bad hostname " + badURLHostname, GitStatus.looselyMatches(lhs, badURLHostname)); for (URIish rhs : uris) { assertTrue(lhs + " and " + rhs + " didn't match", GitStatus.looselyMatches(lhs, rhs)); @@ -418,7 +431,8 @@ private FreeStyleProject setupNotifyProject() throws Exception { GitSCM git = new GitSCM( Collections.singletonList(new UserRemoteConfig(repoURL, null, null, null)), Collections.singletonList(new BranchSpec(branch)), - null, null, + null, + null, Collections.emptyList()); project.setScm(git); project.addTrigger(new SCMTrigger("")); // Required for GitStatus to see polling request @@ -444,12 +458,11 @@ private Map setupParameterMap(String extraValue) { } @Test - public void testDoNotifyCommit() throws Exception { /* No parameters */ + public void testDoNotifyCommit() throws Exception { + /* No parameters */ setupNotifyProject(); this.gitStatus.doNotifyCommit(requestWithNoParameter, repoURL, branch, sha1, notifyCommitApiToken); - assertEquals("URL: " + repoURL - + " SHA1: " + sha1 - + " Branches: " + branch, this.gitStatus.toString()); + assertEquals("URL: " + repoURL + " SHA1: " + sha1 + " Branches: " + branch, this.gitStatus.toString()); } @Test @@ -472,7 +485,8 @@ public void testDoNotifyCommitWithExtraUnsafeParameter() throws Exception { doNotifyCommitWithExtraParameterAllowed(false, "something,is,not,here"); } - private void doNotifyCommitWithExtraParameterAllowed(final boolean allowed, String safeParameters) throws Exception { + private void doNotifyCommitWithExtraParameterAllowed(final boolean allowed, String safeParameters) + throws Exception { if (allowed) { GitStatus.setAllowNotifyCommitParameters(true); } @@ -502,9 +516,7 @@ public void testDoNotifyCommitWithNullValueExtraParameter() throws Exception { setupNotifyProject(); when(requestWithParameter.getParameterMap()).thenReturn(setupParameterMap(null)); this.gitStatus.doNotifyCommit(requestWithParameter, repoURL, branch, sha1, notifyCommitApiToken); - assertEquals("URL: " + repoURL - + " SHA1: " + sha1 - + " Branches: " + branch, this.gitStatus.toString()); + assertEquals("URL: " + repoURL + " SHA1: " + sha1 + " Branches: " + branch, this.gitStatus.toString()); } @Test @@ -529,7 +541,7 @@ public void testDoNotifyCommitWithDefaultUnsafeParameterC() throws Exception { @Test public void testDoNotifyCommitWithDefaultUnsafeParameterExtra() throws Exception { - doNotifyCommitWithDefaultParameter(false, "A,B,C"); + doNotifyCommitWithDefaultParameter(false, "A,B,C"); } private void doNotifyCommitWithDefaultParameter(final boolean allowed, String safeParameters) throws Exception { @@ -555,14 +567,12 @@ private void doNotifyCommitWithDefaultParameter(final boolean allowed, String sa project.addProperty(new ParametersDefinitionProperty( new StringParameterDefinition("A", "aaa"), new StringParameterDefinition("C", "ccc"), - new StringParameterDefinition("B", "$A$C") - )); - final CommandInterpreter script = isWindows() - ? new BatchFile("echo %A% %B% %C%") - : new Shell("echo $A $B $C"); + new StringParameterDefinition("B", "$A$C"))); + final CommandInterpreter script = isWindows() ? new BatchFile("echo %A% %B% %C%") : new Shell("echo $A $B $C"); project.getBuildersList().add(script); - FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause()).get(); + FreeStyleBuild build = + project.scheduleBuild2(0, new Cause.UserIdCause()).get(); jenkins.waitForMessage("aaa aaaccc ccc", build); @@ -589,7 +599,8 @@ private boolean runUnreliableTests() { if (jobUrl == null) { return true; // Always run tests when not inside a CI environment } - return !jobUrl.contains("ci.jenkins.io"); // Skip some tests on ci.jenkins.io, windows cleanup is unreliable on those machines + return !jobUrl.contains( + "ci.jenkins.io"); // Skip some tests on ci.jenkins.io, windows cleanup is unreliable on those machines } /** @@ -608,7 +619,8 @@ public void testDoNotifyCommitTriggeredHeadersLimited() throws Exception { projectTriggers[i] = setupProjectWithTrigger("a", "master", false); } - HttpResponse rsp = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", null, notifyCommitApiToken); + HttpResponse rsp = + this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", null, notifyCommitApiToken); // Up to 10 "Triggered" headers + 1 extra warning are returned. StaplerRequest sReq = mock(StaplerRequest.class); @@ -632,12 +644,13 @@ public void testDoNotifyCommitWithWrongSha1Content() throws Exception { String content = ""; - HttpResponse rsp = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", content, notifyCommitApiToken); + HttpResponse rsp = + this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", content, notifyCommitApiToken); HttpResponses.HttpResponseException responseException = ((HttpResponses.HttpResponseException) rsp); - assertEquals(IllegalArgumentException.class, responseException.getCause().getClass()); + assertEquals( + IllegalArgumentException.class, responseException.getCause().getClass()); assertEquals("Illegal SHA1", responseException.getCause().getMessage()); - } @Test @@ -661,7 +674,8 @@ public void testDoNotifyCommitWithInvalidApiToken() throws Exception { setupProjectWithTrigger("a", "master", false); StaplerResponse res = mock(StaplerResponse.class); - HttpResponse httpResponse = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", null, "invalid"); + HttpResponse httpResponse = + this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", null, "invalid"); httpResponse.generateResponse(null, res, null); Mockito.verify(res).sendError(403, "Invalid access token"); @@ -688,7 +702,10 @@ public void testDoNotifyCommitWithAllowModeRandomValue() throws Exception { HttpResponse httpResponse = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", null, null); httpResponse.generateResponse(null, res, null); - Mockito.verify(res).sendError(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."); + Mockito.verify(res) + .sendError( + 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."); } @Test @@ -701,7 +718,10 @@ public void testDoNotifyCommitWithSha1AndAllowModePoll() throws Exception { HttpResponse httpResponse = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", sha1, null); httpResponse.generateResponse(null, res, null); - Mockito.verify(res).sendError(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."); + Mockito.verify(res) + .sendError( + 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."); } @Test @@ -711,7 +731,8 @@ public void testDoNotifyCommitWithSha1AndAllowModePollWithInvalidToken() throws setupProjectWithTrigger("a", "master", false); StaplerResponse res = mock(StaplerResponse.class); - HttpResponse httpResponse = this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", sha1, "invalid"); + HttpResponse httpResponse = + this.gitStatus.doNotifyCommit(requestWithNoParameter, "a", "master", sha1, "invalid"); httpResponse.generateResponse(null, res, null); Mockito.verify(res).sendError(403, "Invalid access token"); diff --git a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java index 09a4cd05e0..907d75a0a7 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git; +import static org.mockito.Mockito.mock; + import hudson.model.FreeStyleProject; import hudson.model.Run; import hudson.model.View; @@ -9,10 +11,7 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import org.mockito.Mockito; -import static org.mockito.Mockito.mock; - -import static org.junit.Assert.*; +import javax.servlet.http.HttpServletRequest; import org.junit.After; import org.junit.Before; import org.junit.experimental.theories.DataPoints; @@ -20,8 +19,7 @@ import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; - -import javax.servlet.http.HttpServletRequest; +import org.mockito.Mockito; @RunWith(Theories.class) public class GitStatusTheoriesTest extends AbstractGitProject { @@ -45,7 +43,8 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (jenkins.jenkins != null) { - this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -88,30 +87,29 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTheoriesTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); jenkins.waitForCompletion(run); } catch (InterruptedException ex) { - Logger.getLogger(GitStatusTheoriesTest.class.getName()).log(Level.SEVERE, "Interrupted waiting for GitStatusTheoriesTest job", ex); + Logger.getLogger(GitStatusTheoriesTest.class.getName()) + .log(Level.SEVERE, "Interrupted waiting for GitStatusTheoriesTest job", ex); } }); } @DataPoints("branchSpecPrefixes") - public static final String[] BRANCH_SPEC_PREFIXES = new String[] { - "", - "refs/remotes/", - "refs/heads/", - "origin/", - "remotes/origin/" - }; + public static final String[] BRANCH_SPEC_PREFIXES = + new String[] {"", "refs/remotes/", "refs/heads/", "origin/", "remotes/origin/"}; @Theory - public void testDoNotifyCommitBranchWithSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + public void testDoNotifyCommitBranchWithSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) + throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "feature/awesome-feature", false); - this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); + this.gitStatus.doNotifyCommit( + requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } @Theory - public void testDoNotifyCommitBranchWithoutSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + public void testDoNotifyCommitBranchWithoutSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) + throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "awesome-feature", false); this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "awesome-feature", null, notifyCommitApiToken); @@ -119,14 +117,17 @@ public void testDoNotifyCommitBranchWithoutSlash(@FromDataPoints("branchSpecPref } @Theory - public void testDoNotifyCommitBranchByBranchRef(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + public void testDoNotifyCommitBranchByBranchRef(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) + throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "awesome-feature", false); - this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "refs/heads/awesome-feature", null, notifyCommitApiToken); + this.gitStatus.doNotifyCommit( + requestWithNoParameter, "remote", "refs/heads/awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } - private SCMTrigger setupProjectWithTrigger(String url, String branchString, boolean ignoreNotifyCommit) throws Exception { + private SCMTrigger setupProjectWithTrigger(String url, String branchString, boolean ignoreNotifyCommit) + throws Exception { SCMTrigger trigger = Mockito.mock(SCMTrigger.class); Mockito.doReturn(ignoreNotifyCommit).when(trigger).isIgnorePostCommitHooks(); setupProject(url, branchString, trigger); @@ -138,10 +139,13 @@ private void setupProject(String url, String branchString, SCMTrigger trigger) t GitSCM git = new GitSCM( Collections.singletonList(new UserRemoteConfig(url, null, null, null)), Collections.singletonList(new BranchSpec(branchString)), - null, null, + null, + null, Collections.emptyList()); project.setScm(git); - if (trigger != null) project.addTrigger(trigger); + if (trigger != null) { + project.addTrigger(trigger); + } } /** diff --git a/src/test/java/hudson/plugins/git/GitTagActionTest.java b/src/test/java/hudson/plugins/git/GitTagActionTest.java index 251b246fc4..d782322064 100644 --- a/src/test/java/hudson/plugins/git/GitTagActionTest.java +++ b/src/test/java/hudson/plugins/git/GitTagActionTest.java @@ -1,5 +1,20 @@ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import hudson.EnvVars; +import hudson.FilePath; +import hudson.model.Descriptor; +import hudson.model.FreeStyleProject; +import hudson.model.Run; +import hudson.model.TaskListener; +import hudson.plugins.git.GitSCM.DescriptorImpl; +import hudson.plugins.git.extensions.impl.LocalBranch; import java.io.File; import java.io.StringWriter; import java.time.LocalDateTime; @@ -13,30 +28,10 @@ import java.util.Map; import java.util.Random; import java.util.Set; - -import hudson.EnvVars; -import hudson.FilePath; -import hudson.model.Descriptor; -import hudson.model.FreeStyleProject; -import hudson.model.Run; -import hudson.model.TaskListener; -import hudson.plugins.git.GitSCM.DescriptorImpl; -import hudson.plugins.git.extensions.impl.LocalBranch; - +import jenkins.plugins.git.GitSampleRepoRule; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; - -import jenkins.plugins.git.GitSampleRepoRule; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.gargoylesoftware.htmlunit.html.HtmlForm; -import com.gargoylesoftware.htmlunit.html.HtmlPage; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -74,8 +69,7 @@ public class GitTagActionTest { @ClassRule public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - public GitTagActionTest() { - } + public GitTagActionTest() {} private static FreeStyleProject p; private static GitClient workspaceGitClient = null; @@ -216,7 +210,9 @@ private static GitTagAction createTagAction(String message) throws Exception { assertThat(stringWriter.toString(), containsString(commitMessage)); /* Fail if master branch is not defined in the workspace */ - assertThat(workspaceGitClient.getRemoteUrl("origin"), is(sampleRepo.fileUrl().replace("file:/", "file:///"))); + assertThat( + workspaceGitClient.getRemoteUrl("origin"), + is(sampleRepo.fileUrl().replace("file:/", "file:///"))); Set branches = workspaceGitClient.getBranches(); if (branches.isEmpty()) { /* Should not be required since the LocalBranch extension was enabled */ diff --git a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java index 8fe98e3bf4..3a4ba43f4d 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java @@ -3,19 +3,15 @@ import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.impl.EnforceGitClient; -public class JGitSCMTriggerLocalPollTest extends SCMTriggerTest -{ - +public class JGitSCMTriggerLocalPollTest extends SCMTriggerTest { + @Override - protected EnforceGitClient getGitClient() - { + protected EnforceGitClient getGitClient() { return new EnforceGitClient().set(GitClientType.JGIT); } - + @Override - protected boolean isDisableRemotePoll() - { + protected boolean isDisableRemotePoll() { return true; } - } diff --git a/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java b/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java index b8f8d6108a..a2c93ace55 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java @@ -9,18 +9,14 @@ * The isChangeExpected() method adjusts the tests to the difference between * local and remote polling. */ -public class JGitSCMTriggerRemotePollTest extends SCMTriggerTest -{ +public class JGitSCMTriggerRemotePollTest extends SCMTriggerTest { @Override - protected EnforceGitClient getGitClient() - { + protected EnforceGitClient getGitClient() { return new EnforceGitClient().set(GitClientType.JGIT); } - + @Override - protected boolean isDisableRemotePoll() - { + protected boolean isDisableRemotePoll() { return false; } - } diff --git a/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java b/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java index 545c4fecc7..0d9390b036 100644 --- a/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java +++ b/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java @@ -1,18 +1,17 @@ package hudson.plugins.git; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class RevisionParameterActionRemoteUrlTest { @Test @@ -47,7 +46,8 @@ public void multipleRemoteURLsSetAndOneMatches() throws Exception { URIish remoteURL1 = new URIish("https://github.com/jenkinsci/multiple-scms-plugin.git"); URIish remoteURL2 = new URIish("https://github.com/jenkinsci/git-plugin.git"); - assertTrue("should return true when any remote matches", target.canOriginateFrom(remotes(remoteURL1, remoteURL2))); + assertTrue( + "should return true when any remote matches", target.canOriginateFrom(remotes(remoteURL1, remoteURL2))); } private List remotes(URIish... remoteURLs) { diff --git a/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java b/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java index b0e2628163..43604b7624 100644 --- a/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java +++ b/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java @@ -23,14 +23,14 @@ */ package hudson.plugins.git; +import static org.junit.Assert.*; + import hudson.model.Cause; -import hudson.model.FreeStyleProject; import hudson.model.FreeStyleBuild; +import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.plugins.git.util.BuildData; - import java.util.Collections; -import static org.junit.Assert.*; import org.junit.Test; /** @@ -57,21 +57,25 @@ public void testProvidingRevision() throws Exception { commitNewFile(commitFile2); // create second build and set revision parameter using r1 - FreeStyleBuild b2 = p1.scheduleBuild2(0, new Cause.UserIdCause(), - Collections.singletonList(new RevisionParameterAction(r1))).get(); + FreeStyleBuild b2 = p1.scheduleBuild2( + 0, new Cause.UserIdCause(), Collections.singletonList(new RevisionParameterAction(r1))) + .get(); // Check revision built for b2 matches the r1 revision - assertEquals(b2.getAction(BuildData.class) - .getLastBuiltRevision().getSha1String(), r1.getSha1String()); - assertEquals(b2.getAction(BuildData.class) - .getLastBuiltRevision().getBranches().iterator().next() - .getName(), r1.getBranches().iterator().next().getName()); + assertEquals(b2.getAction(BuildData.class).getLastBuiltRevision().getSha1String(), r1.getSha1String()); + assertEquals( + b2.getAction(BuildData.class) + .getLastBuiltRevision() + .getBranches() + .iterator() + .next() + .getName(), + r1.getBranches().iterator().next().getName()); // create a third build FreeStyleBuild b3 = build(p1, Result.SUCCESS, commitFile2); // Check revision built for b3 does not match r1 revision - assertNotEquals(b3.getAction(BuildData.class) - .getLastBuiltRevision().getSha1String(), r1.getSha1String()); + assertNotEquals(b3.getAction(BuildData.class).getLastBuiltRevision().getSha1String(), r1.getSha1String()); } } diff --git a/src/test/java/hudson/plugins/git/SCMTriggerTest.java b/src/test/java/hudson/plugins/git/SCMTriggerTest.java index ae3dad44e4..d5e1276bce 100644 --- a/src/test/java/hudson/plugins/git/SCMTriggerTest.java +++ b/src/test/java/hudson/plugins/git/SCMTriggerTest.java @@ -1,15 +1,16 @@ package hudson.plugins.git; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.*; + import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; +import hudson.model.TaskListener; import hudson.plugins.git.extensions.impl.EnforceGitClient; import hudson.scm.PollingResult; import hudson.triggers.SCMTrigger; import hudson.util.RunList; -import hudson.model.TaskListener; import hudson.util.StreamTaskListener; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -26,16 +27,13 @@ import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; - -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; -public abstract class SCMTriggerTest extends AbstractGitProject -{ +public abstract class SCMTriggerTest extends AbstractGitProject { private ZipFile namespaceRepoZip; private Properties namespaceRepoCommits; private ExecutorService singleThreadExecutor; @@ -51,78 +49,96 @@ public void setUp() throws Exception { namespaceRepoCommits = parseLsRemote(new File("src/test/resources/namespaceBranchRepo.ls-remote")); singleThreadExecutor = Executors.newSingleThreadExecutor(); } - + protected abstract EnforceGitClient getGitClient(); - + protected abstract boolean isDisableRemotePoll(); @Test public void testNamespaces_with_refsHeadsMaster() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/heads/master", - namespaceRepoCommits.getProperty("refs/heads/master"), - "origin/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/heads/master", + namespaceRepoCommits.getProperty("refs/heads/master"), + "origin/master"); } // @Test public void testNamespaces_with_remotesOriginMaster() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "remotes/origin/master", - namespaceRepoCommits.getProperty("refs/heads/master"), - "origin/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "remotes/origin/master", + namespaceRepoCommits.getProperty("refs/heads/master"), + "origin/master"); } // @Test public void testNamespaces_with_refsRemotesOriginMaster() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/remotes/origin/master", - namespaceRepoCommits.getProperty("refs/heads/master"), - "origin/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/remotes/origin/master", + namespaceRepoCommits.getProperty("refs/heads/master"), + "origin/master"); } // @Test public void testNamespaces_with_master() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "master", - namespaceRepoCommits.getProperty("refs/heads/master"), - "origin/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "master", + namespaceRepoCommits.getProperty("refs/heads/master"), + "origin/master"); } // @Test public void testNamespaces_with_namespace1Master() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "a_tests/b_namespace1/master", - namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"), - "origin/a_tests/b_namespace1/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "a_tests/b_namespace1/master", + namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"), + "origin/a_tests/b_namespace1/master"); } // @Test public void testNamespaces_with_refsHeadsNamespace1Master() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/heads/a_tests/b_namespace1/master", - namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"), - "origin/a_tests/b_namespace1/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/heads/a_tests/b_namespace1/master", + namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace1/master"), + "origin/a_tests/b_namespace1/master"); } // @Test public void testNamespaces_with_namespace2Master() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "a_tests/b_namespace2/master", - namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"), - "origin/a_tests/b_namespace2/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "a_tests/b_namespace2/master", + namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"), + "origin/a_tests/b_namespace2/master"); } // @Test public void testNamespaces_with_refsHeadsNamespace2Master() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/heads/a_tests/b_namespace2/master", - namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"), - "origin/a_tests/b_namespace2/master"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/heads/a_tests/b_namespace2/master", + namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace2/master"), + "origin/a_tests/b_namespace2/master"); } // @Test public void testNamespaces_with_namespace3_feature3_sha1() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), "detached"); @@ -130,7 +146,9 @@ public void testNamespaces_with_namespace3_feature3_sha1() throws Exception { // @Test public void testNamespaces_with_namespace3_feature3_branchName() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, "a_tests/b_namespace3/feature3", namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), "origin/a_tests/b_namespace3/feature3"); @@ -138,7 +156,9 @@ public void testNamespaces_with_namespace3_feature3_branchName() throws Exceptio // @Test public void testNamespaces_with_refsHeadsNamespace3_feature3_sha1() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), "detached"); @@ -146,7 +166,9 @@ public void testNamespaces_with_refsHeadsNamespace3_feature3_sha1() throws Excep // @Test public void testNamespaces_with_refsHeadsNamespace3_feature3_branchName() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, "refs/heads/a_tests/b_namespace3/feature3", namespaceRepoCommits.getProperty("refs/heads/a_tests/b_namespace3/feature3"), "origin/a_tests/b_namespace3/feature3"); @@ -154,39 +176,49 @@ public void testNamespaces_with_refsHeadsNamespace3_feature3_branchName() throws // @Test public void testTags_with_TagA() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "TagA", - namespaceRepoCommits.getProperty("refs/tags/TagA"), - "TagA"); //TODO: What do we expect!? + check( + namespaceRepoZip, + namespaceRepoCommits, + "TagA", + namespaceRepoCommits.getProperty("refs/tags/TagA"), + "TagA"); // TODO: What do we expect!? } // @Test public void testTags_with_TagBAnnotated() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "TagBAnnotated", - namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"), - "TagBAnnotated"); //TODO: What do we expect!? + check( + namespaceRepoZip, + namespaceRepoCommits, + "TagBAnnotated", + namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"), + "TagBAnnotated"); // TODO: What do we expect!? } // @Test public void testTags_with_refsTagsTagA() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/tags/TagA", - namespaceRepoCommits.getProperty("refs/tags/TagA"), - "refs/tags/TagA"); //TODO: What do we expect!? + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/tags/TagA", + namespaceRepoCommits.getProperty("refs/tags/TagA"), + "refs/tags/TagA"); // TODO: What do we expect!? } // @Test public void testTags_with_refsTagsTagBAnnotated() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - "refs/tags/TagBAnnotated", - namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"), - "refs/tags/TagBAnnotated"); + check( + namespaceRepoZip, + namespaceRepoCommits, + "refs/tags/TagBAnnotated", + namespaceRepoCommits.getProperty("refs/tags/TagBAnnotated^{}"), + "refs/tags/TagBAnnotated"); } // @Test public void testCommitAsBranchSpec_feature4_sha1() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"), namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"), "detached"); @@ -194,7 +226,9 @@ public void testCommitAsBranchSpec_feature4_sha1() throws Exception { // @Test public void testCommitAsBranchSpec_feature4_branchName() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, + check( + namespaceRepoZip, + namespaceRepoCommits, "refs/heads/b_namespace3/feature4", namespaceRepoCommits.getProperty("refs/heads/b_namespace3/feature4"), "origin/b_namespace3/feature4"); @@ -202,31 +236,36 @@ public void testCommitAsBranchSpec_feature4_branchName() throws Exception { // @Test public void testCommitAsBranchSpec() throws Exception { - check(namespaceRepoZip, namespaceRepoCommits, - namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"), - namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"), - "detached"); + check( + namespaceRepoZip, + namespaceRepoCommits, + namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"), + namespaceRepoCommits.getProperty("refs/heads/b_namespace3/master"), + "detached"); } @Issue("JENKINS-29796") // @Test public void testMultipleRefspecs() throws Exception { final String remote = prepareRepo(namespaceRepoZip); - final UserRemoteConfig remoteConfig = new UserRemoteConfig(remote, "origin", - "+refs/pull/*:refs/remotes/origin/pr/* +refs/heads/*:refs/remotes/origin/*", null); + final UserRemoteConfig remoteConfig = new UserRemoteConfig( + remote, "origin", "+refs/pull/*:refs/remotes/origin/pr/* +refs/heads/*:refs/remotes/origin/*", null); // First, build the master branch String branchSpec = "refs/heads/master"; - FreeStyleProject project = setupProject(Collections.singletonList(remoteConfig), + FreeStyleProject project = setupProject( + Collections.singletonList(remoteConfig), Collections.singletonList(new BranchSpec(branchSpec)), - //empty scmTriggerSpec, SCMTrigger triggered manually - "", isDisableRemotePoll(), getGitClient()); + // empty scmTriggerSpec, SCMTrigger triggered manually + "", + isDisableRemotePoll(), + getGitClient()); triggerSCMTrigger(project.getTrigger(SCMTrigger.class)); FreeStyleBuild build1 = waitForBuildFinished(project, 1, 60000); assertNotNull("Job has not been triggered", build1); // Now switch request a different branch GitSCM scm = (GitSCM) project.getScm(); - scm.getBranches().set(0,new BranchSpec("b_namespace3/master")); + scm.getBranches().set(0, new BranchSpec("b_namespace3/master")); TaskListener listener = StreamTaskListener.fromStderr(); // Since the new branch has an additional commit, polling should report changes. Without the fix for @@ -235,35 +274,47 @@ public void testMultipleRefspecs() throws Exception { assertTrue("Expected and actual polling results disagree", poll.hasChanges()); } - public void check(ZipFile repoZip, Properties commits, String branchSpec, - String expected_GIT_COMMIT, String expected_GIT_BRANCH) throws Exception { + public void check( + ZipFile repoZip, + Properties commits, + String branchSpec, + String expected_GIT_COMMIT, + String expected_GIT_BRANCH) + throws Exception { String remote = prepareRepo(repoZip); - FreeStyleProject project = setupProject(Collections.singletonList(new UserRemoteConfig(remote, null, null, null)), + FreeStyleProject project = setupProject( + Collections.singletonList(new UserRemoteConfig(remote, null, null, null)), Collections.singletonList(new BranchSpec(branchSpec)), - //empty scmTriggerSpec, SCMTrigger triggered manually - "", isDisableRemotePoll(), getGitClient()); - - //Speedup test - avoid waiting 1 minute + // empty scmTriggerSpec, SCMTrigger triggered manually + "", + isDisableRemotePoll(), + getGitClient()); + + // Speedup test - avoid waiting 1 minute triggerSCMTrigger(project.getTrigger(SCMTrigger.class)); - + FreeStyleBuild build1 = waitForBuildFinished(project, 1, 60000); assertNotNull("Job has not been triggered", build1); TaskListener listener = StreamTaskListener.fromStderr(); PollingResult poll = project.poll(listener); assertFalse("Expected and actual polling results disagree", poll.hasChanges()); - - //Speedup test - avoid waiting 1 minute + + // Speedup test - avoid waiting 1 minute triggerSCMTrigger(project.getTrigger(SCMTrigger.class)).get(20, SECONDS); - + FreeStyleBuild build2 = waitForBuildFinished(project, 2, 2000); assertNull("Found build 2 although no new changes and no multi candidate build", build2); - - assertEquals("Unexpected GIT_COMMIT", - expected_GIT_COMMIT, build1.getEnvironment(null).get("GIT_COMMIT")); - assertEquals("Unexpected GIT_BRANCH", - expected_GIT_BRANCH, build1.getEnvironment(null).get("GIT_BRANCH")); + + assertEquals( + "Unexpected GIT_COMMIT", + expected_GIT_COMMIT, + build1.getEnvironment(null).get("GIT_COMMIT")); + assertEquals( + "Unexpected GIT_BRANCH", + expected_GIT_BRANCH, + build1.getEnvironment(null).get("GIT_BRANCH")); } private String prepareRepo(ZipFile repoZip) throws IOException { @@ -272,9 +323,10 @@ private String prepareRepo(ZipFile repoZip) throws IOException { return tempRemoteDir.getAbsolutePath(); } - private Future triggerSCMTrigger(final SCMTrigger trigger) - { - if(trigger == null) return null; + private Future triggerSCMTrigger(final SCMTrigger trigger) { + if (trigger == null) { + return null; + } Callable callable = () -> { trigger.run(); return null; @@ -283,15 +335,16 @@ private Future triggerSCMTrigger(final SCMTrigger trigger) } private FreeStyleBuild waitForBuildFinished(FreeStyleProject project, int expectedBuildNumber, long timeout) - throws Exception - { + throws Exception { long endTime = System.currentTimeMillis() + timeout; - while(System.currentTimeMillis() < endTime) { + while (System.currentTimeMillis() < endTime) { RunList builds = project.getBuilds(); - for(FreeStyleBuild build : builds) { - if(build.getNumber() == expectedBuildNumber) { - if(build.getResult() != null) return build; - break; //Wait until build finished + for (FreeStyleBuild build : builds) { + if (build.getNumber() == expectedBuildNumber) { + if (build.getResult() != null) { + return build; + } + break; // Wait until build finished } } Thread.sleep(10); @@ -299,14 +352,13 @@ private FreeStyleBuild waitForBuildFinished(FreeStyleProject project, int expect return null; } - private Properties parseLsRemote(File file) throws IOException - { + private Properties parseLsRemote(File file) throws IOException { Properties properties = new Properties(); Pattern pattern = Pattern.compile("([a-f0-9]{40})\\s*(.*)"); - for(String lineO : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) { + for (String lineO : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) { String line = lineO.trim(); Matcher matcher = pattern.matcher(line); - if(matcher.matches()) { + if (matcher.matches()) { properties.setProperty(matcher.group(2), matcher.group(1)); } else { System.err.println("ls-remote pattern does not match '" + line + "'"); @@ -314,17 +366,16 @@ private Properties parseLsRemote(File file) throws IOException } return properties; } - - private void extract(ZipFile zipFile, File outputDir) throws IOException - { + + private void extract(ZipFile zipFile, File outputDir) throws IOException { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - File entryDestination = new File(outputDir, entry.getName()); + File entryDestination = new File(outputDir, entry.getName()); entryDestination.getParentFile().mkdirs(); - if (entry.isDirectory()) + if (entry.isDirectory()) { entryDestination.mkdirs(); - else { + } else { try (InputStream in = zipFile.getInputStream(entry)) { Files.copy(in, entryDestination.toPath()); } @@ -334,6 +385,6 @@ private void extract(ZipFile zipFile, File outputDir) throws IOException /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/hudson/plugins/git/Security2478Test.java b/src/test/java/hudson/plugins/git/Security2478Test.java index 7b56bb52e9..89fcefc11c 100644 --- a/src/test/java/hudson/plugins/git/Security2478Test.java +++ b/src/test/java/hudson/plugins/git/Security2478Test.java @@ -1,6 +1,9 @@ package hudson.plugins.git; +import static org.junit.Assert.assertFalse; + import hudson.model.Result; +import java.io.File; import jenkins.plugins.git.GitSampleRepoRule; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; @@ -12,10 +15,6 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import java.io.File; - -import static org.junit.Assert.assertFalse; - public class Security2478Test { @Rule @@ -24,7 +23,6 @@ public class Security2478Test { @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - @Before public void setUpAllowNonRemoteCheckout() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; @@ -45,13 +43,15 @@ public void checkoutShouldNotAbortWhenLocalSourceAndRunningOnAgent() throws Exce sampleRepo.git("commit", "--all", "--message=test commit"); WorkflowJob p = rule.jenkins.createProject(WorkflowJob.class, "pipeline"); - String script = "node('slave0') {\n" + - " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + - "}"; + String script = "node('slave0') {\n" + + " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" + + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + "}"; p.setDefinition(new CpsFlowDefinition(script, true)); WorkflowRun run = rule.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0)); - rule.assertLogNotContains("aborted because it references a local directory, which may be insecure. " + - "You can allow local checkouts anyway by setting the system property 'hudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT' to true.", run); + rule.assertLogNotContains( + "aborted because it references a local directory, which may be insecure. " + + "You can allow local checkouts anyway by setting the system property 'hudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT' to true.", + run); } @Issue("SECURITY-2478") @@ -63,15 +63,17 @@ public void checkoutShouldAbortWhenSourceIsNonRemoteAndRunningOnController() thr String path = "file://" + workspaceDir + File.separator + "jobName@script" + File.separator + "anyhmachash"; String escapedPath = path.replace("\\", "\\\\"); // for windows - String script = "node {\n" + - " checkout([$class: 'GitSCM', branches: [[name: '*/main']], extensions: [], userRemoteConfigs: [[" + - "url: '" + escapedPath + "'," + - " credentialsId: '']]])\n" + - "}"; + String script = "node {\n" + + " checkout([$class: 'GitSCM', branches: [[name: '*/main']], extensions: [], userRemoteConfigs: [[" + + "url: '" + + escapedPath + "'," + " credentialsId: '']]])\n" + + "}"; p.setDefinition(new CpsFlowDefinition(script, true)); WorkflowRun run = rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0)); - rule.assertLogContains("Checkout of Git remote '" + path + "' " + - "aborted because it references a local directory, which may be insecure. " + - "You can allow local checkouts anyway by setting the system property 'hudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT' to true.", run); + rule.assertLogContains( + "Checkout of Git remote '" + path + "' " + + "aborted because it references a local directory, which may be insecure. " + + "You can allow local checkouts anyway by setting the system property 'hudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT' to true.", + run); } } diff --git a/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java b/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java index a53c348d0a..0dd8e97fea 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.util.StreamTaskListener; @@ -13,7 +15,6 @@ import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; @@ -22,13 +23,13 @@ public class SubmoduleCombinatorTest { private SubmoduleCombinator combinator = null; - public SubmoduleCombinatorTest() { - } + public SubmoduleCombinatorTest() {} @Before public void setUp() throws IOException, InterruptedException { TaskListener listener = StreamTaskListener.fromStderr(); - GitClient gitClient = Git.with(listener, new EnvVars()).in(new File(".")).getClient(); + GitClient gitClient = + Git.with(listener, new EnvVars()).in(new File(".")).getClient(); Collection cfg = null; combinator = new SubmoduleCombinator(gitClient, listener, cfg); } diff --git a/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java b/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java index 59bc037566..5acb13b5f7 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java @@ -23,15 +23,16 @@ */ package hudson.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jgit.lib.ObjectId; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; @Deprecated public class SubmoduleConfigTest { diff --git a/src/test/java/hudson/plugins/git/TestGitRepo.java b/src/test/java/hudson/plugins/git/TestGitRepo.java index e6faece60e..7d5facf558 100644 --- a/src/test/java/hudson/plugins/git/TestGitRepo.java +++ b/src/test/java/hudson/plugins/git/TestGitRepo.java @@ -4,57 +4,56 @@ import hudson.EnvVars; import hudson.FilePath; import hudson.model.TaskListener; -import hudson.model.UserProperty; import hudson.model.User; +import hudson.model.UserProperty; import hudson.plugins.git.util.GitUtilsTest; import hudson.tasks.Mailer; - import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import org.eclipse.jgit.lib.PersonIdent; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; public class TestGitRepo { - protected String name; // The name of this repository. - protected TaskListener listener; - - /** + protected String name; // The name of this repository. + protected TaskListener listener; + + /** * This is where the commit commands create a Git repository. */ - public File gitDir; // was "workDir" - public FilePath gitDirPath; // was "workspace" - public GitClient git; - - public final PersonIdent johnDoe = new PersonIdent("John Doe", "john@doe.com"); - public final PersonIdent janeDoe = new PersonIdent("Jane Doe", "jane@doe.com"); - + public File gitDir; // was "workDir" + + public FilePath gitDirPath; // was "workspace" + public GitClient git; + + public final PersonIdent johnDoe = new PersonIdent("John Doe", "john@doe.com"); + public final PersonIdent janeDoe = new PersonIdent("Jane Doe", "jane@doe.com"); + public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException { - this.name = name; - this.listener = listener; - - EnvVars envVars = GitUtilsTest.getConfigNoSystemEnvsVars(); - - gitDir = tmpDir; - User john = User.getOrCreateByIdOrFullName(johnDoe.getName()); - UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress()); - john.addProperty(johnsMailerProperty); - - User jane = User.getOrCreateByIdOrFullName(janeDoe.getName()); - UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress()); - jane.addProperty(janesMailerProperty); - - // initialize the git interface. - gitDirPath = new FilePath(gitDir); - git = Git.with(listener, envVars).in(gitDir).getClient(); + this.name = name; + this.listener = listener; + + EnvVars envVars = GitUtilsTest.getConfigNoSystemEnvsVars(); + + gitDir = tmpDir; + User john = User.getOrCreateByIdOrFullName(johnDoe.getName()); + UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress()); + john.addProperty(johnsMailerProperty); + + User jane = User.getOrCreateByIdOrFullName(janeDoe.getName()); + UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress()); + jane.addProperty(janesMailerProperty); + + // initialize the git interface. + gitDirPath = new FilePath(gitDir); + git = Git.with(listener, envVars).in(gitDir).getClient(); // finally: initialize the repo - git.init(); - } - + git.init(); + } + /** * Creates a commit in current repo. * @param fileName relative path to the file to be committed with default content @@ -79,7 +78,8 @@ public String commit(final String fileName, final PersonIdent committer, final S * @throws GitException on git error * @throws InterruptedException when interrupted */ - public String commit(final String fileName, final PersonIdent author, final PersonIdent committer, final String message) + public String commit( + final String fileName, final PersonIdent author, final PersonIdent committer, final String message) throws GitException, InterruptedException { return commit(fileName, fileName, author, committer, message); } @@ -94,7 +94,8 @@ public String commit(final String fileName, final PersonIdent author, final Pers * @throws GitException on git error * @throws InterruptedException when interrupted */ - public String commit(final String fileName, final String fileContent, final PersonIdent committer, final String message) + public String commit( + final String fileName, final String fileContent, final PersonIdent committer, final String message) throws GitException, InterruptedException { return commit(fileName, fileContent, committer, committer, message); } @@ -110,8 +111,13 @@ public String commit(final String fileName, final String fileContent, final Pers * @throws GitException on git error * @throws InterruptedException when interrupted */ - public String commit(final String fileName, final String fileContent, final PersonIdent author, final PersonIdent committer, - final String message) throws GitException, InterruptedException { + public String commit( + final String fileName, + final String fileContent, + final PersonIdent author, + final PersonIdent committer, + final String message) + throws GitException, InterruptedException { FilePath file = gitDirPath.child(fileName); try { file.write(fileContent, null); diff --git a/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java b/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java index ad1a230859..802abddff9 100644 --- a/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -9,9 +11,8 @@ import nl.jqno.equalsverifier.Warning; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.structs.describable.DescribableModel; -import org.junit.Test; -import static org.junit.Assert.*; import org.junit.ClassRule; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.jvnet.hudson.test.Issue; @@ -31,11 +32,9 @@ public class UserMergeOptionsTest { private final MergeCommand.GitPluginFastForwardMode expectedFastForwardMode; @Deprecated - private UserMergeOptions defineDeprecatedOptions(String mergeRemote, String mergeTarget, MergeCommand.Strategy mergeStrategy) { - return new UserMergeOptions( - mergeRemote, - mergeTarget, - mergeStrategy == null ? null : mergeStrategy.toString()); + private UserMergeOptions defineDeprecatedOptions( + String mergeRemote, String mergeTarget, MergeCommand.Strategy mergeStrategy) { + return new UserMergeOptions(mergeRemote, mergeTarget, mergeStrategy == null ? null : mergeStrategy.toString()); } public UserMergeOptionsTest( @@ -48,19 +47,16 @@ public UserMergeOptionsTest( this.expectedMergeStrategy = mergeStrategy; this.expectedFastForwardMode = fastForwardMode; options = new UserMergeOptions( - mergeRemote, - mergeTarget, - mergeStrategy == null ? null : mergeStrategy.toString(), - fastForwardMode); + mergeRemote, mergeTarget, mergeStrategy == null ? null : mergeStrategy.toString(), fastForwardMode); deprecatedOptions = defineDeprecatedOptions(mergeRemote, mergeTarget, mergeStrategy); } @Parameterized.Parameters(name = "{0}+{1}+{2}+{3}") public static Collection mergeOptionVariants() { List mergeOptions = new ArrayList<>(); - String[] remotes = new String[]{null, "src_remote"}; - String[] targets = new String[]{null, "dst_remote"}; - MergeCommand.Strategy[] mergeStrategies = new MergeCommand.Strategy[]{ + String[] remotes = new String[] {null, "src_remote"}; + String[] targets = new String[] {null, "dst_remote"}; + MergeCommand.Strategy[] mergeStrategies = new MergeCommand.Strategy[] { null, MergeCommand.Strategy.DEFAULT, MergeCommand.Strategy.OCTOPUS, @@ -69,7 +65,7 @@ public static Collection mergeOptionVariants() { MergeCommand.Strategy.RESOLVE, MergeCommand.Strategy.SUBTREE }; - MergeCommand.GitPluginFastForwardMode[] fastForwardModes = new MergeCommand.GitPluginFastForwardMode[]{ + MergeCommand.GitPluginFastForwardMode[] fastForwardModes = new MergeCommand.GitPluginFastForwardMode[] { null, MergeCommand.GitPluginFastForwardMode.FF, MergeCommand.GitPluginFastForwardMode.FF_ONLY, @@ -105,12 +101,16 @@ public void testGetRef() { @Test public void testGetMergeStrategy() { - assertEquals(expectedMergeStrategy == null ? MergeCommand.Strategy.DEFAULT : expectedMergeStrategy, options.getMergeStrategy()); + assertEquals( + expectedMergeStrategy == null ? MergeCommand.Strategy.DEFAULT : expectedMergeStrategy, + options.getMergeStrategy()); } @Test public void testGetFastForwardMode() { - assertEquals(expectedFastForwardMode == null ? MergeCommand.GitPluginFastForwardMode.FF : expectedFastForwardMode, options.getFastForwardMode()); + assertEquals( + expectedFastForwardMode == null ? MergeCommand.GitPluginFastForwardMode.FF : expectedFastForwardMode, + options.getFastForwardMode()); } @Test @@ -118,8 +118,12 @@ public void testToString() { final String expected = "UserMergeOptions{" + "mergeRemote='" + expectedMergeRemote + "', " + "mergeTarget='" + expectedMergeTarget + "', " - + "mergeStrategy='" + (expectedMergeStrategy == null ? MergeCommand.Strategy.DEFAULT : expectedMergeStrategy).name() + "', " - + "fastForwardMode='" + (expectedFastForwardMode == null ? MergeCommand.GitPluginFastForwardMode.FF : expectedFastForwardMode).name() + "'" + + "mergeStrategy='" + + (expectedMergeStrategy == null ? MergeCommand.Strategy.DEFAULT : expectedMergeStrategy).name() + "', " + + "fastForwardMode='" + + (expectedFastForwardMode == null ? MergeCommand.GitPluginFastForwardMode.FF : expectedFastForwardMode) + .name() + + "'" + '}'; assertEquals(expected, options.toString()); } @@ -234,5 +238,4 @@ public void mergeStrategyCase() throws Exception { assertEquals(options, new DescribableModel<>(UserMergeOptions.class).instantiate(args)); } } - } diff --git a/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java b/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java index d96eb41ef1..b65db833d9 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java @@ -1,20 +1,18 @@ package hudson.plugins.git; -import hudson.util.FormValidation; -import org.junit.Test; -import org.jvnet.hudson.test.Issue; +import static org.junit.Assert.assertEquals; +import hudson.util.FormValidation; import java.util.ArrayList; import java.util.List; - -import static org.junit.Assert.assertEquals; - +import org.junit.Test; +import org.jvnet.hudson.test.Issue; public class UserRemoteConfigRefSpecTest { @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithoutWildcards(){ + public void testdoCheckRefspecSuccessWithoutWildcards() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -24,14 +22,14 @@ public void testdoCheckRefspecSuccessWithoutWildcards(){ refSpec.add("master:refs/remotes/origin/mymaster topic:refs/remotes/origin/topic"); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { + for (String ref : refSpec) { assertEquals(FormValidation.ok(), descriptor.doCheckRefspec(url, name, ref)); } } @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithMatchedWildCards(){ + public void testdoCheckRefspecSuccessWithMatchedWildCards() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -39,14 +37,14 @@ public void testdoCheckRefspecSuccessWithMatchedWildCards(){ refSpec.add("+refs/pull/*/head:refs/remotes/origin/pr/*"); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { + for (String ref : refSpec) { assertEquals(FormValidation.ok(), descriptor.doCheckRefspec(url, name, ref)); } } @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecFailureWithUnMatchedWildCards(){ + public void testdoCheckRefspecFailureWithUnMatchedWildCards() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -54,52 +52,50 @@ public void testdoCheckRefspecFailureWithUnMatchedWildCards(){ refSpec.add("+refs/heads/qa/*:refs/remotes/origin/qa"); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { - assertEquals("Specification is invalid.", + for (String ref : refSpec) { + assertEquals( + "Specification is invalid.", descriptor.doCheckRefspec(url, name, ref).getLocalizedMessage()); } } @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithEmptyString(){ + public void testdoCheckRefspecSuccessWithEmptyString() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); refSpec.add(""); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { - assertEquals(FormValidation.ok(), - descriptor.doCheckRefspec(url, name, ref)); + for (String ref : refSpec) { + assertEquals(FormValidation.ok(), descriptor.doCheckRefspec(url, name, ref)); } } @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithPartialGlobs(){ + public void testdoCheckRefspecSuccessWithPartialGlobs() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); refSpec.add("+refs/heads/qa*:refs/remotes/origin/qa*"); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { - assertEquals(FormValidation.ok(), - descriptor.doCheckRefspec(url, name, ref)); + for (String ref : refSpec) { + assertEquals(FormValidation.ok(), descriptor.doCheckRefspec(url, name, ref)); } } @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithEnvironmentVariable(){ + public void testdoCheckRefspecSuccessWithEnvironmentVariable() { String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); refSpec.add("$REFSPEC"); UserRemoteConfig.DescriptorImpl descriptor = new UserRemoteConfig.DescriptorImpl(); - for (String ref:refSpec) { - assertEquals(FormValidation.ok(), - descriptor.doCheckRefspec(url, name, ref)); + for (String ref : refSpec) { + assertEquals(FormValidation.ok(), descriptor.doCheckRefspec(url, name, ref)); } } } diff --git a/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java b/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java index 604478f6fa..b3576fc1f5 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java @@ -1,8 +1,12 @@ package hudson.plugins.git; +import static org.junit.Assert.*; + import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; +import edu.umd.cs.findbugs.annotations.CheckForNull; +import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.User; @@ -11,12 +15,9 @@ import java.util.Arrays; import java.util.Set; import java.util.TreeSet; -import edu.umd.cs.findbugs.annotations.CheckForNull; -import edu.umd.cs.findbugs.annotations.NonNull; import jenkins.model.Jenkins; -import org.junit.Test; -import static org.junit.Assert.*; import org.junit.Rule; +import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; @@ -29,15 +30,24 @@ public class UserRemoteConfigTest { @Issue("JENKINS-38048") @Test public void credentialsDropdown() throws Exception { - SystemCredentialsProvider.getInstance().getCredentials().add(new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "mycreds", null, "jenkins", "s3cr3t")); + SystemCredentialsProvider.getInstance() + .getCredentials() + .add(new UsernamePasswordCredentialsImpl( + CredentialsScope.GLOBAL, "mycreds", null, "jenkins", "s3cr3t")); SystemCredentialsProvider.getInstance().save(); FreeStyleProject p1 = r.createFreeStyleProject("p1"); FreeStyleProject p2 = r.createFreeStyleProject("p2"); r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); - r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). - grant(Jenkins.ADMINISTER).everywhere().to("admin"). - grant(Jenkins.READ, Item.READ).everywhere().to("dev"). - grant(Item.EXTENDED_READ).onItems(p1).to("dev")); + r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() + .grant(Jenkins.ADMINISTER) + .everywhere() + .to("admin") + .grant(Jenkins.READ, Item.READ) + .everywhere() + .to("dev") + .grant(Item.EXTENDED_READ) + .onItems(p1) + .to("dev")); assertCredentials(p1, null, "dev", "", "mycreds"); assertCredentials(p2, null, "dev", ""); assertCredentials(p1, null, "admin", "", "mycreds"); @@ -49,16 +59,24 @@ public void credentialsDropdown() throws Exception { } @Deprecated - private void assertCredentials(@CheckForNull final Item project, @CheckForNull final String currentCredentialsId, @NonNull String user, @NonNull String... expectedCredentialsIds) { - final Set actual = new TreeSet<>(); // for purposes of this test we do not care about order (though StandardListBoxModel does define some) + private void assertCredentials( + @CheckForNull final Item project, + @CheckForNull final String currentCredentialsId, + @NonNull String user, + @NonNull String... expectedCredentialsIds) { + final Set actual = + new TreeSet<>(); // for purposes of this test we do not care about order (though StandardListBoxModel + // does define some) ACL.impersonate(User.get(user).impersonate(), () -> { - for (ListBoxModel.Option option : r.jenkins.getDescriptorByType(UserRemoteConfig.DescriptorImpl.class). - doFillCredentialsIdItems(project, "http://wherever.jenkins.io/", currentCredentialsId)) { + for (ListBoxModel.Option option : r.jenkins + .getDescriptorByType(UserRemoteConfig.DescriptorImpl.class) + .doFillCredentialsIdItems(project, "http://wherever.jenkins.io/", currentCredentialsId)) { actual.add(option.value); } }); - assertEquals("expected completions on " + project + " as " + user + " starting with " + currentCredentialsId, - new TreeSet<>(Arrays.asList(expectedCredentialsIds)), actual); + assertEquals( + "expected completions on " + project + " as " + user + " starting with " + currentCredentialsId, + new TreeSet<>(Arrays.asList(expectedCredentialsIds)), + actual); } - } diff --git a/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java b/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java index 65eaa01c77..a52e301bda 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.browser; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.model.FreeStyleProject; import hudson.util.FormValidation; import org.junit.Before; @@ -7,13 +10,11 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; - public class AssemblaWebDoCheckURLTest { @ClassRule public static JenkinsRule r = new JenkinsRule(); + private static int counter = 0; private FreeStyleProject project; @@ -45,15 +46,16 @@ public void testInitialChecksOnRepoUrlWithVariable() throws Exception { @Test public void testDomainLevelChecksOnRepoUrl() throws Exception { - // Invalid URL, missing '/' character - Earlier it would open connection for such mistakes but now check resolves it beforehand. + // Invalid URL, missing '/' character - Earlier it would open connection for such mistakes but now check + // resolves it beforehand. String url = "https:/assembla.com"; - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), - is("Invalid URL")); + assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Invalid URL")); } @Test public void testDomainLevelChecksOnRepoUrlInvalidURL() throws Exception { - // Invalid URL, missing ':' character - Earlier it would open connection for such mistakes but now check resolves it beforehand. + // Invalid URL, missing ':' character - Earlier it would open connection for such mistakes but now check + // resolves it beforehand. String url = "http//assmebla"; assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Invalid URL")); } @@ -76,25 +78,25 @@ public void testPathLevelChecksOnRepoUrlValidURLNullProject() throws Exception { public void testPathLevelChecksOnRepoUrlUnableToConnect() throws Exception { // Syntax issue related specific to Assembla String url = "https://app.assembla.com/space/git-plugin/git/source/"; - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), + assertThat( + assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Exception reading from Assembla URL " + url + " : ERROR: Unable to connect " + url)); } @Test public void testPathLevelChecksOnRepoUrlSupersetOfAssembla() throws Exception { java.util.Random random = new java.util.Random(); - String [] urls = { - "http://assemblage.com/", - "http://assemblage.net/", - "http://assemblage.org/", - "http://assemblages.com/", - "http://assemblages.net/", - "http://assemblages.org/", - "http://assemblagist.com/", + String[] urls = { + "http://assemblage.com/", + "http://assemblage.net/", + "http://assemblage.org/", + "http://assemblages.com/", + "http://assemblages.net/", + "http://assemblages.org/", + "http://assemblagist.com/", }; String url = urls[random.nextInt(urls.length)]; // Don't abuse a single web site with tests - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), - is("Invalid URL")); + assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Invalid URL")); } @Test @@ -102,7 +104,8 @@ public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesLocalNet() throw String hostname = "assembla.example.localnet"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), + assertThat( + assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Exception reading from Assembla URL " + url + " : ERROR: " + hostname)); } @@ -111,7 +114,8 @@ public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesHome() throws Ex String hostname = "assembla.example.home"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), + assertThat( + assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Exception reading from Assembla URL " + url + " : ERROR: " + hostname)); } @@ -120,7 +124,8 @@ public void testDomainLevelChecksOnRepoUrlCorpDomainMustBeValid() throws Excepti String hostname = "assembla.myorg.corp"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); - assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), + assertThat( + assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Exception reading from Assembla URL " + url + " : ERROR: " + hostname)); } } diff --git a/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java b/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java index dcec85f797..bbf994404c 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -7,7 +9,6 @@ import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -71,5 +72,4 @@ public void testGetFileLink() throws Exception { assertEquals(msg, expectedFileLink, fileLink); } } - } diff --git a/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java b/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java index bbfad4818e..39580450aa 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java @@ -1,17 +1,15 @@ /** * Copyright 2010 Mirko Friedenhagen */ - package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -19,7 +17,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -51,11 +50,15 @@ public void testGetDiffLinkPath() throws Exception { final String path1Str = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; final Path path1 = pathMap.get(path1Str); - assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path1Str, bitbucketServer.getDiffLink(path1).toString()); + assertEquals( + BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path1Str, + bitbucketServer.getDiffLink(path1).toString()); final String path2Str = "src/test/java/hudson/plugins/git/browser/GithubWebTest.java"; final Path path2 = pathMap.get(path2Str); - assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path2Str, bitbucketServer.getDiffLink(path2).toString()); + assertEquals( + BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path2Str, + bitbucketServer.getDiffLink(path2).toString()); final String path3Str = "src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"; final Path path3 = pathMap.get(path3Str); assertNull("Do not return a diff link for added files.", bitbucketServer.getDiffLink(path3)); @@ -63,15 +66,17 @@ public void testGetDiffLinkPath() throws Exception { @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = bitbucketServer.getFileLink(path); - assertEquals(BITBUCKET_URL + "/browse/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + BITBUCKET_URL + "/browse/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = bitbucketServer.getFileLink(path); assertEquals(BITBUCKET_URL + "/browse/bar", String.valueOf(fileLink)); @@ -81,9 +86,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? "Default" : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? "Default" : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(BitbucketServerTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(BitbucketServerTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java b/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java index 130924f9b1..5dba4d93a3 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java @@ -1,17 +1,15 @@ /** * Copyright 2010 Mirko Friedenhagen */ - package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -19,7 +17,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -52,11 +51,15 @@ public void testGetDiffLinkPath() throws Exception { final String path1Str = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; final Path path1 = pathMap.get(path1Str); - assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#chg-" + path1Str, bitbucketWeb.getDiffLink(path1).toString()); + assertEquals( + BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#chg-" + path1Str, + bitbucketWeb.getDiffLink(path1).toString()); final String path2Str = "src/test/java/hudson/plugins/git/browser/GithubWebTest.java"; final Path path2 = pathMap.get(path2Str); - assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#chg-" + path2Str, bitbucketWeb.getDiffLink(path2).toString()); + assertEquals( + BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#chg-" + path2Str, + bitbucketWeb.getDiffLink(path2).toString()); final String path3Str = "src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"; final Path path3 = pathMap.get(path3Str); assertNull("Do not return a diff link for added files.", bitbucketWeb.getDiffLink(path3)); @@ -64,15 +67,17 @@ public void testGetDiffLinkPath() throws Exception { @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = bitbucketWeb.getFileLink(path); - assertEquals(BITBUCKET_URL + "/history/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + BITBUCKET_URL + "/history/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = bitbucketWeb.getFileLink(path); assertEquals(BITBUCKET_URL + "/history/bar", String.valueOf(fileLink)); @@ -82,9 +87,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? "Default" : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? "Default" : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(BitbucketWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(BitbucketWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/CGitTest.java b/src/test/java/hudson/plugins/git/browser/CGitTest.java index 3469f6d91f..09d31a0b0f 100644 --- a/src/test/java/hudson/plugins/git/browser/CGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/CGitTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -7,7 +9,6 @@ import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -79,5 +80,4 @@ public void testGetFileLink() throws Exception { assertEquals(msg, expectedFileLink, fileLink); } } - } diff --git a/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java index 3d439a2eff..454d5b7e9c 100644 --- a/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -7,7 +9,6 @@ import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -56,7 +57,8 @@ public void testGetDiffLink() throws Exception { URL diffLink = fisheye.getDiffLink(path); EditType editType = path.getEditType(); String slash = repoUrl.endsWith("/") ? "" : "/"; - URL expectedDiffLink = new URL(repoUrl + slash + path.getPath() + "?r1=" + sample.parent + "&r2=" + sample.id); + URL expectedDiffLink = + new URL(repoUrl + slash + path.getPath() + "?r1=" + sample.parent + "&r2=" + sample.id); if (editType == EditType.DELETE || editType == EditType.ADD) { expectedDiffLink = null; } diff --git a/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java index f61278189d..749d06d9d6 100644 --- a/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -9,7 +11,6 @@ import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -49,9 +50,12 @@ public void testGetDiffLink() throws Exception { GitBlitRepositoryBrowser gitblit = new GitBlitRepositoryBrowser(repoUrl, projectName); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { EditType editType = path.getEditType(); - assertTrue("Unexpected edit type " + editType.getName(), editType == EditType.ADD || editType == EditType.EDIT || editType == EditType.DELETE); + assertTrue( + "Unexpected edit type " + editType.getName(), + editType == EditType.ADD || editType == EditType.EDIT || editType == EditType.DELETE); URL diffLink = gitblit.getDiffLink(path); - URL expectedDiffLink = new URL(repoUrl + "blobdiff?r=" + projectName + "&h=" + sample.id + "&hb=" + sample.parent); + URL expectedDiffLink = + new URL(repoUrl + "blobdiff?r=" + projectName + "&h=" + sample.id + "&hb=" + sample.parent); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); assertEquals(msg, expectedDiffLink, diffLink); } @@ -65,7 +69,9 @@ public void testGetFileLink() throws Exception { EditType editType = path.getEditType(); URL expectedFileLink = null; if (editType == EditType.ADD || editType == EditType.EDIT) { - expectedFileLink = new URL(repoUrl + "blob?r=" + projectName + "&h=" + sample.id + "&f=" + URLEncoder.encode(path.getPath(), StandardCharsets.UTF_8).replaceAll("\\+", "%20")); + expectedFileLink = new URL(repoUrl + "blob?r=" + projectName + "&h=" + sample.id + "&f=" + + URLEncoder.encode(path.getPath(), StandardCharsets.UTF_8) + .replaceAll("\\+", "%20")); } else if (editType == EditType.DELETE) { expectedFileLink = null; } else { diff --git a/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java b/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java index dbf0ae77fa..6891b31d94 100644 --- a/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java +++ b/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java @@ -31,10 +31,18 @@ public GitChangeSetSample(boolean useAuthorName) { gitChangeLog.add(" "); gitChangeLog.add(" This reverts commit 92ec0aa543f6c871502b0e6f7793a43a4df84519."); gitChangeLog.add(""); - gitChangeLog.add(":100644 000000 4378b5b0223f0435eb2365a684e6a544c5c537fc 0000000000000000000000000000000000000000 D\t" + deletedFileName); - gitChangeLog.add(":100644 100644 c305885ca26ad88b0bf96d3bb81e958cf0535194 56aef71694759b71ea76a9dfe377b0e1f8a8388f M\t" + modifiedFileName); - gitChangeLog.add(":000000 120000 0000000000000000000000000000000000000000 fb9953d5d00cb6307954f6d3bf6cb5d2355f62cd A\t" + addedFileName); - gitChangeLog.add(":100755 100755 4099f430ffd37d7e5d60aa08f61daffdccb81b2c 4099f430ffd37d7e5d60aa08f61daffdccb81b2c R100 " + renamedFileSrcName + "\t" + renamedFileDstName); + gitChangeLog.add( + ":100644 000000 4378b5b0223f0435eb2365a684e6a544c5c537fc 0000000000000000000000000000000000000000 D\t" + + deletedFileName); + gitChangeLog.add( + ":100644 100644 c305885ca26ad88b0bf96d3bb81e958cf0535194 56aef71694759b71ea76a9dfe377b0e1f8a8388f M\t" + + modifiedFileName); + gitChangeLog.add( + ":000000 120000 0000000000000000000000000000000000000000 fb9953d5d00cb6307954f6d3bf6cb5d2355f62cd A\t" + + addedFileName); + gitChangeLog.add( + ":100755 100755 4099f430ffd37d7e5d60aa08f61daffdccb81b2c 4099f430ffd37d7e5d60aa08f61daffdccb81b2c R100 " + + renamedFileSrcName + "\t" + renamedFileDstName); changeSet = new GitChangeSet(gitChangeLog, useAuthorName); } } diff --git a/src/test/java/hudson/plugins/git/browser/GitLabTest.java b/src/test/java/hudson/plugins/git/browser/GitLabTest.java index f5880e736d..6d897c92c3 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabTest.java @@ -1,20 +1,19 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; @Deprecated @@ -26,8 +25,8 @@ public class GitLabTest { private final GitLab gitlab50 = new GitLab(GITLAB_URL, "5.0"); private final GitLab gitlab51 = new GitLab(GITLAB_URL, "5.1"); private final GitLab gitlab711 = new GitLab(GITLAB_URL, "7.11"); /* Which is < 7.2 ! */ -// private final GitLab gitlab7114ee = new GitLab(GITLAB_URL, "7.11.4.ee"); /* Totally borked */ - private final GitLab gitlab7114ee = new GitLab(GITLAB_URL, "7.11"); /* Which is < 7.2 ! */ + // private final GitLab gitlab7114ee = new GitLab(GITLAB_URL, "7.11.4.ee"); /* Totally borked */ + private final GitLab gitlab7114ee = new GitLab(GITLAB_URL, "7.11"); /* Which is < 7.2 ! */ private final GitLab gitlab80 = new GitLab(GITLAB_URL, "8.0"); private final GitLab gitlab87 = new GitLab(GITLAB_URL, "8.7"); private final GitLab gitlabDefault = new GitLab(GITLAB_URL); @@ -71,7 +70,9 @@ public void testGetVersionDouble() { public void testGetChangeSetLinkGitChangeSet() throws Exception { final GitChangeSet changeSet = createChangeSet("rawchangelog"); final String expectedURL = GITLAB_URL + "commit/" + SHA1; - assertEquals(expectedURL.replace("commit/", "commits/"), gitlab29.getChangeSetLink(changeSet).toString()); + assertEquals( + expectedURL.replace("commit/", "commits/"), + gitlab29.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlab42.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlab50.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlab51.getChangeSetLink(changeSet).toString()); @@ -80,7 +81,9 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { assertEquals(expectedURL, gitlabDefault.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlabNaN.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlabInfinity.getChangeSetLink(changeSet).toString()); - assertEquals(expectedURL.replace("commit/", "commits/"), gitlabNegative.getChangeSetLink(changeSet).toString()); + assertEquals( + expectedURL.replace("commit/", "commits/"), + gitlabNegative.getChangeSetLink(changeSet).toString()); assertEquals(expectedURL, gitlabGreater.getChangeSetLink(changeSet).toString()); } @@ -101,7 +104,7 @@ public void testGetDiffLinkPath() throws Exception { assertEquals(expectedPre80, gitlab7114ee.getDiffLink(modified1).toString()); assertEquals(expectedURL, gitlab80.getDiffLink(modified1).toString()); assertEquals(expectedURL, gitlabGreater.getDiffLink(modified1).toString()); - + assertEquals(expectedDefault, gitlabDefault.getDiffLink(modified1).toString()); assertEquals(expectedDefault, gitlabNaN.getDiffLink(modified1).toString()); assertEquals(expectedDefault, gitlabInfinity.getDiffLink(modified1).toString()); @@ -137,7 +140,7 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { final String expectedPre80 = GITLAB_URL + "commit/" + SHA1 + "#" + fileName; final String expectedURL = GITLAB_URL + "commit/" + SHA1 + "#" + "diff-0"; final String expectedDefault = expectedURL; - + assertEquals(expectedPre30, gitlabNegative.getFileLink(path).toString()); assertEquals(expectedPre30, gitlab29.getFileLink(path).toString()); assertEquals(expectedPre80, gitlab42.getFileLink(path).toString()); @@ -147,20 +150,23 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { assertEquals(expectedPre80, gitlab7114ee.getFileLink(path).toString()); assertEquals(expectedURL, gitlab80.getFileLink(path).toString()); assertEquals(expectedURL, gitlabGreater.getFileLink(path).toString()); - + assertEquals(expectedDefault, gitlabDefault.getFileLink(path).toString()); assertEquals(expectedDefault, gitlabNaN.getFileLink(path).toString()); assertEquals(expectedDefault, gitlabInfinity.getFileLink(path).toString()); - } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? "Default" : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? "Default" : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(GitLabTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GitLabTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java b/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java index 3f94625476..6d6cb93f43 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java @@ -12,6 +12,7 @@ public class GitLabWorkflowTest { @Rule public JenkinsRule r = new JenkinsRule(); + @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); @@ -21,14 +22,15 @@ public void checkoutWithVersion() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" - + " checkout(\n" - + " [$class: 'GitSCM', browser: [$class: 'GitLab',\n" - + " repoUrl: 'https://a.org/a/b', version: '9.0'],\n" - + " userRemoteConfigs: [[url: $/" + sampleRepo + "/$]]]\n" - + " )\n" - + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" - + " echo \"token macro expanded branch is ${tokenBranch}\"\n" - + "}", true)); + + " checkout(\n" + + " [$class: 'GitSCM', browser: [$class: 'GitLab',\n" + + " repoUrl: 'https://a.org/a/b', version: '9.0'],\n" + + " userRemoteConfigs: [[url: $/" + sampleRepo + "/$]]]\n" + + " )\n" + + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + + " echo \"token macro expanded branch is ${tokenBranch}\"\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior } @@ -46,7 +48,8 @@ public void checkoutWithoutVersion() throws Exception { + " )\n" + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + " echo \"token macro expanded branch is ${tokenBranch}\"\n" - + "}", true)); + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior } diff --git a/src/test/java/hudson/plugins/git/browser/GitListTest.java b/src/test/java/hudson/plugins/git/browser/GitListTest.java index 18af537757..47558f7ffe 100644 --- a/src/test/java/hudson/plugins/git/browser/GitListTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitListTest.java @@ -1,17 +1,15 @@ /** * Copyright 2010 Mirko Friedenhagen */ - package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -19,8 +17,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -52,24 +50,31 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#1", gitlist.getDiffLink(path1).toString()); + assertEquals( + GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#1", + gitlist.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#2", gitlist.getDiffLink(path2).toString()); + assertEquals( + GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#2", + gitlist.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); assertNull("Do not return a diff link for added files.", gitlist.getDiffLink(path3)); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitlist.getFileLink(path); - assertEquals(GITLIST_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + GITLIST_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitlist.getFileLink(path); assertEquals(GITLIST_URL + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#1", String.valueOf(fileLink)); @@ -79,9 +84,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(GitListTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GitListTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java index 9232ef5b3d..3e57255caf 100644 --- a/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java @@ -1,15 +1,12 @@ package hudson.plugins.git.browser; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSetUtil; - -import org.eclipse.jgit.lib.ObjectId; - -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -17,11 +14,11 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; - +import org.eclipse.jgit.lib.ObjectId; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/src/test/java/hudson/plugins/git/browser/GitWebTest.java b/src/test/java/hudson/plugins/git/browser/GitWebTest.java index 615868a630..da00f828be 100644 --- a/src/test/java/hudson/plugins/git/browser/GitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitWebTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; public class GitWebTest { @@ -39,7 +38,10 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(GITWEB_URL + "&a=blobdiff&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java&fp=src/main/java/hudson/plugins/git/browser/GithubWeb.java&h=3f28ad75f5ecd5e0ea9659362e2eef18951bd451&hp=2e0756cd853dccac638486d6aab0e74bc2ef4041&hb=396fc230a3db05c427737aa5c2eb7856ba72b05d&hpb=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff", gitwebWeb.getDiffLink(modified1).toString()); + assertEquals( + GITWEB_URL + + "&a=blobdiff&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java&fp=src/main/java/hudson/plugins/git/browser/GithubWeb.java&h=3f28ad75f5ecd5e0ea9659362e2eef18951bd451&hp=2e0756cd853dccac638486d6aab0e74bc2ef4041&hb=396fc230a3db05c427737aa5c2eb7856ba72b05d&hpb=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff", + gitwebWeb.getDiffLink(modified1).toString()); } @Test @@ -47,24 +49,34 @@ public void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitwebWeb.getFileLink(path); - assertEquals(GITWEB_URL + "&a=blob&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java&h=2e0756cd853dccac638486d6aab0e74bc2ef4041&hb=396fc230a3db05c427737aa5c2eb7856ba72b05d", String.valueOf(fileLink)); + assertEquals( + GITWEB_URL + + "&a=blob&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java&h=2e0756cd853dccac638486d6aab0e74bc2ef4041&hb=396fc230a3db05c427737aa5c2eb7856ba72b05d", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitwebWeb.getFileLink(path); - assertEquals(GITWEB_URL + "&a=blob&f=bar&h=257cc5642cb1a054f08cc83f2d943e56fd3ebe99&hb=fc029da233f161c65eb06d0f1ed4f36ae81d1f4f", String.valueOf(fileLink)); + assertEquals( + GITWEB_URL + + "&a=blob&f=bar&h=257cc5642cb1a054f08cc83f2d943e56fd3ebe99&hb=fc029da233f161c65eb06d0f1ed4f36ae81d1f4f", + String.valueOf(fileLink)); } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, random.nextBoolean()); - final List changeSetList = logParser.parse(GitWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GitWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java index 7e87701404..e64c00354a 100644 --- a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java @@ -1,9 +1,10 @@ /** * Copyright 2010 Mirko Friedenhagen */ - package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; @@ -11,10 +12,6 @@ import hudson.plugins.git.GitChangeSet.Path; import hudson.plugins.git.GitSCM; import hudson.scm.RepositoryBrowser; -import jenkins.plugins.git.AbstractGitSCMSource; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -23,10 +20,11 @@ import java.util.HashMap; import java.util.List; import java.util.Random; +import jenkins.plugins.git.AbstractGitSCMSource; import jenkins.scm.api.SCMHead; import org.eclipse.jgit.transport.RefSpec; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -40,12 +38,12 @@ public class GithubWebTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(githubWeb.getUrl()), GITHUB_URL + "/"); + assertEquals(String.valueOf(githubWeb.getUrl()), GITHUB_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GithubWeb(GITHUB_URL + "/").getUrl()), GITHUB_URL + "/"); + assertEquals(String.valueOf(new GithubWeb(GITHUB_URL + "/").getUrl()), GITHUB_URL + "/"); } @Test @@ -56,7 +54,7 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { final URL commitLink = githubWeb.getChangeSetLink("396fc230a3db05c427737aa5c2eb7856ba72b05d"); assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", commitLink.toString()); - final URL noLink = githubWeb.getChangeSetLink((String)null); + final URL noLink = githubWeb.getChangeSetLink((String) null); assertNull(noLink); } @@ -64,68 +62,91 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-0", githubWeb.getDiffLink(path1).toString()); + assertEquals( + GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-0", + githubWeb.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", githubWeb.getDiffLink(path2).toString()); + assertEquals( + GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", + githubWeb.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); assertNull("Do not return a diff link for added files.", githubWeb.getDiffLink(path3)); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Issue("JENKINS-42597") @Test public void testGetFileLinkPathWithEscape() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-escape"); + final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%.txt"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25.txt", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25.txt", + String.valueOf(fileLink)); } + @Issue("JENKINS-42597") @Test public void testGetFileLinkPathWithWindowsUnescapeChar() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-escape"); + final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf^%.txt"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%5E%25.txt", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%5E%25.txt", + String.valueOf(fileLink)); } @Issue("JENKINS-42597") @Test public void testGetFileLinkPathWithDoubleEscape() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-escape"); + final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%%.txt"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25%25.txt", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25%25.txt", + String.valueOf(fileLink)); } @Issue("JENKINS-42597") @Test public void testGetFileLinkPathWithWindowsEnvironmentalVariable() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-escape"); + final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%abc%.txt"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25abc%25.txt", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25abc%25.txt", + String.valueOf(fileLink)); } @Issue("JENKINS-42597") @Test public void testGetFileLinkPathWithSpaceInName() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-escape"); + final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/config file.txt"); final URL fileLink = githubWeb.getFileLink(path); - assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/config%20file.txt", String.valueOf(fileLink)); + assertEquals( + GITHUB_URL + + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/config%20file.txt", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = githubWeb.getFileLink(path); assertEquals(GITHUB_URL + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#diff-0", String.valueOf(fileLink)); @@ -142,13 +163,21 @@ public void testGuessBrowser() { assertGuessURL("https://github.com/kohsuke/msv", "https://github.com/kohsuke/msv/"); assertGuessURL("git@github.com:kohsuke/msv.git", "https://github.com/kohsuke/msv/"); assertGuessURL("git@git.apache.org:whatever.git", null); - final boolean allowed [] = { Boolean.TRUE, Boolean.FALSE }; + final boolean allowed[] = {Boolean.TRUE, Boolean.FALSE}; for (final boolean add_git_suffix : allowed) { for (final boolean add_slash_suffix : allowed) { - assertGuessURL(repoUrl("git@github.com:kohsuke/msv", add_git_suffix, add_slash_suffix), "https://github.com/kohsuke/msv/"); - assertGuessURL(repoUrl("https://github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), "https://github.com/kohsuke/msv/"); - assertGuessURL(repoUrl("ssh://github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), "https://github.com/kohsuke/msv/"); - assertGuessURL(repoUrl("ssh://git@github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), "https://github.com/kohsuke/msv/"); + assertGuessURL( + repoUrl("git@github.com:kohsuke/msv", add_git_suffix, add_slash_suffix), + "https://github.com/kohsuke/msv/"); + assertGuessURL( + repoUrl("https://github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), + "https://github.com/kohsuke/msv/"); + assertGuessURL( + repoUrl("ssh://github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), + "https://github.com/kohsuke/msv/"); + assertGuessURL( + repoUrl("ssh://git@github.com/kohsuke/msv", add_git_suffix, add_slash_suffix), + "https://github.com/kohsuke/msv/"); } } } @@ -163,13 +192,21 @@ private void assertGuessURL(String repo, String web) { @Test public void guessBrowserSCMSource() throws Exception { // like GitSCMSource: - assertGuessURL("https://github.com/kohsuke/msv.git", "https://github.com/kohsuke/msv/", "+refs/heads/*:refs/remotes/origin/*"); + assertGuessURL( + "https://github.com/kohsuke/msv.git", + "https://github.com/kohsuke/msv/", + "+refs/heads/*:refs/remotes/origin/*"); // like GitHubSCMSource: - assertGuessURL("https://github.com/kohsuke/msv.git", "https://github.com/kohsuke/msv/", "+refs/heads/*:refs/remotes/origin/*", "+refs/pull/*/merge:refs/remotes/origin/pr/*"); + assertGuessURL( + "https://github.com/kohsuke/msv.git", + "https://github.com/kohsuke/msv/", + "+refs/heads/*:refs/remotes/origin/*", + "+refs/pull/*/merge:refs/remotes/origin/pr/*"); } private void assertGuessURL(String remote, String web, String... refSpecs) { - RepositoryBrowser guess = new MockSCMSource(remote, refSpecs).build(new SCMHead("master")).guessBrowser(); + RepositoryBrowser guess = + new MockSCMSource(remote, refSpecs).build(new SCMHead("master")).guessBrowser(); String actual = guess instanceof GithubWeb ? ((GithubWeb) guess).getRepoUrl() : null; assertEquals(web, actual); } @@ -177,28 +214,34 @@ private void assertGuessURL(String remote, String web, String... refSpecs) { private static class MockSCMSource extends AbstractGitSCMSource { private final String remote; private final String[] refSpecs; + MockSCMSource(String remote, String[] refSpecs) { this.remote = remote; this.refSpecs = refSpecs; } + @Override public String getCredentialsId() { return null; } + @Override public String getRemote() { return remote; } + @Override @Deprecated public String getIncludes() { return "*"; } + @Override @Deprecated public String getExcludes() { return ""; } + @Override @Deprecated protected List getRefSpecs() { @@ -214,9 +257,13 @@ protected List getRefSpecs() { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(GithubWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GithubWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } @@ -228,5 +275,4 @@ private HashMap createPathMap(final String changelog) throws Excep } return pathMap; } - } diff --git a/src/test/java/hudson/plugins/git/browser/GitilesTest.java b/src/test/java/hudson/plugins/git/browser/GitilesTest.java index ba7018164b..6dde6a706e 100644 --- a/src/test/java/hudson/plugins/git/browser/GitilesTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitilesTest.java @@ -1,12 +1,13 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -46,7 +47,8 @@ public void testGetDiffLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = gitiles.getDiffLink(path); URL expectedDiffLink = new URL(repoUrl + "+/" + sample.id + "%5E%21"); - String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName(); + String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + + path.getEditType().getName(); assertEquals(msg, expectedDiffLink, diffLink); } } @@ -57,7 +59,8 @@ public void testGetFileLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = gitiles.getFileLink(path); URL expectedFileLink = new URL(repoUrl + "+blame/" + sample.id + "/" + path.getPath()); - String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName(); + String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + + path.getEditType().getName(); assertEquals(msg, expectedFileLink, fileLink); } } diff --git a/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java b/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java index 09b44e6fab..c050d3ddf2 100644 --- a/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; public class GitoriousWebTest { @@ -26,12 +25,12 @@ public class GitoriousWebTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(gitoriousWeb.getUrl()), GITORIOUS_URL + "/"); + assertEquals(String.valueOf(gitoriousWeb.getUrl()), GITORIOUS_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GitoriousWeb(GITORIOUS_URL + "/").getUrl()), GITORIOUS_URL + "/"); + assertEquals(String.valueOf(new GitoriousWeb(GITORIOUS_URL + "/").getUrl()), GITORIOUS_URL + "/"); } @Test @@ -44,35 +43,51 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/main/java/hudson/plugins/git/browser/GithubWeb.java", gitoriousWeb.getDiffLink(modified1).toString()); + assertEquals( + GITORIOUS_URL + + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/main/java/hudson/plugins/git/browser/GithubWeb.java", + gitoriousWeb.getDiffLink(modified1).toString()); // For added files returns a link to the commit. final Path added = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file", gitoriousWeb.getDiffLink(added).toString()); + assertEquals( + GITORIOUS_URL + + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file", + gitoriousWeb.getDiffLink(added).toString()); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitoriousWeb.getFileLink(path); - assertEquals(GITORIOUS_URL + "/blobs/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + GITORIOUS_URL + + "/blobs/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitoriousWeb.getFileLink(path); - assertEquals(GITORIOUS_URL + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f/diffs?diffmode=sidebyside&fragment=1#bar", String.valueOf(fileLink)); + assertEquals( + GITORIOUS_URL + + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f/diffs?diffmode=sidebyside&fragment=1#bar", + String.valueOf(fileLink)); } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(GitoriousWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GitoriousWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/GogsGitTest.java b/src/test/java/hudson/plugins/git/browser/GogsGitTest.java index 81d1806eca..3afcf76595 100644 --- a/src/test/java/hudson/plugins/git/browser/GogsGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/GogsGitTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -29,12 +28,12 @@ public class GogsGitTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(GogsGit.getUrl()), GOGS_URL + "/"); + assertEquals(String.valueOf(GogsGit.getUrl()), GOGS_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GogsGit(GOGS_URL + "/").getUrl()), GOGS_URL + "/"); + assertEquals(String.valueOf(new GogsGit(GOGS_URL + "/").getUrl()), GOGS_URL + "/"); } @Test @@ -47,9 +46,13 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", GogsGit.getDiffLink(path1).toString()); + assertEquals( + GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", + GogsGit.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", GogsGit.getDiffLink(path2).toString()); + assertEquals( + GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", + GogsGit.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); assertNull("Do not return a diff link for added files.", GogsGit.getDiffLink(path3)); } @@ -59,12 +62,15 @@ public void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = GogsGit.getFileLink(path); - assertEquals(GOGS_URL + "/src/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + GOGS_URL + + "/src/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = GogsGit.getFileLink(path); assertEquals(GOGS_URL + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#diff-1", String.valueOf(fileLink)); @@ -74,9 +80,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(GogsGitTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(GogsGitTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/KilnGitTest.java b/src/test/java/hudson/plugins/git/browser/KilnGitTest.java index 61f75c1a5b..cd1d527044 100644 --- a/src/test/java/hudson/plugins/git/browser/KilnGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/KilnGitTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -29,12 +28,12 @@ public class KilnGitTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(kilnGit.getUrl()), KILN_URL + "/"); + assertEquals(String.valueOf(kilnGit.getUrl()), KILN_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new KilnGit(KILN_URL + "/").getUrl()), KILN_URL + "/"); + assertEquals(String.valueOf(new KilnGit(KILN_URL + "/").getUrl()), KILN_URL + "/"); } @Test @@ -47,24 +46,31 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", kilnGit.getDiffLink(path1).toString()); + assertEquals( + KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", + kilnGit.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", kilnGit.getDiffLink(path2).toString()); + assertEquals( + KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", + kilnGit.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); assertNull("Do not return a diff link for added files.", kilnGit.getDiffLink(path3)); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = kilnGit.getFileLink(path); - assertEquals(KILN_URL + "/FileHistory/src/main/java/hudson/plugins/git/browser/GithubWeb.java?rev=396fc230a3db05c427737aa5c2eb7856ba72b05d", String.valueOf(fileLink)); + assertEquals( + KILN_URL + + "/FileHistory/src/main/java/hudson/plugins/git/browser/GithubWeb.java?rev=396fc230a3db05c427737aa5c2eb7856ba72b05d", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = kilnGit.getFileLink(path); assertEquals(KILN_URL + "/History/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#diff-1", String.valueOf(fileLink)); @@ -74,9 +80,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(KilnGitTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(KilnGitTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java b/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java index 904404e43d..97a267b9fb 100644 --- a/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java +++ b/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java @@ -1,10 +1,11 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import java.io.IOException; import java.net.URL; import org.junit.Test; -import static org.junit.Assert.*; public class PhabricatorTest { @@ -34,7 +35,8 @@ public void testGetChangeSetLink() throws Exception { public void testGetDiffLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = phabricator.getDiffLink(path); - URL expectedDiffLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); + URL expectedDiffLink = + new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); String msg = "Wrong link for path: " + path.getPath(); assertEquals(msg, expectedDiffLink, diffLink); } @@ -44,10 +46,10 @@ public void testGetDiffLink() throws Exception { public void testGetFileLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = phabricator.getDiffLink(path); - URL expectedFileLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); + URL expectedFileLink = + new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); String msg = "Wrong link for path: " + path.getPath(); assertEquals(msg, expectedFileLink, fileLink); } } - } diff --git a/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java b/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java index af0fb384de..adeaabd2e9 100644 --- a/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,7 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -28,12 +28,12 @@ public class RedmineWebTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(redmineWeb.getUrl()), REDMINE_URL + "/"); + assertEquals(String.valueOf(redmineWeb.getUrl()), REDMINE_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new RedmineWeb(REDMINE_URL + "/").getUrl()), REDMINE_URL + "/"); + assertEquals(String.valueOf(new RedmineWeb(REDMINE_URL + "/").getUrl()), REDMINE_URL + "/"); } @Test @@ -46,37 +46,54 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(REDMINE_URL + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java", redmineWeb.getDiffLink(modified1).toString()); + assertEquals( + REDMINE_URL + + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + redmineWeb.getDiffLink(modified1).toString()); final Path modified2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(REDMINE_URL + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/diff/src/test/java/hudson/plugins/git/browser/GithubWebTest.java", redmineWeb.getDiffLink(modified2).toString()); + assertEquals( + REDMINE_URL + + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/diff/src/test/java/hudson/plugins/git/browser/GithubWebTest.java", + redmineWeb.getDiffLink(modified2).toString()); // For added files returns a link to the entry. final Path added = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertEquals(REDMINE_URL + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/entry/src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file", redmineWeb.getDiffLink(added).toString()); + assertEquals( + REDMINE_URL + + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/entry/src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file", + redmineWeb.getDiffLink(added).toString()); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = redmineWeb.getFileLink(path); - assertEquals(REDMINE_URL + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/entry/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + REDMINE_URL + + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/entry/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = redmineWeb.getFileLink(path); - assertEquals(REDMINE_URL + "/revisions/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f/diff/bar", String.valueOf(fileLink)); + assertEquals( + REDMINE_URL + "/revisions/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f/diff/bar", String.valueOf(fileLink)); } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(RedmineWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(RedmineWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java b/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java index f080d4e991..e35cd23e5c 100644 --- a/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java +++ b/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; public class RhodeCodeTest { @@ -26,12 +25,12 @@ public class RhodeCodeTest { @Test public void testGetUrl() throws IOException { - assertEquals(String.valueOf(rhodecode.getUrl()), RHODECODE_URL + "/"); + assertEquals(String.valueOf(rhodecode.getUrl()), RHODECODE_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new RhodeCode(RHODECODE_URL + "/").getUrl()), RHODECODE_URL + "/"); + assertEquals(String.valueOf(new RhodeCode(RHODECODE_URL + "/").getUrl()), RHODECODE_URL + "/"); } @Test @@ -44,23 +43,32 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(RHODECODE_URL + "/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java?diff2=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff&diff1=396fc230a3db05c427737aa5c2eb7856ba72b05d&diff=diff+to+revision", rhodecode.getDiffLink(modified1).toString()); + assertEquals( + RHODECODE_URL + + "/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java?diff2=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff&diff1=396fc230a3db05c427737aa5c2eb7856ba72b05d&diff=diff+to+revision", + rhodecode.getDiffLink(modified1).toString()); // For added files returns a link to the commit. final Path added = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(RHODECODE_URL + "/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java?diff2=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff&diff1=396fc230a3db05c427737aa5c2eb7856ba72b05d&diff=diff+to+revision", rhodecode.getDiffLink(added).toString()); + assertEquals( + RHODECODE_URL + + "/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java?diff2=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff&diff1=396fc230a3db05c427737aa5c2eb7856ba72b05d&diff=diff+to+revision", + rhodecode.getDiffLink(added).toString()); } @Test public void testGetFileLinkPath() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog"); + final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = rhodecode.getFileLink(path); - assertEquals(RHODECODE_URL + "/files/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); + assertEquals( + RHODECODE_URL + + "/files/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", + String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { - final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); + final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = rhodecode.getFileLink(path); assertEquals(RHODECODE_URL + "/files/b547aa10c3f06710c6fdfcdb2a9149c81662923b/bar", String.valueOf(fileLink)); @@ -70,9 +78,13 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(RhodeCodeTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(RhodeCodeTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/StashTest.java b/src/test/java/hudson/plugins/git/browser/StashTest.java index b6398c3f85..64736f2feb 100644 --- a/src/test/java/hudson/plugins/git/browser/StashTest.java +++ b/src/test/java/hudson/plugins/git/browser/StashTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -7,7 +9,6 @@ import java.util.Collection; import java.util.List; import org.junit.Test; -import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -49,9 +50,11 @@ public void testGetDiffLink() throws Exception { EditType editType = path.getEditType(); URL expectedDiffLink = null; if (editType == EditType.ADD || editType == EditType.EDIT) { - expectedDiffLink = new URL(repoUrl + "diff/" + path.getPath() + "?at=" + sample.id + "&until=" + sample.id); + expectedDiffLink = + new URL(repoUrl + "diff/" + path.getPath() + "?at=" + sample.id + "&until=" + sample.id); } else if (editType == EditType.DELETE) { - expectedDiffLink = new URL(repoUrl + "diff/" + path.getPath() + "?at=" + sample.parent + "&until=" + sample.id); + expectedDiffLink = + new URL(repoUrl + "diff/" + path.getPath() + "?at=" + sample.parent + "&until=" + sample.id); } else { fail("Unexpected edit type " + editType.getName()); } diff --git a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java index ae3806d0e9..da55444b28 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java @@ -1,22 +1,21 @@ package hudson.plugins.git.browser; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import hudson.model.*; import hudson.plugins.git.*; import hudson.scm.ChangeLogSet; import hudson.scm.EditType; -import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.BeforeClass; -import org.junit.Test; - import java.net.URL; import java.util.ArrayList; import java.util.Collections; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.jenkinsci.plugins.gitclient.JGitTool; +import org.junit.BeforeClass; +import org.junit.Test; public class TFS2013GitRepositoryBrowserTest { @@ -28,7 +27,8 @@ public static void setUp() { GitSCM scm = new GitSCM( Collections.singletonList(new UserRemoteConfig(repoUrl, null, null, null)), new ArrayList<>(), - null, JGitTool.MAGIC_EXENAME, + null, + JGitTool.MAGIC_EXENAME, Collections.emptyList()); AbstractProject project = mock(AbstractProject.class); @@ -71,7 +71,8 @@ public void testGetDiffLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = browser.getDiffLink(path); EditType editType = path.getEditType(); - URL expectedDiffLink = new URL("http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=compare"); + URL expectedDiffLink = new URL( + "http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=compare"); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); assertEquals(msg, expectedDiffLink, diffLink); } @@ -83,7 +84,8 @@ public void testGetFileLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = browser.getFileLink(path); EditType editType = path.getEditType(); - URL expectedFileLink = new URL("http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=history"); + URL expectedFileLink = new URL( + "http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=history"); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); assertEquals(msg, expectedFileLink, fileLink); } diff --git a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java index 321c13d27d..289946c28c 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java @@ -4,6 +4,9 @@ import hudson.model.FreeStyleProject; import hudson.plugins.git.GitSCM; import hudson.plugins.git.UserRemoteConfig; +import java.util.ArrayList; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicBoolean; import org.jenkinsci.plugins.gitclient.JGitTool; import org.junit.Assert; import org.junit.Rule; @@ -11,10 +14,6 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import java.util.ArrayList; -import java.util.Collections; -import java.util.concurrent.atomic.AtomicBoolean; - public class TFS2013GitRepositoryBrowserXSSTest { @Rule @@ -27,7 +26,8 @@ public void testXSS() throws Exception { GitSCM scm = new GitSCM( Collections.singletonList(new UserRemoteConfig("http://tfs/tfs/project/_git/repo", null, null, null)), new ArrayList<>(), - null, JGitTool.MAGIC_EXENAME, + null, + JGitTool.MAGIC_EXENAME, Collections.emptyList()); scm.setBrowser(new TFS2013GitRepositoryBrowser("")); diff --git a/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java b/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java index bdd2ac3335..a0c4ae405b 100644 --- a/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java @@ -1,13 +1,12 @@ package hudson.plugins.git.browser; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -15,8 +14,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; - -import static org.junit.Assert.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; /** @@ -41,16 +40,24 @@ public void testGetUrlForRepoWithTrailingSlash() throws IOException { @Test public void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = viewGitWeb.getChangeSetLink(createChangeSet("rawchangelog")); - assertEquals("http://SERVER/viewgit/?p=PROJECT&a=commit&h=396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); + assertEquals( + "http://SERVER/viewgit/?p=PROJECT&a=commit&h=396fc230a3db05c427737aa5c2eb7856ba72b05d", + changeSetLink.toString()); } @Test public void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); - assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Fmain%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWeb.java", viewGitWeb.getDiffLink(path1).toString()); + assertEquals( + VIEWGIT_URL + + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Fmain%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWeb.java", + viewGitWeb.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); - assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Ftest%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWebTest.java", viewGitWeb.getDiffLink(path2).toString()); + assertEquals( + VIEWGIT_URL + + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Ftest%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWebTest.java", + viewGitWeb.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); assertNull("Do not return a diff link for added files.", viewGitWeb.getDiffLink(path3)); } @@ -60,16 +67,17 @@ public void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = viewGitWeb.getFileLink(path); - assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=viewblob&h=2e0756cd853dccac638486d6aab0e74bc2ef4041&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java", + assertEquals( + VIEWGIT_URL + + "/?p=PROJECT&a=viewblob&h=2e0756cd853dccac638486d6aab0e74bc2ef4041&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); } - + @Test public void testGetDiffLinkForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); assertNull("Do not return a diff link for deleted files.", viewGitWeb.getDiffLink(path)); - } @Test @@ -77,16 +85,22 @@ public void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = viewGitWeb.getFileLink(path); - assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#bar", String.valueOf(fileLink)); + assertEquals( + VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=fc029da233f161c65eb06d0f1ed4f36ae81d1f4f#bar", + String.valueOf(fileLink)); } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ - GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? null : "jgit").getClient(); + GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(new File(".")) + .using(random.nextBoolean() ? null : "jgit") + .getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); - final List changeSetList = logParser.parse(ViewGitWebTest.class.getResourceAsStream(rawchangelogpath)); + final List changeSetList = + logParser.parse(ViewGitWebTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } diff --git a/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java b/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java index ca8d3e658e..2c3953cd4f 100644 --- a/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java +++ b/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java @@ -1,16 +1,16 @@ package hudson.plugins.git.browser.casc; -import hudson.plugins.git.browser.GitLab; -import io.jenkins.plugins.casc.ConfigurationContext; -import io.jenkins.plugins.casc.model.Mapping; -import org.junit.Test; - +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; +import hudson.plugins.git.browser.GitLab; +import io.jenkins.plugins.casc.ConfigurationContext; +import io.jenkins.plugins.casc.model.Mapping; +import org.junit.Test; + public class GitLabConfiguratorTest { private final GitLabConfigurator configurator = new GitLabConfigurator(); @@ -50,7 +50,8 @@ public void testDescribe() throws Exception { expectedMapping.put("version", "1.1"); final GitLab configuration = new GitLab("http://fake", "1.1"); - final Mapping described = configurator.describe(configuration, NULL_CONFIGURATION_CONTEXT).asMapping(); + final Mapping described = + configurator.describe(configuration, NULL_CONFIGURATION_CONTEXT).asMapping(); assertEquals(expectedMapping.getScalarValue("repoUrl"), described.getScalarValue("repoUrl")); assertEquals(expectedMapping.getScalarValue("version"), described.getScalarValue("version")); } @@ -79,7 +80,6 @@ public void testInstanceWithEmptyRepo() throws Exception { final GitLab instance = configurator.instance(mapping, NULL_CONFIGURATION_CONTEXT); assertEquals(expectedConfiguration.getRepoUrl(), instance.getRepoUrl()); assertEquals(String.valueOf(expectedConfiguration.getVersion()), String.valueOf(instance.getVersion())); - } @Test @@ -94,7 +94,6 @@ public void testInstanceWithNullRepo() throws Exception { assertEquals(String.valueOf(expectedConfiguration.getVersion()), String.valueOf(instance.getVersion())); } - @Test @Deprecated public void testInstanceWithEmptyVersion() throws Exception { @@ -145,5 +144,4 @@ public void testInstanceWithNaNVersion() throws Exception { assertEquals(expectedConfiguration.getRepoUrl(), instance.getRepoUrl()); assertEquals(String.valueOf(expectedConfiguration.getVersion()), String.valueOf(instance.getVersion())); } - } diff --git a/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java b/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java index 60dda34a52..fe48827f02 100644 --- a/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.TestGitRepo; import hudson.util.StreamTaskListener; +import java.util.Collections; +import java.util.List; import org.eclipse.jgit.util.SystemReader; import org.junit.After; import org.junit.Before; @@ -15,79 +17,73 @@ import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import org.jvnet.hudson.test.JenkinsRule; -import java.util.Collections; -import java.util.List; - /** * @author Kanstantsin Shautsou */ public abstract class GitSCMExtensionTest { - protected TaskListener listener; + protected TaskListener listener; - @ClassRule - public static BuildWatcher buildWatcher = new BuildWatcher(); + @ClassRule + public static BuildWatcher buildWatcher = new BuildWatcher(); - @Rule - public JenkinsRule j = new JenkinsRule(); + @Rule + public JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); - @Before - public void setUp() throws Exception { - SystemReader.getInstance().getUserConfig().clear(); - listener = StreamTaskListener.fromStderr(); - before(); - } + @Before + public void setUp() throws Exception { + SystemReader.getInstance().getUserConfig().clear(); + listener = StreamTaskListener.fromStderr(); + before(); + } - @Before - public void allowNonRemoteCheckout() { - GitSCM.ALLOW_LOCAL_CHECKOUT = true; - } + @Before + public void allowNonRemoteCheckout() { + GitSCM.ALLOW_LOCAL_CHECKOUT = true; + } - @After - public void disallowNonRemoteCheckout() { - GitSCM.ALLOW_LOCAL_CHECKOUT = false; - } + @After + public void disallowNonRemoteCheckout() { + GitSCM.ALLOW_LOCAL_CHECKOUT = false; + } - protected abstract void before() throws Exception; + protected abstract void before() throws Exception; - /** - * The {@link GitSCMExtension} being tested - this will be added to the - * project built in {@link #setupBasicProject(TestGitRepo)} - * @return the extension - */ - protected abstract GitSCMExtension getExtension(); + /** + * The {@link GitSCMExtension} being tested - this will be added to the + * project built in {@link #setupBasicProject(TestGitRepo)} + * @return the extension + */ + protected abstract GitSCMExtension getExtension(); - protected FreeStyleBuild build(final FreeStyleProject project, final Result expectedResult) throws Exception { - final FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause()).get(); - if(expectedResult != null) { - j.assertBuildStatus(expectedResult, build); - } - return build; - } + protected FreeStyleBuild build(final FreeStyleProject project, final Result expectedResult) throws Exception { + final FreeStyleBuild build = + project.scheduleBuild2(0, new Cause.UserIdCause()).get(); + if (expectedResult != null) { + j.assertBuildStatus(expectedResult, build); + } + return build; + } - /** - * Create a {@link FreeStyleProject} configured with a {@link GitSCM} - * building on the {@code master} branch of the provided {@code repo}, - * and with the extension described in {@link #getExtension()} added. - * @param repo git repository - * @return the created project - * @throws Exception on error - */ - protected FreeStyleProject setupBasicProject(TestGitRepo repo) throws Exception { - GitSCMExtension extension = getExtension(); - FreeStyleProject project = j.createFreeStyleProject("p"); - List branches = Collections.singletonList(new BranchSpec("master")); - GitSCM scm = new GitSCM( - repo.remoteConfigs(), - branches, - null, null, - Collections.emptyList()); - scm.getExtensions().add(extension); - project.setScm(scm); - project.getBuildersList().add(new CaptureEnvironmentBuilder()); - return project; - } + /** + * Create a {@link FreeStyleProject} configured with a {@link GitSCM} + * building on the {@code master} branch of the provided {@code repo}, + * and with the extension described in {@link #getExtension()} added. + * @param repo git repository + * @return the created project + * @throws Exception on error + */ + protected FreeStyleProject setupBasicProject(TestGitRepo repo) throws Exception { + GitSCMExtension extension = getExtension(); + FreeStyleProject project = j.createFreeStyleProject("p"); + List branches = Collections.singletonList(new BranchSpec("master")); + GitSCM scm = new GitSCM(repo.remoteConfigs(), branches, null, null, Collections.emptyList()); + scm.getExtensions().add(extension); + project.setScm(scm); + project.getBuildersList().add(new CaptureEnvironmentBuilder()); + return project; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java b/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java index b4ac5866fa..c80fe49396 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java @@ -1,18 +1,16 @@ package hudson.plugins.git.extensions.impl; -import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.Test; + public class AuthorInChangelogTest { @Test public void equalsContract() { - EqualsVerifier.forClass(AuthorInChangelog.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(AuthorInChangelog.class).usingGetClass().verify(); } @Test @@ -20,5 +18,4 @@ public void checkToString() { AuthorInChangelog setting = new AuthorInChangelog(); assertThat(setting.toString(), is("AuthorInChangelog{}")); } - } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java index 83b4678d7d..1e6c5e84b0 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java @@ -7,19 +7,17 @@ import hudson.model.View; import hudson.plugins.git.AbstractGitTestCase; import hudson.plugins.git.BranchSpec; - import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitStatusTest; import hudson.util.RunList; import java.io.File; -import org.junit.Assert; -import org.junit.Test; - import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; +import org.junit.Assert; +import org.junit.Test; public class BuildSingleRevisionOnlyTest extends AbstractGitTestCase { @@ -46,7 +44,8 @@ public void waitForAllJobsToComplete() { Logger.getLogger(GitStatusTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); rule.waitForCompletion(run); } catch (InterruptedException ex) { - Logger.getLogger(GitStatusTest.class.getName()).log(Level.SEVERE, "Interrupted waiting for GitStatusTest job", ex); + Logger.getLogger(GitStatusTest.class.getName()) + .log(Level.SEVERE, "Interrupted waiting for GitStatusTest job", ex); } }); } @@ -58,9 +57,7 @@ public void testSingleRevision() throws Exception { branchSpec.add(new BranchSpec("master")); branchSpec.add(new BranchSpec("foo")); branchSpec.add(new BranchSpec("bar")); - FreeStyleProject project = setupProject(branchSpec, false, "", - "","", - "", false, ""); + FreeStyleProject project = setupProject(branchSpec, false, "", "", "", "", false, ""); ((GitSCM) project.getScm()).getExtensions().add(new BuildSingleRevisionOnly()); final String commitFile = "commitFile1"; @@ -78,8 +75,8 @@ public void testSingleRevision() throws Exception { final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile); rule.assertBuildStatusSuccess(build); - boolean result = build.getLog(100).contains( - String.format("Scheduling another build to catch up with %s", project.getName())); + boolean result = build.getLog(100) + .contains(String.format("Scheduling another build to catch up with %s", project.getName())); Assert.assertFalse("Single revision scheduling did not prevent a build of a different revision", result); } @@ -90,9 +87,7 @@ public void testMultiRevision() throws Exception { branchSpec.add(new BranchSpec("master")); branchSpec.add(new BranchSpec("foo")); branchSpec.add(new BranchSpec("bar")); - FreeStyleProject project = setupProject(branchSpec, false, "", - "","", - "", false, ""); + FreeStyleProject project = setupProject(branchSpec, false, "", "", "", "", false, ""); final String commitFile = "commitFile1"; // create the initial master commit diff --git a/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java index 0db3c9bf2d..d30d12971f 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java @@ -1,19 +1,18 @@ package hudson.plugins.git.extensions.impl; -import hudson.plugins.git.ChangelogToBranchOptions; - -import org.junit.Test; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThrows; +import hudson.plugins.git.ChangelogToBranchOptions; +import org.junit.Test; + public class ChangelogToBranchTest { @Test public void checkConstructorIllegalArgument() { ChangelogToBranchOptions nullOptions = null; - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> new ChangelogToBranch(nullOptions)); + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> new ChangelogToBranch(nullOptions)); assertThat(e.getMessage(), containsString("options may not be null")); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java index 1d0822716a..f67c525ee6 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.extensions.impl; +import static org.junit.Assert.*; + import com.cloudbees.plugins.credentials.common.StandardCredentials; import hudson.model.Run; import hudson.model.TaskListener; @@ -12,15 +14,13 @@ import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; public class CheckoutOptionTest { private CheckoutOption option; private static final int INITIAL_TIMEOUT = 10; - public CheckoutOptionTest() { - } + public CheckoutOptionTest() {} @Before public void setUp() { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java index 371a4d3063..683f6a7375 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java @@ -12,6 +12,7 @@ public class CheckoutOptionWorkflowTest { @Rule public JenkinsRule r = new JenkinsRule(); + @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); @@ -21,13 +22,14 @@ public void checkoutTimeout() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" - + " checkout(\n" - + " [$class: 'GitSCM', extensions: [[$class: 'CheckoutOption', timeout: 1234]],\n" - + " userRemoteConfigs: [[url: $/" + sampleRepo + "/$]]]\n" - + " )\n" - + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" - + " echo \"token macro expanded branch is ${tokenBranch}\"\n" - + "}", true)); + + " checkout(\n" + + " [$class: 'GitSCM', extensions: [[$class: 'CheckoutOption', timeout: 1234]],\n" + + " userRemoteConfigs: [[url: $/" + sampleRepo + "/$]]]\n" + + " )\n" + + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + + " echo \"token macro expanded branch is ${tokenBranch}\"\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("# timeout=1234", b); r.waitForMessage("token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java index 82e71d7d08..2e6db959f6 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - public class CleanCheckoutTest { @Test diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java index 920f643072..59b3888a10 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java @@ -4,14 +4,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.PrintStream; - import hudson.EnvVars; import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitSCM; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; +import java.io.PrintStream; import org.jenkinsci.plugins.gitclient.CloneCommand; import org.jenkinsci.plugins.gitclient.FetchCommand; import org.jenkinsci.plugins.gitclient.GitClient; @@ -45,7 +44,7 @@ public CloneOptionDepthTest(int configuredDepth, int usedDepth) { @Parameterized.Parameters(name = "depth: configured={0}, used={1}") public static Object[][] depthCombinations() { - return new Object[][] { { 0, 1 }, { 1, 1 }, { 2, 2 } }; + return new Object[][] {{0, 1}, {1, 1}, {2, 2}}; } @Before diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java index 63cdfce8ca..896e099f15 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.ParametersDefinitionProperty; @@ -12,21 +15,18 @@ import hudson.tasks.BatchFile; import hudson.tasks.Builder; import hudson.tasks.Shell; -import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.jvnet.hudson.test.Issue; - import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Random; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import org.jenkinsci.plugins.gitclient.JGitTool; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.jvnet.hudson.test.Issue; @RunWith(Parameterized.class) public class CloneOptionHonorRefSpecTest extends AbstractGitTestCase { @@ -46,9 +46,9 @@ public static Collection permuteRefSpecVariable() { List values = new ArrayList<>(); String[] keys = { - "JOB_NAME", // Variable set by Jenkins - (isWindows() ? "USERNAME" : "USER"), // Variable set by the operating system - "USER_SELECTED_BRANCH_NAME" // Parametrised build param + "JOB_NAME", // Variable set by Jenkins + (isWindows() ? "USERNAME" : "USER"), // Variable set by the operating system + "USER_SELECTED_BRANCH_NAME" // Parametrised build param }; for (String refSpecName : keys) { @@ -74,8 +74,7 @@ public void setUp() throws Exception { // Setup job beforehand to get expected value of the environment variable project = createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( - new StringParameterDefinition("USER_SELECTED_BRANCH_NAME", "user_branch") - )); + new StringParameterDefinition("USER_SELECTED_BRANCH_NAME", "user_branch"))); project.getBuildersList().add(createEnvEchoBuilder(refSpecName)); final FreeStyleBuild b = rule.buildAndAssertSuccess(project); @@ -104,8 +103,9 @@ public void setUp() throws Exception { public void testRefSpecWithExpandedVariables() throws Exception { if (refSpecExpectedValue == null || refSpecExpectedValue.isEmpty()) { /* Test does not support an empty or null expected value. - Skip the test if the expected value is empty or null */ - System.out.println("*** testRefSpecWithExpandedVariables empty expected value for '" + refSpecName + "' ***"); + Skip the test if the expected value is empty or null */ + System.out.println( + "*** testRefSpecWithExpandedVariables empty expected value for '" + refSpecName + "' ***"); return; } // Create initial commit @@ -122,7 +122,8 @@ public void testRefSpecWithExpandedVariables() throws Exception { repos.add(new UserRemoteConfig( testRepo.gitDir.getAbsolutePath(), "origin", - "+refs/heads/${" + refSpecName + "}:refs/remotes/origin/${" + refSpecName + "}", null)); + "+refs/heads/${" + refSpecName + "}:refs/remotes/origin/${" + refSpecName + "}", + null)); /* Use the variable or its value as the branch name. * Same result expected in either case. @@ -131,8 +132,10 @@ public void testRefSpecWithExpandedVariables() throws Exception { GitSCM scm = new GitSCM( repos, Collections.singletonList(new BranchSpec(branchName)), - false, Collections.emptyList(), - null, random.nextBoolean() ? JGitTool.MAGIC_EXENAME : null, + false, + Collections.emptyList(), + null, + random.nextBoolean() ? JGitTool.MAGIC_EXENAME : null, Collections.emptyList()); project.setScm(scm); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java index 675a3b0818..a8a3975f8f 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java @@ -3,15 +3,13 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import java.io.IOException; -import java.util.Set; - -import hudson.model.Result; import hudson.model.FreeStyleProject; +import hudson.model.Result; import hudson.plugins.git.TestGitRepo; -import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.extensions.GitSCMExtension; - +import hudson.plugins.git.extensions.GitSCMExtensionTest; +import java.io.IOException; +import java.util.Set; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; @@ -45,11 +43,15 @@ public void cloningShouldNotFetchTags() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); repo.tag("v0.0.1", "a tag that should never be fetched"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect a change after initial commit", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS); - assertTrue("there should no tags have been cloned from remote", allTagsInProjectWorkspace().isEmpty()); + assertTrue( + "there should no tags have been cloned from remote", + allTagsInProjectWorkspace().isEmpty()); } @Test @@ -57,17 +59,23 @@ public void detectNoChangeAfterCreatingATag() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect a change after initial commit", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS); repo.tag("v0.0.1", "a tag that should never be fetched"); - assertFalse("scm polling should not detect a change after creating a tag", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect a change after creating a tag", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS); - assertTrue("there should no tags have been fetched from remote", allTagsInProjectWorkspace().isEmpty()); + assertTrue( + "there should no tags have been fetched from remote", + allTagsInProjectWorkspace().isEmpty()); } private Set allTagsInProjectWorkspace() throws IOException, InterruptedException { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java index 4778c9e8c7..d0a4a40295 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java @@ -2,15 +2,14 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import hudson.model.Result; + import hudson.model.FreeStyleProject; +import hudson.model.Result; import hudson.plugins.git.TestGitRepo; -import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.extensions.GitSCMExtension; - +import hudson.plugins.git.extensions.GitSCMExtensionTest; import java.io.IOException; import java.util.Set; - import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; @@ -44,11 +43,16 @@ public void evenShallowCloningFetchesTagsByDefault() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); repo.tag(tagName, "a tag that should be fetched by default"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect a change after initial commit", + project.poll(listener).hasChanges()); build(project, Result.SUCCESS); - assertEquals("tag " + tagName + " should have been cloned from remote", 1, tagsInProjectWorkspaceWithName(tagName).size()); + assertEquals( + "tag " + tagName + " should have been cloned from remote", + 1, + tagsInProjectWorkspaceWithName(tagName).size()); } private Set tagsInProjectWorkspaceWithName(String tagPattern) throws IOException, InterruptedException { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java index e10f6e91f2..dc0bf6d414 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java @@ -1,10 +1,11 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.plugins.git.extensions.GitClientType; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.Test; public class CloneOptionTest { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java b/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java index 341ae31b5c..25ec14db0d 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java @@ -4,7 +4,6 @@ import hudson.plugins.git.extensions.FakeGitSCMExtension; import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; - import org.kohsuke.stapler.DataBoundConstructor; /** @@ -13,21 +12,19 @@ public class EnforceGitClient extends FakeGitSCMExtension { GitClientType clientType = GitClientType.ANY; - + public EnforceGitClient set(GitClientType type) { this.clientType = type; return this; } - + @Override - public GitClientType getRequiredClient() - { + public GitClientType getRequiredClient() { return clientType; } @DataBoundConstructor - public EnforceGitClient() { - } + public EnforceGitClient() {} @Extension public static class DescriptorImpl extends GitSCMExtensionDescriptor { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java b/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java index a34b6d30c2..2d8075892c 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java @@ -7,8 +7,6 @@ public class GitLFSPullTest { @Test public void equalsContract() { - EqualsVerifier.forClass(GitLFSPull.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(GitLFSPull.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java b/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java index c8816c0e9e..3f70114798 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java @@ -7,8 +7,6 @@ public class IgnoreNotifyCommitTest { @Test public void equalsContract() { - EqualsVerifier.forClass(IgnoreNotifyCommit.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(IgnoreNotifyCommit.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java index a8f046d5f5..2b889cd933 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java @@ -1,18 +1,16 @@ package hudson.plugins.git.extensions.impl; -import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.Test; + public class LocalBranchTest { @Test public void equalsContract() { - EqualsVerifier.forClass(LocalBranch.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(LocalBranch.class).usingGetClass().verify(); } @Test diff --git a/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java b/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java index e3764a327e..7275d9ba92 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java @@ -44,8 +44,7 @@ public void publish(LogRecord lr) { } @Override - public void flush() { - } + public void flush() {} @Override public void close() throws SecurityException { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java index b0a072d9d4..b7e597a487 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java @@ -1,54 +1,64 @@ package hudson.plugins.git.extensions.impl; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.model.*; import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * @author Kanstantsin Shautsou */ public class MessageExclusionTest extends GitSCMExtensionTest { - protected FreeStyleProject project; - protected TestGitRepo repo; + protected FreeStyleProject project; + protected TestGitRepo repo; - @Override - protected GitSCMExtension getExtension() { - return new MessageExclusion("(?s).*\\[maven-release-plugin\\].*"); - } + @Override + protected GitSCMExtension getExtension() { + return new MessageExclusion("(?s).*\\[maven-release-plugin\\].*"); + } - @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); - project = setupBasicProject(repo); - } + @Override + public void before() throws Exception { + repo = new TestGitRepo("repo", tmp.newFolder(), listener); + project = setupBasicProject(repo); + } - @Test - public void test() throws Exception { - repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); + @Test + public void test() throws Exception { + repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue( + "scm polling should detect a change after initial commit", + project.poll(listener).hasChanges()); - build(project, Result.SUCCESS); + build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); - repo.commit("repo-init", repo.janeDoe, " [maven-release-plugin] excluded message commit"); + repo.commit("repo-init", repo.janeDoe, " [maven-release-plugin] excluded message commit"); - assertFalse("scm polling should not detect excluded message", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect excluded message", + project.poll(listener).hasChanges()); - repo.commit("repo-init", repo.janeDoe, "first line in excluded commit\nsecond\nthird [maven-release-plugin]\n"); + repo.commit("repo-init", repo.janeDoe, "first line in excluded commit\nsecond\nthird [maven-release-plugin]\n"); - assertFalse("scm polling should not detect multiline message", project.poll(listener).hasChanges()); + assertFalse( + "scm polling should not detect multiline message", + project.poll(listener).hasChanges()); - // should be enough, but let's test more + // should be enough, but let's test more - build(project, Result.SUCCESS); + build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); - } + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java index b8799f51ec..9d1738c096 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java @@ -1,24 +1,21 @@ package hudson.plugins.git.extensions.impl; -import hudson.model.FreeStyleProject; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import hudson.model.FreeStyleProject; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.util.BuildData; - import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; - import org.mockito.Mockito; // NOTE: isRevExcluded generally returns null instead of false @@ -36,7 +33,6 @@ public void before() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); project = setupBasicProject(repo); } - } public static class NoRulesTest extends PathRestrictionExtensionTest { @@ -49,7 +45,9 @@ protected GitSCMExtension getExtension() { @Test public void test() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "bar/bar.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } @@ -63,11 +61,12 @@ protected GitSCMExtension getExtension() { @Test public void test() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>()); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class BasicExcludeTest extends PathRestrictionExtensionTest { @Override @@ -78,13 +77,17 @@ protected GitSCMExtension getExtension() { @Test public void testMiss() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test public void testMatch() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } @@ -98,17 +101,20 @@ protected GitSCMExtension getExtension() { @Test public void testMatch() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test public void testMiss() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class MultiExcludeTest extends PathRestrictionExtensionTest { @Override @@ -119,21 +125,33 @@ protected GitSCMExtension getExtension() { @Test public void testAccept() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "foo.foo", "README.mdown"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("docs.txt", "more-docs.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("a/really/long/path/file.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test public void testReject() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/bar.txt", "foo.bax"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/docs.txt", "bar/more-docs.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } @@ -146,24 +164,39 @@ protected GitSCMExtension getExtension() { @Test public void testAccept() throws Exception { - GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "something/else"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + GitChangeSet commit = + new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "something/else"))); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "foo.foo", "README.mdown"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("docs.txt", "qux/more-docs.txt"))); - assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertNull(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test public void testReject() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/bar.txt", "bar.bar", "README.mdown"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("docs.txt", "more-docs.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("a/really/long/path/file.txt"))); - assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); + assertTrue(getExtension() + .isRevExcluded( + (hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java index 7f784ed73a..fce8057019 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.extensions.impl; +import static org.junit.Assert.*; + import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; @@ -14,19 +16,17 @@ import org.jenkinsci.plugins.gitclient.MergeCommand; import org.junit.Test; -import static org.junit.Assert.*; - /** * @author dalvizu */ -public class PreBuildMergeTest extends GitSCMExtensionTest -{ +public class PreBuildMergeTest extends GitSCMExtensionTest { private FreeStyleProject project; private TestGitRepo repo; private String MASTER_FILE = "commitFileBase"; + @Override public void before() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); project = setupBasicProject(repo); @@ -45,7 +45,7 @@ public void testBasicPreMerge() throws Exception { public void testFailedMerge() throws Exception { FreeStyleBuild firstBuild = build(project, Result.SUCCESS); assertEquals(GitSCM.class, project.getScm().getClass()); - GitSCM gitSCM = (GitSCM)project.getScm(); + GitSCM gitSCM = (GitSCM) project.getScm(); BuildData buildData = gitSCM.getBuildData(firstBuild); assertNotNull("Build data not found", buildData); assertEquals(firstBuild.getNumber(), buildData.lastBuild.getBuildNumber()); @@ -57,37 +57,54 @@ public void testFailedMerge() throws Exception { // pretend we merged and published it successfully repo.git.deleteBranch("integration"); repo.git.checkoutBranch("integration", "master"); - repo.commit(MASTER_FILE, "new content on integration branch", repo.johnDoe, repo.johnDoe, "Commit which should fail!"); + repo.commit( + MASTER_FILE, + "new content on integration branch", + repo.johnDoe, + repo.johnDoe, + "Commit which should fail!"); repo.git.checkout().ref("master").execute(); // make a new commit in master branch, this commit should not merge cleanly! - assertFalse("SCM polling should not detect any more changes after build", project.poll(listener).hasChanges()); - String conflictSha1 = repo.commit(MASTER_FILE, "new content - expect a merge conflict!", repo.johnDoe, repo.johnDoe, "Commit which should fail!"); + assertFalse( + "SCM polling should not detect any more changes after build", + project.poll(listener).hasChanges()); + String conflictSha1 = repo.commit( + MASTER_FILE, + "new content - expect a merge conflict!", + repo.johnDoe, + repo.johnDoe, + "Commit which should fail!"); assertTrue("SCM polling should detect changes", project.poll(listener).hasChanges()); FreeStyleBuild secondBuild = build(project, Result.FAILURE); - assertEquals(secondBuild.getNumber(), gitSCM.getBuildData(secondBuild).lastBuild.getBuildNumber()); + assertEquals( + secondBuild.getNumber(), + gitSCM.getBuildData(secondBuild).lastBuild.getBuildNumber()); // buildData should mark this as built - assertEquals(conflictSha1, gitSCM.getBuildData(secondBuild).lastBuild.getMarked().getSha1String()); - assertEquals(conflictSha1, gitSCM.getBuildData(secondBuild).lastBuild.getRevision().getSha1String()); + assertEquals( + conflictSha1, + gitSCM.getBuildData(secondBuild).lastBuild.getMarked().getSha1String()); + assertEquals( + conflictSha1, + gitSCM.getBuildData(secondBuild).lastBuild.getRevision().getSha1String()); // Check to see that build data is not corrupted (JENKINS-44037) - assertEquals(firstBuild.getNumber(), gitSCM.getBuildData(firstBuild).lastBuild.getBuildNumber()); + assertEquals( + firstBuild.getNumber(), + gitSCM.getBuildData(firstBuild).lastBuild.getBuildNumber()); assertEquals(firstMarked, gitSCM.getBuildData(firstBuild).lastBuild.getMarked()); assertEquals(firstRevision, gitSCM.getBuildData(firstBuild).lastBuild.getRevision()); } @Test public void equalsContract() { - EqualsVerifier.forClass(PreBuildMerge.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(PreBuildMerge.class).usingGetClass().verify(); } @Override protected GitSCMExtension getExtension() { - return new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", - MergeCommand.GitPluginFastForwardMode.FF)); + return new PreBuildMerge( + new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF)); } - } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java index ee7dc7170a..db01be31dd 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java @@ -7,8 +7,6 @@ public class PruneStaleBranchTest { @Test public void equalsContract() { - EqualsVerifier.forClass(PruneStaleBranch.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(PruneStaleBranch.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java index 2fda95897e..bc80a648b7 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java @@ -24,11 +24,16 @@ */ package hudson.plugins.git.extensions.impl; +import hudson.EnvVars; +import hudson.FilePath; +import hudson.Functions; +import hudson.model.Result; +import hudson.model.TaskListener; +import hudson.plugins.git.GitSCM; +import hudson.util.LogTaskListener; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; - -import hudson.plugins.git.GitSCM; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.TestCliGitAPIImpl; @@ -44,17 +49,11 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Functions; -import hudson.model.Result; -import hudson.model.TaskListener; -import hudson.util.LogTaskListener; - public class PruneStaleTagPipelineTest { @Rule public TemporaryFolder fileRule = new TemporaryFolder(); + @Rule public JenkinsRule j = new JenkinsRule(); @@ -91,16 +90,18 @@ public void verify_that_local_tag_is_pruned_when_not_exist_on_remote_using_pipel FilePath workspace = j.jenkins.getWorkspaceFor(job); String remoteURL = "file://" + remoteRepo.toURI().getPath(); - job.setDefinition(new CpsFlowDefinition("" - + " node {\n" - + " checkout([$class: 'GitSCM',\n" - + " branches: [[name: '*/master']],\n" - + " extensions: [pruneTags(true)],\n" - + " userRemoteConfigs: [[url: '" + remoteURL + "']]\n" - + " ])\n" - + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" - + " echo \"token macro expanded branch is ${tokenBranch}\"\n" - + " }\n", true)); + job.setDefinition(new CpsFlowDefinition( + "" + + " node {\n" + + " checkout([$class: 'GitSCM',\n" + + " branches: [[name: '*/master']],\n" + + " extensions: [pruneTags(true)],\n" + + " userRemoteConfigs: [[url: '" + remoteURL + "']]\n" + + " ])\n" + + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + + " echo \"token macro expanded branch is ${tokenBranch}\"\n" + + " }\n", + true)); // first run clone the repository WorkflowRun r = job.scheduleBuild2(0).waitForStart(); @@ -135,5 +136,4 @@ private GitClient initRepository(File workspace) throws Exception { remoteClient.commit("initial commit"); return remoteClient; } - } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java index a6e071917d..f1457f216a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java @@ -24,13 +24,21 @@ */ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import hudson.EnvVars; +import hudson.Functions; +import hudson.model.Run; +import hudson.model.TaskListener; +import hudson.plugins.git.GitSCM; +import hudson.util.LogTaskListener; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; - import nl.jqno.equalsverifier.EqualsVerifier; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.gitclient.GitClient; @@ -41,17 +49,6 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; - -import hudson.EnvVars; -import hudson.Functions; -import hudson.model.Run; -import hudson.model.TaskListener; -import hudson.plugins.git.GitSCM; -import hudson.util.LogTaskListener; - public class PruneStaleTagTest { @Rule @@ -84,21 +81,30 @@ public void verify_local_tag_is_pruned_if_different_than_on_remote() throws Exce remoteClient.tag(tagName, tagComment); // clone remote repository to workspace - GitClient localClient = cloneRepository(remoteRepo); + GitClient localClient = cloneRepository(remoteRepo); GitSCM scm = new GitSCM(localClient.getRemoteUrl("origin")); PruneStaleTag extension = new PruneStaleTag(true); // get remote SHA1 for the tag - String remoteTagHash = remoteClient.getTags().stream().filter(t -> tagName.equals(t.getName())).findFirst().get().getSHA1String(); + String remoteTagHash = remoteClient.getTags().stream() + .filter(t -> tagName.equals(t.getName())) + .findFirst() + .get() + .getSHA1String(); FileUtils.touch(new File(localClient.getWorkTree().getRemote(), "localTest")); localClient.add("localTest"); localClient.commit("more commits"); localClient.deleteTag(tagName); localClient.tag(tagName, tagComment); - String localHashTag = localClient.getTags().stream().filter(t -> tagName.equals(t.getName())).findFirst().get().getSHA1String(); - Assert.assertNotEquals("pre validation failed, local tag must not be the same than remote", remoteTagHash, localHashTag); + String localHashTag = localClient.getTags().stream() + .filter(t -> tagName.equals(t.getName())) + .findFirst() + .get() + .getSHA1String(); + Assert.assertNotEquals( + "pre validation failed, local tag must not be the same than remote", remoteTagHash, localHashTag); extension.decorateFetchCommand(scm, run, localClient, listener, null); Assert.assertFalse("local tag differ from remote tag and is not pruned", localClient.tagExists(tagName)); @@ -117,7 +123,7 @@ public void verify_do_nothing_when_remote_tag_do_not_exist_locally() throws Exce GitClient remoteClient = initRepository(remoteRepo); // clone remote repository to workspace - GitClient localClient = cloneRepository(remoteRepo); + GitClient localClient = cloneRepository(remoteRepo); GitSCM scm = new GitSCM(localClient.getRemoteUrl("origin")); PruneStaleTag extension = new PruneStaleTag(true); @@ -146,7 +152,7 @@ public void verify_that_local_tag_is_not_pruned_when_exist_on_remote() throws Ex remoteClient.tag(tagName, tagComment); // clone remote repository to workspace - GitClient localClient = cloneRepository(remoteRepo); + GitClient localClient = cloneRepository(remoteRepo); GitSCM scm = new GitSCM(localClient.getRemoteUrl("origin")); PruneStaleTag extension = new PruneStaleTag(true); @@ -171,7 +177,7 @@ public void verify_that_local_tag_is_pruned_when_not_exist_on_remote() throws Ex remoteClient.tag(tagName, tagComment); // clone remote repository to workspace - GitClient localClient = cloneRepository(remoteRepo); + GitClient localClient = cloneRepository(remoteRepo); GitSCM scm = new GitSCM(localClient.getRemoteUrl("origin")); PruneStaleTag extension = new PruneStaleTag(true); @@ -190,7 +196,7 @@ public void verify_fetch_do_not_prune_local_branches() throws Exception { initRepository(remoteRepo); // clone remote repository to workspace - GitClient localClient = cloneRepository(remoteRepo); + GitClient localClient = cloneRepository(remoteRepo); // create a local branch that should not be pruned with tags String branchName = "localBranch"; @@ -201,7 +207,9 @@ public void verify_fetch_do_not_prune_local_branches() throws Exception { PruneStaleTag extension = new PruneStaleTag(true); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertTrue("Local branches must not be pruned", localClient.getBranches().stream().anyMatch(b -> branchName.equals(b.getName()))); + Assert.assertTrue( + "Local branches must not be pruned", + localClient.getBranches().stream().anyMatch(b -> branchName.equals(b.getName()))); } private GitClient newGitClient(File localRepo) { diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java index 7a18475882..8faf98d96a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java @@ -7,8 +7,6 @@ public class SparseCheckoutPathTest { @Test public void equalsContract() { - EqualsVerifier.forClass(SparseCheckoutPath.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(SparseCheckoutPath.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java index 5e8ca27aae..916c333b20 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java @@ -23,27 +23,25 @@ */ package hudson.plugins.git.extensions.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; import com.cloudbees.plugins.credentials.common.StandardCredentials; import hudson.model.Run; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.util.LogTaskListener; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import nl.jqno.equalsverifier.EqualsVerifier; import org.jenkinsci.plugins.gitclient.CheckoutCommand; import org.jenkinsci.plugins.gitclient.CloneCommand; import org.jenkinsci.plugins.gitclient.GitClient; - -import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; - public class SparseCheckoutPathsTest { private final SparseCheckoutPaths emptySparseCheckoutPaths; @@ -187,6 +185,5 @@ public CheckoutCommand lfsCredentials(StandardCredentials sc) { public void execute() throws GitException, InterruptedException { throw new UnsupportedOperationException("Not supported yet."); } - } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java index 42b2ae9906..73f37df304 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java @@ -4,14 +4,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.PrintStream; - import hudson.EnvVars; import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitSCM; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; +import java.io.PrintStream; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.SubmoduleUpdateCommand; import org.junit.Before; @@ -39,7 +38,7 @@ public SubmoduleOptionDepthTest(int configuredDepth, int usedDepth) { @Parameterized.Parameters(name = "depth: configured={0}, used={1}") public static Object[][] depthCombinations() { - return new Object[][] { { 0, 1 }, { 1, 1 }, { 2, 2 } }; + return new Object[][] {{0, 1}, {1, 1}, {2, 2}}; } @Before diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java index dbd659b760..a3c283855c 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java @@ -1,30 +1,25 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThrows; + import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; - import java.io.IOException; - import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; - import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.UnsupportedCommand; - import org.junit.Before; import org.junit.Test; - import org.jvnet.hudson.test.Issue; import org.mockito.Mockito; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThrows; - public class SubmoduleOptionTest { private SubmoduleOption submoduleOption; @@ -37,7 +32,8 @@ public class SubmoduleOptionTest { private static final Integer SUBMODULES_TIMEOUT = null; private SubmoduleOption newSubmoduleOption() { - return new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + return new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -68,7 +64,8 @@ public void testSubmoduleUpdateThrowsIOException() throws Exception { Mockito.when(client.hasGitModules()).thenReturn(true); Mockito.when(client.submoduleUpdate()).thenThrow(new GitException("a git exception")); - Exception e = assertThrows(IOException.class, () -> submoduleOption.onCheckoutCompleted(scm, build, client, listener)); + Exception e = assertThrows( + IOException.class, () -> submoduleOption.onCheckoutCompleted(scm, build, client, listener)); assertThat(e.getMessage(), is("Could not perform submodule update")); } @@ -92,7 +89,8 @@ public void testIsDisableSubmodules() { @Test public void testIsDisableSubmodulesTrue() { - submoduleOption = new SubmoduleOption(true, + submoduleOption = new SubmoduleOption( + true, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -108,7 +106,8 @@ public void testIsRecursiveSubmodules() { @Test public void testIsRecursiveSubmodulesTrue() { - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, true, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -124,7 +123,8 @@ public void testIsTrackingSubmodules() { @Test public void testIsTrackingSubmodulesTrue() { - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, true, SUBMODULES_REFERENCE_REPOSITORY, @@ -140,7 +140,8 @@ public void testIsParentCredentials() { @Test public void testIsParentCredentialsTrue() { - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -157,7 +158,8 @@ public void testGetReference() { @Test public void testGetReferenceNotNull() { final String referenceRepoDirName = "/repo.git"; - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, referenceRepoDirName, @@ -174,7 +176,8 @@ public void testGetTimeout() { @Test public void testGetTimeoutNotNull() { Integer timeout = 3; - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -229,33 +232,37 @@ public void testSetThreads() { @Test public void testToString() { - assertThat(submoduleOption.toString(), is("SubmoduleOption{" - + "disableSubmodules=false" - + ", recursiveSubmodules=false" - + ", trackingSubmodules=false" - + ", reference='null'" - + ", parentCredentials=false" - + ", timeout=null" - + ", shallow=false" - + ", depth=null" - + ", threads=null" - + '}')); + assertThat( + submoduleOption.toString(), + is("SubmoduleOption{" + + "disableSubmodules=false" + + ", recursiveSubmodules=false" + + ", trackingSubmodules=false" + + ", reference='null'" + + ", parentCredentials=false" + + ", timeout=null" + + ", shallow=false" + + ", depth=null" + + ", threads=null" + + '}')); } @Test public void testToStringDataBoundConstructor() { submoduleOption = new SubmoduleOption(); - assertThat(submoduleOption.toString(), is("SubmoduleOption{" - + "disableSubmodules=false" - + ", recursiveSubmodules=false" - + ", trackingSubmodules=false" - + ", reference='null'" - + ", parentCredentials=false" - + ", timeout=null" - + ", shallow=false" - + ", depth=null" - + ", threads=null" - + '}')); + assertThat( + submoduleOption.toString(), + is("SubmoduleOption{" + + "disableSubmodules=false" + + ", recursiveSubmodules=false" + + ", trackingSubmodules=false" + + ", reference='null'" + + ", parentCredentials=false" + + ", timeout=null" + + ", shallow=false" + + ", depth=null" + + ", threads=null" + + '}')); } @Test @@ -274,7 +281,8 @@ public void testDetermineSupportForJGit() { public void testDetermineSupportForJGitRecursiveSubmodules() { /* JGit was incorrectly used when submodule option was added with only recursive submodule checked. */ GitSCM scm = new GitSCM("https://github.com/jenkinsci/git-plugin"); - submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, + submoduleOption = new SubmoduleOption( + DISABLE_SUBMODULES_FALSE, true, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, diff --git a/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java index d0c1dda03b..7ff1046c32 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.extensions.impl; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.plugins.git.TestGitRepo; @@ -7,48 +10,52 @@ import hudson.plugins.git.extensions.GitSCMExtensionTest; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * @author Kanstantsin Shautsou */ -public class UserExclusionTest extends GitSCMExtensionTest{ - - FreeStyleProject project; - TestGitRepo repo; +public class UserExclusionTest extends GitSCMExtensionTest { - @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); - project = setupBasicProject(repo); - } + FreeStyleProject project; + TestGitRepo repo; - @Override - protected GitSCMExtension getExtension() { - return new UserExclusion("Jane Doe"); - } + @Override + public void before() throws Exception { + repo = new TestGitRepo("repo", tmp.newFolder(), listener); + project = setupBasicProject(repo); + } - @Test - public void test() throws Exception { + @Override + protected GitSCMExtension getExtension() { + return new UserExclusion("Jane Doe"); + } - repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); + @Test + public void test() throws Exception { - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - build(project, Result.SUCCESS); + assertTrue( + "scm polling should detect a change after initial commit", + project.poll(listener).hasChanges()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + build(project, Result.SUCCESS); - repo.commit("repo-init", repo.janeDoe, "excluded user commit"); + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); - assertFalse("scm polling should ignore excluded user", project.poll(listener).hasChanges()); + repo.commit("repo-init", repo.janeDoe, "excluded user commit"); - // should be enough, but let's test more + assertFalse( + "scm polling should ignore excluded user", + project.poll(listener).hasChanges()); - build(project, Result.SUCCESS); + // should be enough, but let's test more - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + build(project, Result.SUCCESS); - } + assertFalse( + "scm polling should not detect any more changes after build", + project.poll(listener).hasChanges()); + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java index f702cb0874..5f9603d2d8 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import hudson.EnvVars; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; @@ -14,10 +17,7 @@ import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - -public class UserIdentityTest extends GitSCMExtensionTest { +public class UserIdentityTest extends GitSCMExtensionTest { TestGitRepo repo; GitClient git; @@ -35,7 +35,9 @@ protected GitSCMExtension getExtension() { @Test public void testUserIdentity() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); - git = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()).in(repo.gitDir).getClient(); + git = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()) + .in(repo.gitDir) + .getClient(); FreeStyleProject projectWithMaster = setupBasicProject(repo); git.commit("First commit"); @@ -48,7 +50,7 @@ public void testUserIdentity() throws Exception { @Test @WithoutJenkins - public void testGetNameAndEmail(){ + public void testGetNameAndEmail() { UserIdentity userIdentity = new UserIdentity("Jane Doe", "janeDoe@xyz.com"); assertThat("Jane Doe", is(userIdentity.getName())); @@ -58,8 +60,6 @@ public void testGetNameAndEmail(){ @Test @WithoutJenkins public void equalsContract() { - EqualsVerifier.forClass(UserIdentity.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(UserIdentity.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java b/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java index 6c18dfdc9a..6471589135 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.extensions.impl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; + import hudson.EnvVars; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; @@ -14,9 +17,6 @@ import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; - public class WipeWorkspaceTest extends GitSCMExtensionTest { TestGitRepo repo; @@ -51,8 +51,6 @@ public void testWipeWorkspace() throws Exception { @Test @WithoutJenkins public void equalsContract() { - EqualsVerifier.forClass(WipeWorkspace.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(WipeWorkspace.class).usingGetClass().verify(); } } diff --git a/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java b/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java index 459b468860..4e642c71b7 100644 --- a/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java @@ -31,20 +31,32 @@ import hudson.plugins.git.extensions.impl.PreBuildMerge; import java.util.Collections; import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.junit.Test; import org.junit.Rule; +import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; public class PreBuildMergeOptionsTest { - @Rule public JenkinsRule r = new JenkinsRule(); + @Rule + public JenkinsRule r = new JenkinsRule(); @Issue("JENKINS-9843") - @Test public void exporting() throws Exception { + @Test + public void exporting() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); - p.setScm(new GitSCM(Collections.singletonList(new UserRemoteConfig("http://wherever/thing.git", "repo", null, null)), null, null, null, null, null, Collections.singletonList(new PreBuildMerge(new UserMergeOptions("repo", "master", MergeCommand.Strategy.DEFAULT.name(), MergeCommand.GitPluginFastForwardMode.FF))))); + p.setScm(new GitSCM( + Collections.singletonList(new UserRemoteConfig("http://wherever/thing.git", "repo", null, null)), + null, + null, + null, + null, + null, + Collections.singletonList(new PreBuildMerge(new UserMergeOptions( + "repo", + "master", + MergeCommand.Strategy.DEFAULT.name(), + MergeCommand.GitPluginFastForwardMode.FF))))); r.createWebClient().goToXml(p.getUrl() + "api/xml?depth=2"); } - } diff --git a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java index 9d6a73fc5f..96f1236af8 100644 --- a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java +++ b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java @@ -1,10 +1,17 @@ package hudson.plugins.git.security; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.util.NameValuePair; import hudson.plugins.git.ApiTokenPropertyConfiguration; +import java.util.Collection; +import java.util.Collections; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.junit.Before; @@ -13,14 +20,6 @@ import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; -import java.util.Collection; -import java.util.Collections; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class ApiTokenPropertyConfigurationTest { @Rule @@ -40,7 +39,8 @@ public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception try (JenkinsRule.WebClient wc = j.createWebClient()) { wc.login("bob"); WebRequest req = new WebRequest( - wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/generate"), HttpMethod.POST); + wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/generate"), + HttpMethod.POST); req.setRequestBody("{\"apiTokenName\":\"test\"}"); wc.setThrowExceptionOnFailingStatusCode(false); @@ -55,7 +55,9 @@ public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception public void adminPermissionsRequiredToRevokeApiTokens() throws Exception { try (JenkinsRule.WebClient wc = j.createWebClient()) { wc.login("bob"); - WebRequest req = new WebRequest(wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/revoke"), HttpMethod.POST); + WebRequest req = new WebRequest( + wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/revoke"), + HttpMethod.POST); wc.setThrowExceptionOnFailingStatusCode(false); WebResponse res = wc.getPage(req).getWebResponse(); @@ -70,45 +72,41 @@ public void testBasicGenerationAndRevocation() throws Exception { try (JenkinsRule.WebClient wc = j.createWebClient()) { wc.login("alice"); WebRequest generateReq = new WebRequest( - wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/generate"), HttpMethod.POST); + wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/generate"), + HttpMethod.POST); generateReq.setRequestParameters(Collections.singletonList(new NameValuePair("apiTokenName", "token"))); - String uuid = JSONObject.fromObject(wc.getPage(generateReq).getWebResponse().getContentAsString()).getJSONObject("data").getString("uuid"); + String uuid = JSONObject.fromObject( + wc.getPage(generateReq).getWebResponse().getContentAsString()) + .getJSONObject("data") + .getString("uuid"); generateReq.setRequestParameters(Collections.singletonList(new NameValuePair("apiTokenName", "nekot"))); - String uuid2 = JSONObject.fromObject(wc.getPage(generateReq).getWebResponse().getContentAsString()).getJSONObject("data").getString("uuid"); - - Collection apiTokens = ApiTokenPropertyConfiguration.get().getApiTokens(); - assertThat(apiTokens, allOf( - iterableWithSize(2), - hasItem( - allOf( - hasProperty("name", is("token")), - hasProperty("uuid", is(uuid)) - ) - ), - hasItem( - allOf( - hasProperty("name", is("nekot")), - hasProperty("uuid", is(uuid2)) - ) - ) - )); + String uuid2 = JSONObject.fromObject( + wc.getPage(generateReq).getWebResponse().getContentAsString()) + .getJSONObject("data") + .getString("uuid"); + + Collection apiTokens = + ApiTokenPropertyConfiguration.get().getApiTokens(); + assertThat( + apiTokens, + allOf( + iterableWithSize(2), + hasItem(allOf(hasProperty("name", is("token")), hasProperty("uuid", is(uuid)))), + hasItem(allOf(hasProperty("name", is("nekot")), hasProperty("uuid", is(uuid2)))))); WebRequest revokeReq = new WebRequest( - wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/revoke"), HttpMethod.POST); + wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/revoke"), + HttpMethod.POST); revokeReq.setRequestParameters(Collections.singletonList(new NameValuePair("apiTokenUuid", uuid))); wc.getPage(revokeReq); apiTokens = ApiTokenPropertyConfiguration.get().getApiTokens(); - assertThat(apiTokens, allOf( - iterableWithSize(1), - hasItem( - allOf( - hasProperty("name", is("nekot")), - hasProperty("uuid", is(uuid2)) - ) - ) - )); + assertThat( + apiTokens, + allOf( + iterableWithSize(1), + hasItem(allOf(hasProperty("name", is("nekot")), hasProperty("uuid", is(uuid2)))))); } } @@ -118,5 +116,4 @@ public void isValidApiTokenReturnsTrueIfGivenApiTokenExists() { assertTrue(ApiTokenPropertyConfiguration.get().isValidApiToken(json.getString("value"))); } - } diff --git a/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java b/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java index 87c2c706c1..b8417962c5 100644 --- a/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java +++ b/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.util; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.AbstractGitRepository; @@ -8,235 +10,237 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; import hudson.plugins.git.extensions.impl.BuildChooserSetting; - +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Collection; +import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; - import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.gitclient.GitClient; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; +import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import static org.junit.Assert.*; -import org.junit.Before; - public class AncestryBuildChooserTest extends AbstractGitRepository { - + private String rootCommit = null; private String ancestorCommit = null; private String fiveDaysAgoCommit = null; private String tenDaysAgoCommit = null; private String twentyDaysAgoCommit = null; - + private final LocalDateTime fiveDaysAgo = LocalDate.now().atStartOfDay().minusDays(5); private final LocalDateTime tenDaysAgo = LocalDate.now().atStartOfDay().minusDays(10); private final LocalDateTime twentyDaysAgo = LocalDate.now().atStartOfDay().minusDays(20); - + private final PersonIdent johnDoe = new PersonIdent("John Doe", "john@example.com"); /* * 20 days old -> O O <- 10 days old * |/ - * ancestor -> O O <- 5 days old + * ancestor -> O O <- 5 days old * \ / * root -> O - * + * * Creates a small repository of 5 commits with different branches and ages. */ @Before public void setUp() throws Exception { Set prevBranches = stringifyBranches(testGitClient.getBranches()); - + testGitClient.commit("Root Commit"); rootCommit = getLastCommitSha1(prevBranches); - + testGitClient.commit("Ancestor Commit"); ancestorCommit = getLastCommitSha1(prevBranches); - + testGitClient.branch("20-days-old-branch"); testGitClient.checkoutBranch("20-days-old-branch", ancestorCommit); - Date twentyDaysAgoDate = Date.from(twentyDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); + Date twentyDaysAgoDate = + Date.from(twentyDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); PersonIdent johnDoeTwentyDaysAgo = new PersonIdent(johnDoe, twentyDaysAgoDate); this.commit("20 days ago commit message", johnDoeTwentyDaysAgo, johnDoeTwentyDaysAgo); twentyDaysAgoCommit = getLastCommitSha1(prevBranches); - + testGitClient.checkout().ref(ancestorCommit).execute(); testGitClient.checkoutBranch("10-days-old-branch", ancestorCommit); - Date tenDaysAgoDate = Date.from(tenDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); + Date tenDaysAgoDate = + Date.from(tenDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); PersonIdent johnDoeTenDaysAgo = new PersonIdent(johnDoe, tenDaysAgoDate); this.commit("10 days ago commit message", johnDoeTenDaysAgo, johnDoeTenDaysAgo); tenDaysAgoCommit = getLastCommitSha1(prevBranches); - + testGitClient.checkout().ref(rootCommit).execute(); testGitClient.checkoutBranch("5-days-old-branch", rootCommit); - Date fiveDaysAgoDate = Date.from(fiveDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); + Date fiveDaysAgoDate = + Date.from(fiveDaysAgo.atZone(ZoneId.systemDefault()).toInstant()); PersonIdent johnDoeFiveDaysAgo = new PersonIdent(johnDoe, fiveDaysAgoDate); this.commit("5 days ago commit message", johnDoeFiveDaysAgo, johnDoeFiveDaysAgo); fiveDaysAgoCommit = getLastCommitSha1(prevBranches); } - + private Set stringifyBranches(Set original) { Set result = new TreeSet<>(); for (Branch branch : original) { result.add(branch.getSHA1String()); } - + return result; } - + private String getLastCommitSha1(Set prevBranches) throws Exception { Set newBranches = stringifyBranches(testGitClient.getBranches()); - + Set difference = new HashSet<>(newBranches); difference.removeAll(prevBranches); - + assertEquals(1, difference.size()); - + String result = difference.iterator().next(); - + prevBranches.clear(); prevBranches.addAll(newBranches); - + return result; } - + // Git Client implementation throws away committer date info so we have to do this manually.. // Copied from JGitAPIImpl.commit(String message) private void commit(String message, PersonIdent author, PersonIdent committer) { try (@SuppressWarnings("deprecation") // Local repository reference - Repository repo = testGitClient.getRepository()) { + Repository repo = testGitClient.getRepository()) { CommitCommand cmd = Git.wrap(repo).commit().setMessage(message); - if (author != null) + if (author != null) { cmd.setAuthor(author); - if (committer != null) + } + if (committer != null) { // cmd.setCommitter(new PersonIdent(committer,new Date())); cmd.setCommitter(committer); + } cmd.call(); } catch (GitAPIException e) { throw new GitException(e); } } - + private List getFilteredTestCandidates(Integer maxAgeInDays, String ancestorCommitSha1) throws Exception { GitSCM gitSCM = new GitSCM("foo"); AncestryBuildChooser chooser = new AncestryBuildChooser(maxAgeInDays, ancestorCommitSha1); gitSCM.getExtensions().add(new BuildChooserSetting(chooser)); assertEquals(maxAgeInDays, chooser.getMaximumAgeInDays()); assertEquals(ancestorCommitSha1, chooser.getAncestorCommitSha1()); - + // mock necessary objects GitClient git = Mockito.spy(this.testGitClient); Mockito.when(git.getRemoteBranches()).thenReturn(this.testGitClient.getBranches()); - + BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.hasBeenBuilt(git.revParse(rootCommit))).thenReturn(false); - + BuildChooserContext context = Mockito.mock(BuildChooserContext.class); Mockito.when(context.getEnvironment()).thenReturn(new EnvVars()); - + TaskListener listener = TaskListener.NULL; - + // get filtered candidates - Collection candidateRevisions = gitSCM.getBuildChooser().getCandidateRevisions(true, "**-days-old-branch", git, listener, buildData, context); - + Collection candidateRevisions = gitSCM.getBuildChooser() + .getCandidateRevisions(true, "**-days-old-branch", git, listener, buildData, context); + // transform revision candidates to sha1 strings List candidateSha1s = - candidateRevisions.stream() - .map(Revision::getSha1String) - .collect(Collectors.toList()); - + candidateRevisions.stream().map(Revision::getSha1String).collect(Collectors.toList()); + return candidateSha1s; } - + @Test public void testFilterRevisionsNoRestriction() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = null; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(3, candidateSha1s.size()); assertTrue(candidateSha1s.contains(fiveDaysAgoCommit)); assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test public void testFilterRevisionsZeroDate() throws Exception { final Integer maxAgeInDays = 0; final String ancestorCommitSha1 = null; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(0, candidateSha1s.size()); } - + @Test public void testFilterRevisionsTenDays() throws Exception { final Integer maxAgeInDays = 10; final String ancestorCommitSha1 = null; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(1, candidateSha1s.size()); assertTrue(candidateSha1s.contains(fiveDaysAgoCommit)); } - + @Test public void testFilterRevisionsThirtyDays() throws Exception { final Integer maxAgeInDays = 30; final String ancestorCommitSha1 = null; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(3, candidateSha1s.size()); assertTrue(candidateSha1s.contains(fiveDaysAgoCommit)); assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test public void testFilterRevisionsBlankAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = ""; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(3, candidateSha1s.size()); assertTrue(candidateSha1s.contains(fiveDaysAgoCommit)); assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test public void testFilterRevisionsNonExistingAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = "This commit sha1 does not exist."; - assertThrows("Invalid sha1 should throw GitException.", GitException.class, + assertThrows( + "Invalid sha1 should throw GitException.", + GitException.class, () -> getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1)); } - + @Test public void testFilterRevisionsExistingAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = ancestorCommit; - + List candidateSha1s = getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1); - + assertEquals(2, candidateSha1s.size()); assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); diff --git a/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java b/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java index bff6e26a87..ccc85f43fc 100644 --- a/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.util; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; - import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertTrue; + +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -77,11 +77,9 @@ public void publish(LogRecord record) { } @Override - public void close() { - } + public void close() {} @Override - public void flush() { - } + public void flush() {} } } diff --git a/src/test/java/hudson/plugins/git/util/BuildDataTest.java b/src/test/java/hudson/plugins/git/util/BuildDataTest.java index f503c5db85..1d6fe05f61 100644 --- a/src/test/java/hudson/plugins/git/util/BuildDataTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildDataTest.java @@ -1,26 +1,24 @@ package hudson.plugins.git.util; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import hudson.model.Api; import hudson.model.Result; import hudson.plugins.git.Branch; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; - import java.util.ArrayList; import java.util.Collection; import java.util.Random; - import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.eclipse.jgit.lib.ObjectId; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -264,7 +262,9 @@ public void testToStringNullSCMBuildData() { @Test public void testToStringNonNullSCMBuildData() { BuildData nonNullSCM = new BuildData("gitless"); - assertThat(nonNullSCM.toString(), endsWith("[scmName=gitless,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); + assertThat( + nonNullSCM.toString(), + endsWith("[scmName=gitless,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test @@ -396,31 +396,32 @@ private void permuteBaseURL(String simpleURL, BuildData simple) { final String TRAILING_SLASH_URL = simpleURL + "/"; BuildData trailingSlash = new BuildData("git-" + TRAILING_SLASH_URL); trailingSlash.addRemoteUrl(TRAILING_SLASH_URL); - assertTrue("Trailing slash not similar to simple URL " + TRAILING_SLASH_URL, - trailingSlash.similarTo(simple)); + assertTrue("Trailing slash not similar to simple URL " + TRAILING_SLASH_URL, trailingSlash.similarTo(simple)); final String TRAILING_SLASHES_URL = TRAILING_SLASH_URL + "//"; BuildData trailingSlashes = new BuildData("git-" + TRAILING_SLASHES_URL); trailingSlashes.addRemoteUrl(TRAILING_SLASHES_URL); - assertTrue("Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL, + assertTrue( + "Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL, trailingSlashes.similarTo(simple)); final String DOT_GIT_URL = simpleURL + ".git"; BuildData dotGit = new BuildData("git-" + DOT_GIT_URL); dotGit.addRemoteUrl(DOT_GIT_URL); - assertTrue("Dot git not similar to simple URL " + DOT_GIT_URL, - dotGit.similarTo(simple)); + assertTrue("Dot git not similar to simple URL " + DOT_GIT_URL, dotGit.similarTo(simple)); final String DOT_GIT_TRAILING_SLASH_URL = DOT_GIT_URL + "/"; BuildData dotGitTrailingSlash = new BuildData("git-" + DOT_GIT_TRAILING_SLASH_URL); dotGitTrailingSlash.addRemoteUrl(DOT_GIT_TRAILING_SLASH_URL); - assertTrue("Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL, + assertTrue( + "Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL, dotGitTrailingSlash.similarTo(dotGit)); final String DOT_GIT_TRAILING_SLASHES_URL = DOT_GIT_TRAILING_SLASH_URL + "///"; BuildData dotGitTrailingSlashes = new BuildData("git-" + DOT_GIT_TRAILING_SLASHES_URL); dotGitTrailingSlashes.addRemoteUrl(DOT_GIT_TRAILING_SLASHES_URL); - assertTrue("Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL, + assertTrue( + "Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL, dotGitTrailingSlashes.similarTo(dotGit)); } @@ -484,7 +485,9 @@ public void testSimilarTo() { BuildData dataSCM = new BuildData("scm"); assertFalse("Object similar to data with SCM name", dataSCM.similarTo(data)); assertTrue("Object with SCM name not similar to data with SCM name", dataSCM.similarTo(new BuildData("abc"))); - assertTrue("Object with SCM name not similar to data with SCM name & empty", dataSCM.similarTo(new BuildData("abc", emptyList))); + assertTrue( + "Object with SCM name not similar to data with SCM name & empty", + dataSCM.similarTo(new BuildData("abc", emptyList))); // Cloned object equals original object BuildData dataClone = data.clone(); diff --git a/src/test/java/hudson/plugins/git/util/BuildTest.java b/src/test/java/hudson/plugins/git/util/BuildTest.java index 73c580da96..353da36fbc 100644 --- a/src/test/java/hudson/plugins/git/util/BuildTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git.util; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.model.Result; import hudson.plugins.git.Revision; import nl.jqno.equalsverifier.EqualsVerifier; @@ -7,9 +10,6 @@ import org.eclipse.jgit.lib.ObjectId; import org.junit.Test; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; - public class BuildTest { private final int BUILD_NUMBER = 1; diff --git a/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java b/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java index fa66a703ce..eaac28c9c8 100644 --- a/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java +++ b/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java @@ -1,5 +1,7 @@ package hudson.plugins.git.util; +import static org.junit.Assert.*; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.AbstractGitRepository; @@ -10,15 +12,14 @@ import java.util.Collection; import java.util.Collections; import java.util.Random; +import jenkins.plugins.git.GitSampleRepoRule; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.RefSpec; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import jenkins.plugins.git.GitSampleRepoRule; import org.mockito.Mockito; public class CandidateRevisionsTest extends AbstractGitRepository { @@ -86,7 +87,8 @@ public void testChooseWithMultipleTag() throws Exception { /* This refspec doesn't clone master branch, don't checkout master */ RefSpec tagsRefSpec = new RefSpec("+refs/tags/tag/*:refs/remotes/origin/tags/tag/*"); - testGitClient2.clone_() + testGitClient2 + .clone_() .refspecs(Collections.singletonList(tagsRefSpec)) .repositoryName("origin") .url(testGitDir.getAbsolutePath()) @@ -98,7 +100,8 @@ public void testChooseWithMultipleTag() throws Exception { assertEquals(commit2, testGitClient2.revParse("tag/b")); assertEquals(commit2, testGitClient2.revParse("tag/c")); - DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM(testGitDir.getAbsolutePath()).getBuildChooser(); + DefaultBuildChooser buildChooser = + (DefaultBuildChooser) new GitSCM(testGitDir.getAbsolutePath()).getBuildChooser(); BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.hasBeenBuilt(testGitClient2.revParse("tag/a"))).thenReturn(true); @@ -108,9 +111,16 @@ public void testChooseWithMultipleTag() throws Exception { BuildChooserContext context = Mockito.mock(BuildChooserContext.class); Mockito.when(context.getEnvironment()).thenReturn(new EnvVars()); - Collection candidateRevisions = buildChooser.getCandidateRevisions(false, "tag/*", testGitClient2, null, buildData, context); + Collection candidateRevisions = + buildChooser.getCandidateRevisions(false, "tag/*", testGitClient2, null, buildData, context); assertEquals(1, candidateRevisions.size()); - String name = candidateRevisions.iterator().next().getBranches().iterator().next().getName(); + String name = candidateRevisions + .iterator() + .next() + .getBranches() + .iterator() + .next() + .getName(); assertTrue("Expected .*/tags/b or .*/tags/c, was '" + name + "'", name.matches("(origin|refs)/tags/tag/[bc]")); } diff --git a/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java b/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java index 1f421cb89e..c7aa65bccf 100644 --- a/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java +++ b/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java @@ -1,15 +1,15 @@ package hudson.plugins.git.util; +import static org.junit.Assert.*; + import hudson.plugins.git.AbstractGitRepository; import hudson.plugins.git.Branch; import hudson.plugins.git.Revision; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; import org.junit.Test; /** @@ -21,35 +21,42 @@ public class CommitTimeComparatorTest extends AbstractGitRepository { public void testSort_OrderIsOldToNew() throws Exception { boolean first = true; // create repository with three commits - for (int i=0; i<3; i++) { - // in Git, the precision of the timestamp is 1 sec, so we need a large delay to produce commits with different timestamps. - if (first) first = false; - else Thread.sleep(1000); + for (int i = 0; i < 3; i++) { + // in Git, the precision of the timestamp is 1 sec, so we need a large delay to produce commits with + // different timestamps. + if (first) { + first = false; + } else { + Thread.sleep(1000); + } commitNewFile("file" + i); testGitClient.branch("branch" + i); } - Map branches = new HashMap<>(); + Map branches = new HashMap<>(); List revs = new ArrayList<>(); for (Branch b : testGitClient.getBranches()) { - if (!b.getName().startsWith("branch")) continue; + if (!b.getName().startsWith("branch")) { + continue; + } Revision r = new Revision(b.getSHA1()); revs.add(r); - branches.put(r,b); + branches.put(r, b); } - assertEquals(3,revs.size()); + assertEquals(3, revs.size()); @SuppressWarnings("deprecation") // Local repository reference org.eclipse.jgit.lib.Repository testRepo = testGitClient.getRepository(); - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { // shuffle, then sort. Collections.shuffle(revs); revs.sort(new CommitTimeComparator(testRepo)); // it should be always branch1, branch2, branch3 - for (int j=0; j<3; j++) - assertEquals("branch"+j, branches.get(revs.get(j)).getName()); + for (int j = 0; j < 3; j++) { + assertEquals("branch" + j, branches.get(revs.get(j)).getName()); + } } } } diff --git a/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java b/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java index e7e42598f4..ea6b2e79a7 100644 --- a/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java +++ b/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java @@ -1,17 +1,17 @@ package hudson.plugins.git.util; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.plugins.git.AbstractGitRepository; import hudson.plugins.git.Branch; -import java.util.Collection; -import java.util.HashSet; - import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; +import java.util.Collection; +import java.util.HashSet; import org.eclipse.jgit.lib.ObjectId; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -29,12 +29,14 @@ public void testChooseGitRevisionToBuildByShaHash() throws Exception { DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); - Collection candidateRevisions = buildChooser.getCandidateRevisions(false, shaHashCommit1, testGitClient, null, null, null); + Collection candidateRevisions = + buildChooser.getCandidateRevisions(false, shaHashCommit1, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(1)); assertThat(candidateRevisions.iterator().next().getSha1String(), is(shaHashCommit1)); - candidateRevisions = buildChooser.getCandidateRevisions(false, "aaa" + shaHashCommit1.substring(3), testGitClient, null, null, null); + candidateRevisions = buildChooser.getCandidateRevisions( + false, "aaa" + shaHashCommit1.substring(3), testGitClient, null, null, null); assertThat(candidateRevisions, is(empty())); } @@ -62,11 +64,12 @@ public void testPreferRemoteBranchInCandidateRevisionsWithWrongOrderInHashSet() DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); Collection candidateRevisions = - buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(2)); Revision firstCandidateRevision = candidateRevisions.iterator().next(); - Branch firstCandidateBranch = firstCandidateRevision.getBranches().iterator().next(); + Branch firstCandidateBranch = + firstCandidateRevision.getBranches().iterator().next(); assertThat(firstCandidateBranch.getName(), is(remoteRef)); } @@ -81,11 +84,12 @@ public void testPreferRemoteBranchInCandidateRevisionsWithCorrectOrderInHashSet( DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); Collection candidateRevisions = - buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(2)); Revision firstCandidateRevision = candidateRevisions.iterator().next(); - Branch firstCandidateBranch = firstCandidateRevision.getBranches().iterator().next(); + Branch firstCandidateBranch = + firstCandidateRevision.getBranches().iterator().next(); assertThat(firstCandidateBranch.getName(), is(remoteRef)); } @@ -101,7 +105,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommit() thro DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); Collection candidateRevisions = - buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(1)); } @@ -117,8 +121,8 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithOri createRefsWithPredefinedOrderInHashSet(localRef, remoteRef); DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); - Collection candidateRevisions - = buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + Collection candidateRevisions = + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(1)); } @@ -126,7 +130,8 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithOri /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRemotesOriginPrefix() throws Exception { + public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRemotesOriginPrefix() + throws Exception { String baseBranchName = "feature/42"; String branchName = "remotes/origin/" + baseBranchName; String localRef = "refs/heads/" + baseBranchName; @@ -135,7 +140,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRem DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); Collection candidateRevisions = - buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(1)); } @@ -152,7 +157,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRef DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); Collection candidateRevisions = - buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); + buildChooser.getCandidateRevisions(false, branchName, testGitClient, null, null, null); assertThat(candidateRevisions, hasSize(1)); } diff --git a/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java b/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java index 234050dac7..90b525dea2 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java @@ -23,6 +23,9 @@ */ package hudson.plugins.git.util; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.EnvVars; import hudson.FilePath; import hudson.model.Label; @@ -33,9 +36,6 @@ import hudson.slaves.DumbSlave; import hudson.util.StreamTaskListener; import java.util.UUID; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; diff --git a/src/test/java/hudson/plugins/git/util/GitUtilsTest.java b/src/test/java/hudson/plugins/git/util/GitUtilsTest.java index a79dad41a8..e96f79565c 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsTest.java @@ -23,6 +23,11 @@ */ package hudson.plugins.git.util; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; + import edu.umd.cs.findbugs.annotations.NonNull; import hudson.EnvVars; import hudson.model.TaskListener; @@ -39,12 +44,8 @@ import java.util.Set; import jenkins.plugins.git.GitSampleRepoRule; import org.eclipse.jgit.lib.ObjectId; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -59,12 +60,7 @@ public class GitUtilsTest { @ClassRule public static TemporaryFolder repoParentFolder = new TemporaryFolder(); - private static final String[] HEAD_BRANCH_NAMES = { - "master", - "sally-2", - "baker-1", - "able-4" - }; + private static final String[] HEAD_BRANCH_NAMES = {"master", "sally-2", "baker-1", "able-4"}; private static final String OLDER_BRANCH_NAME = "older-branch"; private static ObjectId headId = null; @@ -81,11 +77,7 @@ public class GitUtilsTest { private static final String HEAD_TAG_NAME_1 = "head-tag-1"; private static final String HEAD_TAG_NAME_2 = "head-tag-2-annotated"; private final String[] tagNames = { - PRIOR_TAG_NAME_1, - PRIOR_TAG_NAME_2, - HEAD_TAG_NAME_0, - HEAD_TAG_NAME_1, - HEAD_TAG_NAME_2 + PRIOR_TAG_NAME_1, PRIOR_TAG_NAME_2, HEAD_TAG_NAME_0, HEAD_TAG_NAME_1, HEAD_TAG_NAME_2 }; private static List branchSpecList = null; diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java index e6b8ccee19..2cadc2bdbb 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java @@ -1,5 +1,30 @@ package jenkins.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.cloudbees.hudson.plugins.folder.Folder; import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsProvider; @@ -16,13 +41,13 @@ import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitException; -import hudson.plugins.git.UserRemoteConfig; -import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit; -import hudson.scm.SCMRevisionState; import hudson.plugins.git.GitSCM; +import hudson.plugins.git.UserRemoteConfig; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.impl.BuildChooserSetting; +import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit; import hudson.plugins.git.extensions.impl.LocalBranch; +import hudson.scm.SCMRevisionState; import hudson.util.StreamTaskListener; import java.io.File; import java.util.ArrayList; @@ -38,18 +63,10 @@ import jenkins.plugins.git.traits.IgnoreOnPushNotificationTrait; import jenkins.plugins.git.traits.PruneStaleBranchTrait; import jenkins.plugins.git.traits.TagDiscoveryTrait; - import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.collection.IsEmptyCollection.empty; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; - import jenkins.scm.api.SCMSourceCriteria; import jenkins.scm.api.SCMSourceOwner; import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction; @@ -73,44 +90,29 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.CALLS_REAL_METHODS; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - /** * Tests for {@link AbstractGitSCMSource} */ @OrderWith(RandomOrder.class) public class AbstractGitSCMSourceTest { - static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; - static final String GitBranchSCMHead_DEV_DEV2_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + static final String GitBranchSCMHead_DEV_MASTER = + "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + static final String GitBranchSCMHead_DEV_DEV2_MASTER = + "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; @Rule public JenkinsRule r = new JenkinsRule(); + @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + @Rule public GitSampleRepoRule sampleRepo2 = new GitSampleRepoRule(); @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -125,7 +127,8 @@ private boolean isTimeAvailable() { return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; } - // TODO AbstractGitSCMSourceRetrieveHeadsTest *sounds* like it would be the right place, but it does not in fact retrieve any heads! + // TODO AbstractGitSCMSourceRetrieveHeadsTest *sounds* like it would be the right place, but it does not in fact + // retrieve any heads! @Issue("JENKINS-37482") @Test @Deprecated // Tests deprecated GitSCMSource constructor @@ -233,25 +236,32 @@ public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() th long fileTimeStampFuzz = isWindows() ? 2000L : 1000L; fileTimeStampFuzz = 12 * fileTimeStampFuzz / 10; // 20% grace for file system noise switch (scmHead.getName()) { - case "lightweight": - { - long timeStampDelta = afterLightweightTag - tagHead.getTimestamp(); - assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterLightweightTag - beforeLightweightTag + fileTimeStampFuzz)))); - break; - } - case "annotated": - { - long timeStampDelta = afterAnnotatedTag - tagHead.getTimestamp(); - assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterAnnotatedTag - beforeAnnotatedTag + fileTimeStampFuzz)))); - break; - } + case "lightweight": { + long timeStampDelta = afterLightweightTag - tagHead.getTimestamp(); + assertThat( + timeStampDelta, + is(both(greaterThanOrEqualTo(0L)) + .and(lessThanOrEqualTo( + afterLightweightTag - beforeLightweightTag + fileTimeStampFuzz)))); + break; + } + case "annotated": { + long timeStampDelta = afterAnnotatedTag - tagHead.getTimestamp(); + assertThat( + timeStampDelta, + is(both(greaterThanOrEqualTo(0L)) + .and(lessThanOrEqualTo( + afterAnnotatedTag - beforeAnnotatedTag + fileTimeStampFuzz)))); + break; + } default: fail("Unexpected tag head '" + scmHead.getName() + "'"); break; } } } - String expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + String expected = + "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; assertEquals(expected, scmHeadSet.toString()); // And reuse cache: assertEquals(expected, source.fetch(listener).toString()); @@ -259,7 +269,8 @@ public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() th sampleRepo.write("file", "modified again"); sampleRepo.git("commit", "--all", "--message=dev2"); // After changing data: - expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + expected = + "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; assertEquals(expected, source.fetch(listener).toString()); } @@ -283,9 +294,13 @@ public void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrai // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: assertEquals("[]", source.fetch(listener).toString()); source.setTraits(Collections.singletonList(new TagDiscoveryTrait())); - assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString()); + assertEquals( + "[SCMHead{'annotated'}, SCMHead{'lightweight'}]", + source.fetch(listener).toString()); // And reuse cache: - assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString()); + assertEquals( + "[SCMHead{'annotated'}, SCMHead{'lightweight'}]", + source.fetch(listener).toString()); } @Issue("JENKINS-45953") @@ -311,7 +326,8 @@ public void retrieveRevisions() throws Exception { source.setTraits(Collections.singletonList(new TagDiscoveryTrait())); assertThat(source.fetchRevisions(listener, null), containsInAnyOrder("annotated", "lightweight")); source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); - assertThat(source.fetchRevisions(listener, null), containsInAnyOrder("dev", "master", "annotated", "lightweight")); + assertThat( + source.fetchRevisions(listener, null), containsInAnyOrder("dev", "master", "annotated", "lightweight")); } @Issue("JENKINS-64803") @@ -338,8 +354,8 @@ public void retrieveTags_folderScopedCredentials() throws Exception { } assert folderStore != null; String fCredentialsId = "fcreds"; - StandardCredentials fCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, - fCredentialsId, "fcreds", "user", "password"); + StandardCredentials fCredentials = new UsernamePasswordCredentialsImpl( + CredentialsScope.GLOBAL, fCredentialsId, "fcreds", "user", "password"); folderStore.addCredentials(Domain.global(), fCredentials); folderStore.save(); WorkflowJob p = f.createProject(WorkflowJob.class, "wjob"); @@ -357,7 +373,8 @@ public void retrieveTags_folderScopedCredentials() throws Exception { String className = "jenkins.plugins.git.AbstractGitSCMSourceTest"; String testName = "retrieveTags_folderScopedCredentials"; String flag = className + "." + testName + ".enabled"; - String defaultValue = "The source.fetch() unexpectedly modifies the git remote.origin.url in the working repo"; + String defaultValue = + "The source.fetch() unexpectedly modifies the git remote.origin.url in the working repo"; /* If -Djenkins.plugins.git.AbstractGitSCMSourceTest.retrieveTags_folderScopedCredentials.enabled=true */ if (!System.getProperty(flag, defaultValue).equals(defaultValue)) { /* The source.fetch() unexpectedly modifies the git remote.origin.url in the working repo */ @@ -396,19 +413,19 @@ public void retrieveByName() throws Exception { listener.getLogger().println("\n=== fetch('master') ===\n"); SCMRevision rev = source.fetch("master", listener, null); assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); - assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(masterHash)); + assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(masterHash)); listener.getLogger().println("\n=== fetch('dev') ===\n"); rev = source.fetch("dev", listener, null); assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); - assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(devHash)); + assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(devHash)); listener.getLogger().println("\n=== fetch('v1') ===\n"); rev = source.fetch("v1", listener, null); assertThat(rev, instanceOf(GitTagSCMRevision.class)); - assertThat(((GitTagSCMRevision)rev).getHash(), is(v1Hash)); + assertThat(((GitTagSCMRevision) rev).getHash(), is(v1Hash)); listener.getLogger().println("\n=== fetch('v2') ===\n"); rev = source.fetch("v2", listener, null); assertThat(rev, instanceOf(GitTagSCMRevision.class)); - assertThat(((GitTagSCMRevision)rev).getHash(), is(v2Hash)); + assertThat(((GitTagSCMRevision) rev).getHash(), is(v2Hash)); listener.getLogger().printf("%n=== fetch('%s') ===%n%n", masterHash); rev = source.fetch(masterHash, listener, null); @@ -459,12 +476,9 @@ public void retrieveByName() throws Exception { rev = source.fetch(v2Tag, listener, null); assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash)); - } - public static abstract class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner { - - } + public abstract static class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner {} @Test @Deprecated @@ -508,17 +522,18 @@ private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception { source.setOwner(owner); TaskListener listener = StreamTaskListener.fromStderr(); Map headByName = new TreeMap<>(); - for (SCMHead h: source.fetch(listener)) { + for (SCMHead h : source.fetch(listener)) { headByName.put(h.getName(), h); } if (duplicatePrimary) { - assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary", "new-primary-duplicate")); + assertThat( + headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary", "new-primary-duplicate")); } else { assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary")); } List actions = source.fetchActions(null, listener); GitRemoteHeadRefAction refAction = null; - for (Action a: actions) { + for (Action a : actions) { if (a instanceof GitRemoteHeadRefAction) { refAction = (GitRemoteHeadRefAction) a; break; @@ -536,7 +551,7 @@ private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception { } PrimaryInstanceMetadataAction primary = null; - for (Action a: actions) { + for (Action a : actions) { if (a instanceof PrimaryInstanceMetadataAction) { primary = (PrimaryInstanceMetadataAction) a; break; @@ -564,7 +579,7 @@ public void retrieveRevision() throws Exception { sampleRepo.write("file", "v3"); sampleRepo.git("commit", "--all", "--message=v3"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); StreamTaskListener listener = StreamTaskListener.fromStderr(); @@ -603,7 +618,7 @@ public void retrieveRevision_nonHead() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); StreamTaskListener listener = StreamTaskListener.fromStderr(); @@ -631,7 +646,7 @@ public void retrieveRevision_nonAdvertised() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); StreamTaskListener listener = StreamTaskListener.fromStderr(); @@ -661,12 +676,10 @@ public void retrieveRevision_customRef() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList( - new BranchDiscoveryTrait(), - new TagDiscoveryTrait(), - new DiscoverOtherRefsTrait("refs/custom/foo"))); + new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("refs/custom/foo"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); // Test retrieval of non head revision: assertEquals("v3", fileAt(v3, run, source, listener)); @@ -692,17 +705,15 @@ public void retrieveRevision_customRef_descendant() throws Exception { sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd sampleRepo.git("reset", "--hard", "HEAD~2"); // dev String dev = sampleRepo.head(); - assertNotEquals(dev, v3); //Just verifying the reset nav got correct + assertNotEquals(dev, v3); // Just verifying the reset nav got correct assertEquals(dev, v2); sampleRepo.write("file", "v5"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList( - new BranchDiscoveryTrait(), - new TagDiscoveryTrait(), - new DiscoverOtherRefsTrait("refs/custom/*"))); + new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("refs/custom/*"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); // Test retrieval of non head revision: assertEquals("v3", fileAt(v3, run, source, listener)); @@ -728,12 +739,10 @@ public void retrieveRevision_customRef_abbrev_sha1() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Arrays.asList( - new BranchDiscoveryTrait(), - new TagDiscoveryTrait(), - new DiscoverOtherRefsTrait("refs/custom/foo"))); + new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("refs/custom/foo"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); // Test retrieval of non head revision: assertEquals("v3", fileAt(v3.substring(0, 7), run, source, listener)); @@ -754,14 +763,18 @@ public void retrieveRevision_pr_refspec() throws Exception { sampleRepo.write("file", "v3"); sampleRepo.git("commit", "--all", "--message=v3"); // dev String v3 = sampleRepo.head(); - sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd + sampleRepo.git( + "update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd sampleRepo.git("reset", "--hard", "HEAD^"); // dev sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); - source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("pull-requests/*/from"))); + source.setTraits(Arrays.asList( + new BranchDiscoveryTrait(), + new TagDiscoveryTrait(), + new DiscoverOtherRefsTrait("pull-requests/*/from"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); // Test retrieval of non head revision: assertEquals("v3", fileAt("pull-requests/1/from", run, source, listener)); @@ -782,15 +795,18 @@ public void retrieveRevision_pr_local_refspec() throws Exception { sampleRepo.write("file", "v3"); sampleRepo.git("commit", "--all", "--message=v3"); // dev String v3 = sampleRepo.head(); - sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd + sampleRepo.git( + "update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd sampleRepo.git("reset", "--hard", "HEAD^"); // dev sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); - //new RefSpecsSCMSourceTrait("+refs/pull-requests/*/from:refs/remotes/@{remote}/pr/*") - source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), + // new RefSpecsSCMSourceTrait("+refs/pull-requests/*/from:refs/remotes/@{remote}/pr/*") + source.setTraits(Arrays.asList( + new BranchDiscoveryTrait(), + new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("/pull-requests/*/from", "pr/@{1}"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); // Test retrieval of non head revision: @@ -798,13 +814,15 @@ public void retrieveRevision_pr_local_refspec() throws Exception { } private int wsCount; - private String fileAt(String revision, Run run, SCMSource source, TaskListener listener) throws Exception { + + private String fileAt(String revision, Run run, SCMSource source, TaskListener listener) throws Exception { SCMRevision rev = source.fetch(revision, listener, null); if (rev == null) { return null; } else { FilePath ws = new FilePath(run.getRootDir()).child("ws" + ++wsCount); - source.build(rev.getHead(), rev).checkout(run, new Launcher.LocalLauncher(listener), ws, listener, null, SCMRevisionState.NONE); + source.build(rev.getHead(), rev) + .checkout(run, new Launcher.LocalLauncher(listener), ws, listener, null, SCMRevisionState.NONE); return ws.child("file").readToString(); } } @@ -829,20 +847,18 @@ public void fetchOtherRef() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); - source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*"))); + source.setTraits(Arrays.asList( + new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); final SCMHeadObserver.Collector collector = - source.fetch((SCMSourceCriteria) (probe, listener1) -> true, new SCMHeadObserver.Collector(), listener); + source.fetch((SCMSourceCriteria) (probe, listener1) -> true, new SCMHeadObserver.Collector(), listener); final Map result = collector.result(); assertThat(result.entrySet(), hasSize(4)); - assertThat(result, hasKey(allOf( - instanceOf(GitRefSCMHead.class), - hasProperty("name", equalTo("custom-1")) - ))); + assertThat(result, hasKey(allOf(instanceOf(GitRefSCMHead.class), hasProperty("name", equalTo("custom-1"))))); } @Issue("JENKINS-48061") @@ -865,20 +881,17 @@ public void fetchOtherRevisions() throws Exception { sampleRepo.write("file", "v4"); sampleRepo.git("commit", "--all", "--message=v4"); // dev // SCM.checkout does not permit a null build argument, unfortunately. - Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); + Run run = r.buildAndAssertSuccess(r.createFreeStyleProject()); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); - source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*"))); + source.setTraits(Arrays.asList( + new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*"))); StreamTaskListener listener = StreamTaskListener.fromStderr(); final Set revisions = source.fetchRevisions(listener, null); assertThat(revisions, hasSize(4)); - assertThat(revisions, containsInAnyOrder( - equalTo("custom-1"), - equalTo("v1"), - equalTo("dev"), - equalTo("master") - )); + assertThat( + revisions, containsInAnyOrder(equalTo("custom-1"), equalTo("v1"), equalTo("dev"), equalTo("master"))); } @Issue("JENKINS-37727") @@ -920,7 +933,9 @@ public void pruneRemovesDeletedBranches() throws Exception { sampleRepo.git("branch", "-D", "dev"); /* Fetch and confirm dev branch was pruned */ - assertEquals("[GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]", source.fetch(listener).toString()); + assertEquals( + "[GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]", + source.fetch(listener).toString()); } @Test @@ -942,48 +957,38 @@ public void testSpecificRevisionBuildChooser() throws Exception { LocalBranch localBranchExtension = new LocalBranch("**"); extensions.add(localBranchExtension); source.setExtensions(extensions); - assertThat(source.getExtensions(), contains( - allOf( - instanceOf(LocalBranch.class), - hasProperty("localBranch", is("**") - ) - ) - )); + assertThat( + source.getExtensions(), + contains(allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))))); SCMHead head = new SCMHead("master"); - SCMRevision revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "beaded4deed2bed4feed2deaf78933d0f97a5a34"); + SCMRevision revision = + new AbstractGitSCMSource.SCMRevisionImpl(head, "beaded4deed2bed4feed2deaf78933d0f97a5a34"); // because we are ignoring push notifications we also ignore commits extensions.add(new IgnoreNotifyCommit()); /* Check that BuildChooserSetting not added to extensions by build() */ GitSCM scm = (GitSCM) source.build(head); - assertThat(scm.getExtensions(), containsInAnyOrder( - allOf( - instanceOf(LocalBranch.class), - hasProperty("localBranch", is("**") - ) - ), - // no BuildChooserSetting - instanceOf(IgnoreNotifyCommit.class), - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))), + // no BuildChooserSetting + instanceOf(IgnoreNotifyCommit.class), + instanceOf(GitSCMSourceDefaults.class))); /* Check that BuildChooserSetting has been added to extensions by build() */ GitSCM scmRevision = (GitSCM) source.build(head, revision); - assertThat(scmRevision.getExtensions(), containsInAnyOrder( - allOf( - instanceOf(LocalBranch.class), - hasProperty("localBranch", is("**") - ) - ), - instanceOf(BuildChooserSetting.class), - instanceOf(IgnoreNotifyCommit.class), - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat( + scmRevision.getExtensions(), + containsInAnyOrder( + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))), + instanceOf(BuildChooserSetting.class), + instanceOf(IgnoreNotifyCommit.class), + instanceOf(GitSCMSourceDefaults.class))); } - @Test @Deprecated // Tests deprecated GitSCMSource constructor public void testCustomRemoteName() throws Exception { @@ -1006,7 +1011,15 @@ public void testCustomRefSpecs() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); sampleRepo.init(); - GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", null, "+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", "*", "", true); + GitSCMSource source = new GitSCMSource( + null, + sampleRepo.toString(), + "", + null, + "+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", + "*", + "", + true); SCMHead head = new SCMHead("master"); GitSCM scm = (GitSCM) source.build(head); List configs = scm.getUserRemoteConfigs(); @@ -1015,7 +1028,9 @@ public void testCustomRefSpecs() throws Exception { UserRemoteConfig config = configs.get(0); assertEquals("origin", config.getName()); - assertEquals("+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", config.getRefspec()); + assertEquals( + "+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", + config.getRefspec()); } /* Return true if git config reports fetch.prune == true, otherwise return false */ @@ -1111,27 +1126,28 @@ private void createRefLockEnvironment(TaskListener listener, GitSCMSource source String branchRefLock = "prune/prune"; sampleRepo.init(); - //Create branch x + // Create branch x sampleRepo.git("checkout", "-b", branch); sampleRepo.git("push", "--set-upstream", source.getRemote(), branch); - //Ensure source retrieval has fetched branch x + // Ensure source retrieval has fetched branch x source.fetch("v1.2", listener, null); - //Remove branch x + // Remove branch x sampleRepo.git("checkout", "master"); sampleRepo.git("push", source.getRemote(), "--delete", branch); - //Create branch x/x (ref lock engaged) + // Create branch x/x (ref lock engaged) sampleRepo.git("checkout", "-b", branchRefLock); sampleRepo.git("push", "--set-upstream", source.getRemote(), branchRefLock); - //create tag for retrieval + // create tag for retrieval sampleRepo.git("tag", "v1.2"); sampleRepo.git("push", source.getRemote(), "v1.2"); } - @Test @Issue("JENKINS-50394") + @Test + @Issue("JENKINS-50394") public void when_commits_added_during_discovery_we_do_not_crash() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); sampleRepo.init(); @@ -1144,20 +1160,20 @@ public void when_commits_added_during_discovery_we_do_not_crash() throws Excepti GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); TaskListener listener = StreamTaskListener.fromStderr(); - SCMHeadObserver.Collector c = source.fetch((SCMSourceCriteria) (probe, listener1) -> true, new SCMHeadObserver.Collector(), listener); + SCMHeadObserver.Collector c = source.fetch( + (SCMSourceCriteria) (probe, listener1) -> true, new SCMHeadObserver.Collector(), listener); - assertThat(c.result().keySet(), containsInAnyOrder( - hasProperty("name", equalTo("master")), - hasProperty("name", equalTo("dev")) - )); - } catch(MissingObjectException me) { + assertThat( + c.result().keySet(), + containsInAnyOrder(hasProperty("name", equalTo("master")), hasProperty("name", equalTo("dev")))); + } catch (MissingObjectException me) { fail("Not supposed to get MissingObjectException"); } finally { System.clearProperty(Git.class.getName() + ".mockClient"); sharedSampleRepo = null; } } - //Ugly but MockGitClient needs to be static and no good way to pass it on + // Ugly but MockGitClient needs to be static and no good way to pass it on static GitSampleRepoRule sharedSampleRepo; public static class MockGitClient extends TestJGitAPIImpl { @@ -1171,10 +1187,12 @@ public MockGitClient(String exe, EnvVars env, File workspace, TaskListener liste } @Override - public Map getRemoteReferences(String url, String pattern, boolean headsOnly, boolean tagsOnly) throws GitException, InterruptedException { + public Map getRemoteReferences( + String url, String pattern, boolean headsOnly, boolean tagsOnly) + throws GitException, InterruptedException { final Map remoteReferences = super.getRemoteReferences(url, pattern, headsOnly, tagsOnly); try { - //Now update the repo with new commits + // Now update the repo with new commits sharedSampleRepo.write("file2", "New"); sharedSampleRepo.git("add", "file2"); sharedSampleRepo.git("commit", "--all", "--message=inbetween"); @@ -1187,7 +1205,7 @@ public Map getRemoteReferences(String url, String pattern, boo @Override public FetchCommand fetch_() { final FetchCommand fetchCommand = super.fetch_(); - //returning something that updates the repo after the fetch is performed + // returning something that updates the repo after the fetch is performed return new FetchCommand() { @Override public FetchCommand from(URIish urIish, List list) { @@ -1236,7 +1254,7 @@ public FetchCommand depth(Integer integer) { public void execute() throws GitException, InterruptedException { fetchCommand.execute(); try { - //Now update the repo with new commits + // Now update the repo with new commits sharedSampleRepo.write("file3", "New"); sharedSampleRepo.git("add", "file3"); sharedSampleRepo.git("commit", "--all", "--message=inbetween"); diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java index 6500a699d8..66e979da99 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java @@ -1,22 +1,21 @@ package jenkins.plugins.git; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + import edu.umd.cs.findbugs.annotations.NonNull; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitSCM; import hudson.plugins.git.UserRemoteConfig; - import java.util.ArrayList; import java.util.List; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMRevision; import nl.jqno.equalsverifier.EqualsVerifier; import org.eclipse.jgit.transport.RefSpec; -import org.junit.Test; - -import static org.junit.Assert.*; import org.junit.Before; +import org.junit.Test; import org.mockito.Mockito; -import static org.mockito.Mockito.*; public class AbstractGitSCMSourceTrivialTest { @@ -166,10 +165,12 @@ public AbstractGitSCMSourceImpl() { setId("AbstractGitSCMSourceImpl-id"); } + @Override public String getCredentialsId() { return expectedCredentialsId; } + @Override public String getRemote() { return expectedRemote; } @@ -209,5 +210,4 @@ public int hashCode() { throw new UnsupportedOperationException("Intentionally unimplemented"); } } - } diff --git a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java index 996181e239..855fdeac3a 100644 --- a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java @@ -1,5 +1,14 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import hudson.plugins.git.GitSCM; import hudson.plugins.git.browser.AssemblaWeb; import hudson.plugins.git.browser.BitbucketServer; @@ -24,231 +33,120 @@ import hudson.plugins.git.browser.ViewGitWeb; import hudson.scm.SCM; import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import java.util.ArrayList; +import java.util.List; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.LibraryRetriever; import org.jenkinsci.plugins.workflow.libs.SCMRetriever; import org.jvnet.hudson.test.RestartableJenkinsRule; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.core.AllOf.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; - public class BrowsersJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { final List libraries = GlobalLibraries.get().getLibraries(); - assertThat(libraries, containsInAnyOrder( - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withAssembla")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withFisheye")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withKiln")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withMic")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withBitbucket")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withBitbucketServer")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withCGit")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGithub")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitiles")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitlab")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitlist")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitorious")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitweb")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGogsgit")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withPhab")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withRedmine")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withRhodecode")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withStash")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withViewgit")) - ), - allOf( - instanceOf(LibraryConfiguration.class), - hasProperty("name", equalTo("withGitlib")) - ) - )); + assertThat( + libraries, + containsInAnyOrder( + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withAssembla"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withFisheye"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withKiln"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withMic"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withBitbucket"))), + allOf( + instanceOf(LibraryConfiguration.class), + hasProperty("name", equalTo("withBitbucketServer"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withCGit"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGithub"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitiles"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitlab"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitlist"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitorious"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitweb"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGogsgit"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withPhab"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withRedmine"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withRhodecode"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withStash"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withViewgit"))), + allOf(instanceOf(LibraryConfiguration.class), hasProperty("name", equalTo("withGitlib"))))); final List browsers = new ArrayList<>(); for (LibraryConfiguration library : libraries) { final String errorMessage = String.format("Error checking library %s", library.getName()); final LibraryRetriever retriever = library.getRetriever(); assertThat(errorMessage, retriever, instanceOf(SCMRetriever.class)); - final SCM scm = ((SCMRetriever) retriever).getScm(); + final SCM scm = ((SCMRetriever) retriever).getScm(); assertThat(errorMessage, scm, instanceOf(GitSCM.class)); - final GitSCM gitSCM = (GitSCM)scm; + final GitSCM gitSCM = (GitSCM) scm; assertNotNull(errorMessage, gitSCM.getBrowser()); browsers.add(gitSCM.getBrowser()); } assertEquals(libraries.size(), browsers.size()); - assertThat(browsers, containsInAnyOrder( - // AssemblaWeb - allOf( - instanceOf(AssemblaWeb.class), - hasProperty("repoUrl", equalTo("http://url.assembla")) - ), - // FishEye - allOf( - instanceOf(FisheyeGitRepositoryBrowser.class), - hasProperty("repoUrl", equalTo("http://url.fishEye/browse/foobar")) - ), - // Kiln - allOf( - instanceOf(KilnGit.class), - hasProperty("repoUrl", equalTo("http://url.kiln")) - ), - // Microsoft Team Foundation Server/Visual Studio Team Services - allOf( - instanceOf(TFS2013GitRepositoryBrowser.class), - hasProperty("repoUrl", equalTo("http://url.mic/_git/foobar/")) - ), - // bitbucketweb - allOf( - instanceOf(BitbucketWeb.class), - hasProperty("repoUrl", equalTo("http://url.bitbucket")) - ), - // bitbucketserver - allOf( - instanceOf(BitbucketServer.class), - hasProperty("repoUrl", equalTo("http://url.bitbucketserver")) - ), - // cgit - allOf( - instanceOf(CGit.class), - hasProperty("repoUrl", equalTo("http://url.cgit")) - ), - // gitblit - allOf( - instanceOf(GitBlitRepositoryBrowser.class), - hasProperty("repoUrl", equalTo("http://url.gitlib")), - hasProperty("projectName", equalTo("my_project")) - ), - // githubweb - allOf( - instanceOf(GithubWeb.class), - hasProperty("repoUrl", equalTo("http://github.com")) - ), - // gitiles - allOf( - instanceOf(Gitiles.class), - hasProperty("repoUrl", equalTo("http://url.gitiles")) - ), - // gitlab - allOf( - instanceOf(GitLab.class), - // TODO This property fails in CI but succeeds in local. Meanwhile, it's tested in GitLabConfiguratorTest - // hasProperty("version", equalTo(1.0)), - hasProperty("repoUrl", equalTo("http://gitlab.com")) - ), - // gitlist - allOf( - instanceOf(GitList.class), - hasProperty("repoUrl", equalTo("http://url.gitlist")) - ), - // gitoriousweb - allOf( - instanceOf(GitoriousWeb.class), - hasProperty("repoUrl", equalTo("http://url.gitorious")) - ), - // gitweb - allOf( - instanceOf(GitWeb.class), - hasProperty("repoUrl", equalTo("http://url.gitweb")) - ), - // gogs - allOf( - instanceOf(GogsGit.class), - hasProperty("repoUrl", equalTo("http://url.gogs")) - ), - // phabricator - allOf( - instanceOf(Phabricator.class), - hasProperty("repoUrl", equalTo("http://url.phabricator")), - hasProperty("repo", equalTo("my_repository")) - ), - // redmineweb - allOf( - instanceOf(RedmineWeb.class), - hasProperty("repoUrl", equalTo("http://url.redmineweb")) - ), - // rhodecode - allOf( - instanceOf(RhodeCode.class), - hasProperty("repoUrl", equalTo("http://url.rhodecode")) - ), - // stash - allOf( - instanceOf(Stash.class), - hasProperty("repoUrl", equalTo("http://url.stash")) - ), - // viewgit - allOf( - instanceOf(ViewGitWeb.class), - hasProperty("repoUrl", equalTo("http://url.viewgit")), - hasProperty("projectName", equalTo("my_other_project")) - ) - )); + assertThat( + browsers, + containsInAnyOrder( + // AssemblaWeb + allOf(instanceOf(AssemblaWeb.class), hasProperty("repoUrl", equalTo("http://url.assembla"))), + // FishEye + allOf( + instanceOf(FisheyeGitRepositoryBrowser.class), + hasProperty("repoUrl", equalTo("http://url.fishEye/browse/foobar"))), + // Kiln + allOf(instanceOf(KilnGit.class), hasProperty("repoUrl", equalTo("http://url.kiln"))), + // Microsoft Team Foundation Server/Visual Studio Team Services + allOf( + instanceOf(TFS2013GitRepositoryBrowser.class), + hasProperty("repoUrl", equalTo("http://url.mic/_git/foobar/"))), + // bitbucketweb + allOf(instanceOf(BitbucketWeb.class), hasProperty("repoUrl", equalTo("http://url.bitbucket"))), + // bitbucketserver + allOf( + instanceOf(BitbucketServer.class), + hasProperty("repoUrl", equalTo("http://url.bitbucketserver"))), + // cgit + allOf(instanceOf(CGit.class), hasProperty("repoUrl", equalTo("http://url.cgit"))), + // gitblit + allOf( + instanceOf(GitBlitRepositoryBrowser.class), + hasProperty("repoUrl", equalTo("http://url.gitlib")), + hasProperty("projectName", equalTo("my_project"))), + // githubweb + allOf(instanceOf(GithubWeb.class), hasProperty("repoUrl", equalTo("http://github.com"))), + // gitiles + allOf(instanceOf(Gitiles.class), hasProperty("repoUrl", equalTo("http://url.gitiles"))), + // gitlab + allOf( + instanceOf(GitLab.class), + // TODO This property fails in CI but succeeds in local. Meanwhile, it's tested in + // GitLabConfiguratorTest + // hasProperty("version", equalTo(1.0)), + hasProperty("repoUrl", equalTo("http://gitlab.com"))), + // gitlist + allOf(instanceOf(GitList.class), hasProperty("repoUrl", equalTo("http://url.gitlist"))), + // gitoriousweb + allOf(instanceOf(GitoriousWeb.class), hasProperty("repoUrl", equalTo("http://url.gitorious"))), + // gitweb + allOf(instanceOf(GitWeb.class), hasProperty("repoUrl", equalTo("http://url.gitweb"))), + // gogs + allOf(instanceOf(GogsGit.class), hasProperty("repoUrl", equalTo("http://url.gogs"))), + // phabricator + allOf( + instanceOf(Phabricator.class), + hasProperty("repoUrl", equalTo("http://url.phabricator")), + hasProperty("repo", equalTo("my_repository"))), + // redmineweb + allOf(instanceOf(RedmineWeb.class), hasProperty("repoUrl", equalTo("http://url.redmineweb"))), + // rhodecode + allOf(instanceOf(RhodeCode.class), hasProperty("repoUrl", equalTo("http://url.rhodecode"))), + // stash + allOf(instanceOf(Stash.class), hasProperty("repoUrl", equalTo("http://url.stash"))), + // viewgit + allOf( + instanceOf(ViewGitWeb.class), + hasProperty("repoUrl", equalTo("http://url.viewgit")), + hasProperty("projectName", equalTo("my_other_project"))))); } @Override diff --git a/src/test/java/jenkins/plugins/git/CliGitCommand.java b/src/test/java/jenkins/plugins/git/CliGitCommand.java index 7406b92c6b..468de36bcb 100644 --- a/src/test/java/jenkins/plugins/git/CliGitCommand.java +++ b/src/test/java/jenkins/plugins/git/CliGitCommand.java @@ -23,14 +23,16 @@ */ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItems; + import hudson.EnvVars; import hudson.Launcher; import hudson.model.TaskListener; +import hudson.plugins.git.GitException; import hudson.plugins.git.util.GitUtilsTest; import hudson.util.ArgumentListBuilder; import hudson.util.StreamTaskListener; -import hudson.plugins.git.GitException; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -40,10 +42,8 @@ import java.util.List; import java.util.concurrent.TimeUnit; import org.eclipse.jgit.lib.Repository; -import static org.hamcrest.Matchers.hasItems; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Assert; -import static org.hamcrest.MatcherAssert.assertThat; /** * Run a command line git command, return output as array of String, optionally @@ -72,7 +72,7 @@ public CliGitCommand(GitClient client, EnvVars envVars, String... arguments) { env = envVars; if (client != null) { try (@SuppressWarnings("deprecation") // Local repository reference - Repository repo = client.getRepository()) { + Repository repo = client.getRepository()) { dir = repo.getWorkTree(); } } else { @@ -97,7 +97,12 @@ public String[] run() throws IOException, InterruptedException { private String[] run(boolean assertProcessStatus) throws IOException, InterruptedException { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteArrayOutputStream bytesErr = new ByteArrayOutputStream(); - Launcher.ProcStarter p = launcher.launch().cmds(args).envs(env).stdout(bytesOut).stderr(bytesErr).pwd(dir); + Launcher.ProcStarter p = launcher.launch() + .cmds(args) + .envs(env) + .stdout(bytesOut) + .stderr(bytesErr) + .pwd(dir); int status = p.start().joinWithTimeout(1, TimeUnit.MINUTES, listener); String result = bytesOut.toString(StandardCharsets.UTF_8); if (bytesErr.size() > 0) { @@ -105,7 +110,8 @@ private String[] run(boolean assertProcessStatus) throws IOException, Interrupte } output = result.split("[\\n\\r]"); if (assertProcessStatus) { - Assert.assertEquals(args.toString() + " command failed and reported '" + Arrays.toString(output) + "'", 0, status); + Assert.assertEquals( + args.toString() + " command failed and reported '" + Arrays.toString(output) + "'", 0, status); } return output; } @@ -118,7 +124,8 @@ public void assertOutputContains(String... expectedRegExes) { notFound.removeIf(line::matches); } if (!notFound.isEmpty()) { - Assert.fail(Arrays.toString(output) + " did not match all strings in notFound: " + Arrays.toString(expectedRegExes)); + Assert.fail(Arrays.toString(output) + " did not match all strings in notFound: " + + Arrays.toString(expectedRegExes)); } } @@ -132,7 +139,8 @@ private void setConfigIfEmpty(String configName, String value) throws Exception /* Read config value */ cmdOutput = run("config", "--global", configName); if (cmdOutput == null || cmdOutput[0].isEmpty() || !cmdOutput[0].equals(value)) { - throw new GitException("ERROR: git config --global " + configName + " reported '" + cmdOutput[0] + "' instead of '" + value + "'"); + throw new GitException("ERROR: git config --global " + configName + " reported '" + cmdOutput[0] + + "' instead of '" + value + "'"); } } } @@ -150,9 +158,9 @@ private void setConfigIfEmpty(String configName, String value) throws Exception public void setDefaults() throws Exception { if (System.getenv("JENKINS_URL") != null && System.getenv("BUILD_NUMBER") != null) { /* We're in a Jenkins agent environment */ - setConfigIfEmpty("user.name", "Name From Git-Plugin-Test"); - setConfigIfEmpty("user.email", "email.from.git.plugin.test@example.com"); - } + setConfigIfEmpty("user.name", "Name From Git-Plugin-Test"); + setConfigIfEmpty("user.email", "email.from.git.plugin.test@example.com"); + } } /** @@ -165,5 +173,4 @@ public CliGitCommand env(String key, String value) { env.put(key, value); return this; } - } diff --git a/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java b/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java index 40a6f29fad..086b98c309 100644 --- a/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java +++ b/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java @@ -1,7 +1,13 @@ package jenkins.plugins.git; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import hudson.FilePath; import hudson.model.Queue; +import java.io.File; +import java.io.IOException; +import java.net.URL; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; @@ -12,21 +18,18 @@ import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.recipes.LocalData; -import java.io.File; -import java.io.IOException; -import java.net.URL; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - public class GitBranchSCMHeadTest { @Rule public JenkinsRule j = new JenkinsRule() { @Override public void before() throws Throwable { - if (!isWindows() && "testMigrationNoBuildStorm".equals(this.getTestDescription().getMethodName())) { - URL res = getClass().getResource("/jenkins/plugins/git/GitBranchSCMHeadTest/testMigrationNoBuildStorm_repositories.zip"); + if (!isWindows() + && "testMigrationNoBuildStorm" + .equals(this.getTestDescription().getMethodName())) { + URL res = getClass() + .getResource( + "/jenkins/plugins/git/GitBranchSCMHeadTest/testMigrationNoBuildStorm_repositories.zip"); final File path = new File("/tmp/JENKINS-48061"); if (path.exists()) { if (path.isDirectory()) { @@ -50,7 +53,6 @@ public void removeRepos() throws IOException { } } - @Issue("JENKINS-48061") @Test @LocalData @@ -85,6 +87,6 @@ public void testMigrationNoBuildStorm() throws Exception { /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java b/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java index c12e16f5d2..c02ef0ac51 100644 --- a/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java +++ b/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java @@ -23,6 +23,12 @@ */ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.EnvVars; import hudson.model.TaskListener; import java.io.File; @@ -37,12 +43,6 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class GitHooksConfigurationTest { @Rule @@ -54,8 +54,7 @@ public class GitHooksConfigurationTest { private final Random random = new Random(); private static final String NULL_HOOKS_PATH = isWindows() ? "NUL:" : "/dev/null"; - public GitHooksConfigurationTest() { - } + public GitHooksConfigurationTest() {} @Before public void setUp() throws IOException, InterruptedException { diff --git a/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java index d5733251bf..9e321bb744 100644 --- a/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java @@ -1,5 +1,7 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; + import hudson.plugins.git.GitSCM; import hudson.scm.SCM; import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; @@ -9,15 +11,12 @@ import org.jenkinsci.plugins.workflow.libs.SCMRetriever; import org.jvnet.hudson.test.RestartableJenkinsRule; - -import static org.hamcrest.MatcherAssert.assertThat; - public class GitJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { LibraryRetriever retriever = GlobalLibraries.get().getLibraries().get(0).getRetriever(); assertThat(retriever, CoreMatchers.instanceOf(SCMRetriever.class)); - SCM scm = ((SCMRetriever) retriever).getScm(); + SCM scm = ((SCMRetriever) retriever).getScm(); assertThat(scm, CoreMatchers.instanceOf(GitSCM.class)); } diff --git a/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java b/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java index f9f1f4c1c8..ada174cc43 100644 --- a/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java +++ b/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java @@ -7,8 +7,6 @@ public class GitRemoteHeadRefActionTest { @Test public void equalsContract() { - EqualsVerifier.forClass(GitRemoteHeadRefAction.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(GitRemoteHeadRefAction.class).usingGetClass().verify(); } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java b/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java index 11016cdf19..135ab44607 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java @@ -1,5 +1,15 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + import hudson.plugins.git.GitSCM; import hudson.plugins.git.UserRemoteConfig; import hudson.plugins.git.browser.GithubWeb; @@ -14,39 +24,25 @@ import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - public class GitSCMBuilderTest { - private GitSCMBuilder instance = new GitSCMBuilder<>( - new SCMHead("master"), - null, - "http://git.test/repo.git", - null); + private GitSCMBuilder instance = + new GitSCMBuilder<>(new SCMHead("master"), null, "http://git.test/repo.git", null); @Test public void build() throws Exception { GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -54,26 +50,35 @@ public void withRevision() throws Exception { instance.withExtension(new BuildChooserSetting(new InverseBuildChooser())); GitSCM scm = instance.build(); assertThat(scm.getExtensions().get(BuildChooserSetting.class), notNullValue()); - assertThat(scm.getExtensions().get(BuildChooserSetting.class).getBuildChooser(), + assertThat( + scm.getExtensions().get(BuildChooserSetting.class).getBuildChooser(), instanceOf(InverseBuildChooser.class)); instance.withRevision( new AbstractGitSCMSource.SCMRevisionImpl(instance.head(), "3f0b897057d8b43d3b9ff55e3fdefbb021493470")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); assertThat(scm.getExtensions().get(BuildChooserSetting.class), notNullValue()); - assertThat(scm.getExtensions().get(BuildChooserSetting.class).getBuildChooser(), + assertThat( + scm.getExtensions().get(BuildChooserSetting.class).getBuildChooser(), instanceOf(AbstractGitSCMSource.SpecificRevisionBuildChooser.class)); - assertThat(scm.getExtensions().get(BuildChooserSetting.class).getBuildChooser() - .getCandidateRevisions(false, null, (GitClient) null, null, null, null).iterator().next() - .getSha1String(), is("3f0b897057d8b43d3b9ff55e3fdefbb021493470")); + assertThat( + scm.getExtensions() + .get(BuildChooserSetting.class) + .getBuildChooser() + .getCandidateRevisions(false, null, (GitClient) null, null, null, null) + .iterator() + .next() + .getSha1String(), + is("3f0b897057d8b43d3b9ff55e3fdefbb021493470")); } @Test @@ -82,17 +87,16 @@ public void withBrowser() throws Exception { assertThat(instance.browser(), is(instanceOf(GithubWeb.class))); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(instanceOf(GithubWeb.class))); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -101,17 +105,16 @@ public void withCredentials() throws Exception { assertThat(instance.credentialsId(), is("example-id")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is("example-id"))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is("example-id"))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -120,62 +123,68 @@ public void withExtension() throws Exception { assertThat(instance.extensions(), contains(instanceOf(AuthorInChangelog.class))); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder(instanceOf(AuthorInChangelog.class), instanceOf(GitSCMSourceDefaults.class))); // repeated calls build up new extensions instance.withExtension(new LocalBranch("**")); - assertThat(instance.extensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))) - )); + assertThat( + instance.extensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))))); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(GitSCMSourceDefaults.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))))); // repeated calls re-define up existing extensions instance.withExtension(new LocalBranch("master")); - assertThat(instance.extensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))) - )); + assertThat( + instance.extensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))))); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(GitSCMSourceDefaults.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))))); } @Test @@ -184,87 +193,94 @@ public void withExtensions() throws Exception { assertThat(instance.extensions(), contains(instanceOf(AuthorInChangelog.class))); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder(instanceOf(AuthorInChangelog.class), instanceOf(GitSCMSourceDefaults.class))); // repeated calls build up extensions instance.withExtensions(new CleanCheckout()); - assertThat(instance.extensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(CleanCheckout.class) - )); + assertThat( + instance.extensions(), + containsInAnyOrder(instanceOf(AuthorInChangelog.class), instanceOf(CleanCheckout.class))); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class), - instanceOf(CleanCheckout.class) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(GitSCMSourceDefaults.class), + instanceOf(CleanCheckout.class))); instance.withExtension(new LocalBranch("**")); - assertThat(instance.extensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(CleanCheckout.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))) - )); + assertThat( + instance.extensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(CleanCheckout.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))))); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class), - instanceOf(CleanCheckout.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(GitSCMSourceDefaults.class), + instanceOf(CleanCheckout.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))))); // repeated calls re-define up existing extensions instance.withExtension(new LocalBranch("master")); - assertThat(instance.extensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(CleanCheckout.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))) - )); + assertThat( + instance.extensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(CleanCheckout.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))))); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), containsInAnyOrder( - instanceOf(AuthorInChangelog.class), - instanceOf(GitSCMSourceDefaults.class), - instanceOf(CleanCheckout.class), - allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))) - )); + assertThat( + scm.getExtensions(), + containsInAnyOrder( + instanceOf(AuthorInChangelog.class), + instanceOf(GitSCMSourceDefaults.class), + instanceOf(CleanCheckout.class), + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("master"))))); } @Test @@ -273,17 +289,16 @@ public void withGitTool() throws Exception { assertThat(instance.gitTool(), is("git")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is("git")); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -293,17 +308,16 @@ public void withRefSpecAndCloneOption() throws Exception { assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(CloneOption.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(CloneOption.class))); } @Test @@ -312,89 +326,88 @@ public void withRefSpec() throws Exception { assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); // repeated calls build up instance.withRefSpec("+refs/heads/feature:refs/remotes/@{remote}/feature"); - assertThat(instance.refSpecs(), containsInAnyOrder( - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/feature:refs/remotes/@{remote}/feature" - )); + assertThat( + instance.refSpecs(), + containsInAnyOrder( + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/feature:refs/remotes/@{remote}/feature")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), containsInAnyOrder( - allOf( + assertThat( + scm.getUserRemoteConfigs(), + containsInAnyOrder(allOf( instanceOf(UserRemoteConfig.class), hasProperty("url", is("http://git.test/repo.git")), hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master " - + "+refs/heads/feature:refs/remotes/origin/feature")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + hasProperty( + "refspec", + is("+refs/heads/master:refs/remotes/origin/master " + + "+refs/heads/feature:refs/remotes/origin/feature")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); // repeated calls build up but remote configs de-duplicated instance.withRefSpec("+refs/heads/master:refs/remotes/@{remote}/master"); - assertThat(instance.refSpecs(), containsInAnyOrder( - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/feature:refs/remotes/@{remote}/feature", - "+refs/heads/master:refs/remotes/@{remote}/master" - )); + assertThat( + instance.refSpecs(), + containsInAnyOrder( + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/feature:refs/remotes/@{remote}/feature", + "+refs/heads/master:refs/remotes/@{remote}/master")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), containsInAnyOrder( - allOf( + assertThat( + scm.getUserRemoteConfigs(), + containsInAnyOrder(allOf( instanceOf(UserRemoteConfig.class), hasProperty("url", is("http://git.test/repo.git")), hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master " - + "+refs/heads/feature:refs/remotes/origin/feature")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + hasProperty( + "refspec", + is("+refs/heads/master:refs/remotes/origin/master " + + "+refs/heads/feature:refs/remotes/origin/feature")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); // de-duplication is applied after template substitution instance.withRefSpec("+refs/heads/master:refs/remotes/origin/master"); - assertThat(instance.refSpecs(), containsInAnyOrder( - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/feature:refs/remotes/@{remote}/feature", - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/master:refs/remotes/origin/master" - )); + assertThat( + instance.refSpecs(), + containsInAnyOrder( + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/feature:refs/remotes/@{remote}/feature", + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/master:refs/remotes/origin/master")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), containsInAnyOrder( - allOf( + assertThat( + scm.getUserRemoteConfigs(), + containsInAnyOrder(allOf( instanceOf(UserRemoteConfig.class), hasProperty("url", is("http://git.test/repo.git")), hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master " - + "+refs/heads/feature:refs/remotes/origin/feature")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + hasProperty( + "refspec", + is("+refs/heads/master:refs/remotes/origin/master " + + "+refs/heads/feature:refs/remotes/origin/feature")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -403,63 +416,62 @@ public void withRefSpecs() throws Exception { assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); // repeated calls accumulate instance.withRefSpecs(Collections.singletonList("+refs/heads/feature:refs/remotes/@{remote}/feature")); - assertThat(instance.refSpecs(), contains( - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/feature:refs/remotes/@{remote}/feature" - )); + assertThat( + instance.refSpecs(), + contains( + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/feature:refs/remotes/@{remote}/feature")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains( - allOf( + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( instanceOf(UserRemoteConfig.class), hasProperty("url", is("http://git.test/repo.git")), hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master " - + "+refs/heads/feature:refs/remotes/origin/feature")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + hasProperty( + "refspec", + is("+refs/heads/master:refs/remotes/origin/master " + + "+refs/heads/feature:refs/remotes/origin/feature")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); // empty list is no-op instance.withRefSpecs(Collections.emptyList()); - assertThat(instance.refSpecs(), contains( - "+refs/heads/master:refs/remotes/@{remote}/master", - "+refs/heads/feature:refs/remotes/@{remote}/feature" - )); + assertThat( + instance.refSpecs(), + contains( + "+refs/heads/master:refs/remotes/@{remote}/master", + "+refs/heads/feature:refs/remotes/@{remote}/feature")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains( - allOf( + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( instanceOf(UserRemoteConfig.class), hasProperty("url", is("http://git.test/repo.git")), hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/origin/master " - + "+refs/heads/feature:refs/remotes/origin/feature")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + hasProperty( + "refspec", + is("+refs/heads/master:refs/remotes/origin/master " + + "+refs/heads/feature:refs/remotes/origin/feature")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -473,17 +485,16 @@ public void withoutRefSpecs() throws Exception { assertThat(instance.refSpecs(), contains("+refs/heads/*:refs/remotes/@{remote}/*")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -492,17 +503,16 @@ public void withRemote() throws Exception { assertThat(instance.remote(), is("http://git.test/my-repo.git")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/my-repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/my-repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test @@ -511,87 +521,79 @@ public void withRemoteName() throws Exception { assertThat(instance.remoteName(), is("my-remote")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), contains(allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("my-remote")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/my-remote/*")), - hasProperty("credentialsId", is(nullValue()))) - )); + assertThat( + scm.getUserRemoteConfigs(), + contains(allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("my-remote")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/my-remote/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } @Test public void withAdditionalRemote() throws Exception { - instance.withAdditionalRemote("upstream", "http://git.test/upstream.git", - "+refs/heads/master:refs/remotes/@{remote}/master"); + instance.withAdditionalRemote( + "upstream", "http://git.test/upstream.git", "+refs/heads/master:refs/remotes/@{remote}/master"); assertThat(instance.additionalRemoteNames(), contains("upstream")); assertThat(instance.additionalRemote("upstream"), is("http://git.test/upstream.git")); - assertThat(instance.additionalRemoteRefSpecs("upstream"), contains( - "+refs/heads/master:refs/remotes/@{remote}/master")); + assertThat( + instance.additionalRemoteRefSpecs("upstream"), + contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), containsInAnyOrder( - allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue())) - ), - allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/upstream.git")), - hasProperty("name", is("upstream")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/upstream/master")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + assertThat( + scm.getUserRemoteConfigs(), + containsInAnyOrder( + allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))), + allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/upstream.git")), + hasProperty("name", is("upstream")), + hasProperty("refspec", is("+refs/heads/master:refs/remotes/upstream/master")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); instance.withAdditionalRemote("production", "http://git.test/production.git"); assertThat(instance.additionalRemoteNames(), containsInAnyOrder("upstream", "production")); assertThat(instance.additionalRemote("upstream"), is("http://git.test/upstream.git")); - assertThat(instance.additionalRemoteRefSpecs("upstream"), contains( - "+refs/heads/master:refs/remotes/@{remote}/master")); + assertThat( + instance.additionalRemoteRefSpecs("upstream"), + contains("+refs/heads/master:refs/remotes/@{remote}/master")); assertThat(instance.additionalRemote("production"), is("http://git.test/production.git")); - assertThat(instance.additionalRemoteRefSpecs("production"), contains( - "+refs/heads/*:refs/remotes/@{remote}/*")); + assertThat(instance.additionalRemoteRefSpecs("production"), contains("+refs/heads/*:refs/remotes/@{remote}/*")); scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); - assertThat(scm.getUserRemoteConfigs(), containsInAnyOrder( - allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/repo.git")), - hasProperty("name", is("origin")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), - hasProperty("credentialsId", is(nullValue())) - ), - allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/upstream.git")), - hasProperty("name", is("upstream")), - hasProperty("refspec", is("+refs/heads/master:refs/remotes/upstream/master")), - hasProperty("credentialsId", is(nullValue())) - ), - allOf( - instanceOf(UserRemoteConfig.class), - hasProperty("url", is("http://git.test/production.git")), - hasProperty("name", is("production")), - hasProperty("refspec", is("+refs/heads/*:refs/remotes/production/*")), - hasProperty("credentialsId", is(nullValue())) - ) - )); + assertThat( + scm.getUserRemoteConfigs(), + containsInAnyOrder( + allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/repo.git")), + hasProperty("name", is("origin")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/origin/*")), + hasProperty("credentialsId", is(nullValue()))), + allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/upstream.git")), + hasProperty("name", is("upstream")), + hasProperty("refspec", is("+refs/heads/master:refs/remotes/upstream/master")), + hasProperty("credentialsId", is(nullValue()))), + allOf( + instanceOf(UserRemoteConfig.class), + hasProperty("url", is("http://git.test/production.git")), + hasProperty("name", is("production")), + hasProperty("refspec", is("+refs/heads/*:refs/remotes/production/*")), + hasProperty("credentialsId", is(nullValue()))))); assertThat(scm.getGitTool(), is(nullValue())); - assertThat(scm.getExtensions(), contains( - instanceOf(GitSCMSourceDefaults.class) - )); + assertThat(scm.getExtensions(), contains(instanceOf(GitSCMSourceDefaults.class))); } - } diff --git a/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java b/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java index 64eb3718d5..826d94b65a 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java @@ -25,11 +25,24 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.BranchSpec; -import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitException; +import hudson.plugins.git.GitSCM; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Collections; @@ -42,7 +55,6 @@ import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceDescriptor; - import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.gitclient.Git; @@ -54,19 +66,6 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - /** * Tests for {@link AbstractGitSCMSource} */ @@ -78,8 +77,8 @@ public class GitSCMFileSystemTest { @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - private final static String GIT_2_6_0_TAG = "git-2.6.0"; - private final static String GIT_2_6_1_TAG = "git-2.6.1"; + private static final String GIT_2_6_0_TAG = "git-2.6.0"; + private static final String GIT_2_6_1_TAG = "git-2.6.1"; /* This test requires the tag git-2.6.1 and git-2.6.0. If you're working from a * forked copy of the repository and your fork was created before the @@ -93,9 +92,12 @@ public class GitSCMFileSystemTest { @BeforeClass public static void confirmTagsAvailable() throws Exception { File gitDir = new File("."); - GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("jgit").getClient(); + GitClient client = Git.with(TaskListener.NULL, new EnvVars()) + .in(gitDir) + .using("jgit") + .getClient(); - String[] tags = { GIT_2_6_0_TAG, GIT_2_6_1_TAG }; + String[] tags = {GIT_2_6_0_TAG, GIT_2_6_1_TAG}; for (String tag : tags) { ObjectId tagId; try { @@ -182,7 +184,14 @@ public void slashyBranches() throws Exception { sampleRepo.git("checkout", "-b", "bug/JENKINS-42817"); sampleRepo.write("file", "modified"); sampleRepo.git("commit", "--all", "--message=dev"); - SCMFileSystem fs = SCMFileSystem.of(r.createFreeStyleProject(), new GitSCM(GitSCM.createRepoList(sampleRepo.toString(), null), Collections.singletonList(new BranchSpec("*/bug/JENKINS-42817")), null, null, Collections.emptyList())); + SCMFileSystem fs = SCMFileSystem.of( + r.createFreeStyleProject(), + new GitSCM( + GitSCM.createRepoList(sampleRepo.toString(), null), + Collections.singletonList(new BranchSpec("*/bug/JENKINS-42817")), + null, + null, + Collections.emptyList())); assertThat(fs, notNullValue()); SCMFile root = fs.getRoot(); assertThat(root, notNullValue()); @@ -209,11 +218,14 @@ public void wildcardBranchNameCausesNPE() throws Exception { * null pointer exception when trying to resolve the branch * name in the GitSCMFileSystem constructor. */ - SCMFileSystem fs = SCMFileSystem.of(r.createFreeStyleProject(), - new GitSCM(GitSCM.createRepoList(sampleRepo.toString(), null), - Collections.singletonList(new BranchSpec("*")), // JENKINS-57587 issue here - null, null, - Collections.emptyList())); + SCMFileSystem fs = SCMFileSystem.of( + r.createFreeStyleProject(), + new GitSCM( + GitSCM.createRepoList(sampleRepo.toString(), null), + Collections.singletonList(new BranchSpec("*")), // JENKINS-57587 issue here + null, + null, + Collections.emptyList())); assertThat("Wildcard branch name '*' resolved to a specific checkout unexpectedly", fs, is(nullValue())); } @@ -302,7 +314,7 @@ public void mixedContent() throws Exception { SCMFile file = null; SCMFile file2 = null; SCMFile dir = null; - for (SCMFile f: children) { + for (SCMFile f : children) { names.add(f.getName()); switch (f.getName()) { case "file": @@ -329,7 +341,10 @@ public void mixedContent() throws Exception { @Test public void given_filesystem_when_askingChangesSinceSameRevision_then_changesAreEmpty() throws Exception { File gitDir = new File("."); - GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); + GitClient client = Git.with(TaskListener.NULL, new EnvVars()) + .in(gitDir) + .using("git") + .getClient(); ObjectId git261 = client.revParse(GIT_2_6_1_TAG); AbstractGitSCMSource.SCMRevisionImpl rev261 = @@ -344,7 +359,10 @@ public void given_filesystem_when_askingChangesSinceSameRevision_then_changesAre @Test public void given_filesystem_when_askingChangesSinceOldRevision_then_changesArePopulated() throws Exception { File gitDir = new File("."); - GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); + GitClient client = Git.with(TaskListener.NULL, new EnvVars()) + .in(gitDir) + .using("git") + .getClient(); ObjectId git261 = client.revParse(GIT_2_6_1_TAG); AbstractGitSCMSource.SCMRevisionImpl rev261 = @@ -363,9 +381,13 @@ public void given_filesystem_when_askingChangesSinceOldRevision_then_changesAreP } @Test - public void given_filesystem_when_askingChangesSinceNewRevision_then_changesArePopulatedButEmpty() throws Exception { + public void given_filesystem_when_askingChangesSinceNewRevision_then_changesArePopulatedButEmpty() + throws Exception { File gitDir = new File("."); - GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); + GitClient client = Git.with(TaskListener.NULL, new EnvVars()) + .in(gitDir) + .using("git") + .getClient(); ObjectId git260 = client.revParse(GIT_2_6_0_TAG); AbstractGitSCMSource.SCMRevisionImpl rev260 = @@ -375,8 +397,7 @@ public void given_filesystem_when_askingChangesSinceNewRevision_then_changesAreP ObjectId git261 = client.revParse(GIT_2_6_1_TAG); AbstractGitSCMSource.SCMRevisionImpl rev261 = new AbstractGitSCMSource.SCMRevisionImpl(new SCMHead("origin"), git261.getName()); - GitSCMFileSystem gitPlugin261FS = - new GitSCMFileSystem(client, "origin", git261.getName(), rev261); + GitSCMFileSystem gitPlugin261FS = new GitSCMFileSystem(client, "origin", git261.getName(), rev261); assertEquals(git261.getName(), gitPlugin261FS.getRevision().getHash()); assertThat(git261, not(is(git260))); @@ -395,7 +416,14 @@ public void create_SCMFileSystem_from_tag() throws Exception { sampleRepo.write("dir/subdir/file", "modified"); sampleRepo.git("commit", "--all", "--message=dev"); sampleRepo.git("tag", "v1.0"); - SCMFileSystem fs = SCMFileSystem.of(r.createFreeStyleProject(), new GitSCM(GitSCM.createRepoList(sampleRepo.toString(), null), Collections.singletonList(new BranchSpec("refs/tags/v1.0")), null, null, Collections.emptyList())); + SCMFileSystem fs = SCMFileSystem.of( + r.createFreeStyleProject(), + new GitSCM( + GitSCM.createRepoList(sampleRepo.toString(), null), + Collections.singletonList(new BranchSpec("refs/tags/v1.0")), + null, + null, + Collections.emptyList())); assertThat(fs, notNullValue()); assertThat(fs.getRoot(), notNullValue()); Iterable children = fs.getRoot().children(); @@ -431,33 +459,33 @@ public void filesystem_supports_descriptor() throws Exception { @Issue("JENKINS-42971") @Test public void calculate_head_name_with_env() throws Exception { - GitSCMFileSystem.BuilderImpl.HeadNameResult result1 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("${BRANCH}"), null, - new EnvVars("BRANCH", "master-a")); + GitSCMFileSystem.BuilderImpl.HeadNameResult result1 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate( + new BranchSpec("${BRANCH}"), null, new EnvVars("BRANCH", "master-a")); assertEquals("master-a", result1.headName); assertEquals(Constants.R_HEADS, result1.prefix); - GitSCMFileSystem.BuilderImpl.HeadNameResult result2 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("${BRANCH}"), null, - new EnvVars("BRANCH", "refs/heads/master-b")); + GitSCMFileSystem.BuilderImpl.HeadNameResult result2 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate( + new BranchSpec("${BRANCH}"), null, new EnvVars("BRANCH", "refs/heads/master-b")); assertEquals("master-b", result2.headName); assertEquals(Constants.R_HEADS, result2.prefix); - GitSCMFileSystem.BuilderImpl.HeadNameResult result3 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("refs/heads/${BRANCH}"), null, - new EnvVars("BRANCH", "master-c")); + GitSCMFileSystem.BuilderImpl.HeadNameResult result3 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate( + new BranchSpec("refs/heads/${BRANCH}"), null, new EnvVars("BRANCH", "master-c")); assertEquals("master-c", result3.headName); assertEquals(Constants.R_HEADS, result3.prefix); - GitSCMFileSystem.BuilderImpl.HeadNameResult result4 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("${BRANCH}"), null, - null); + GitSCMFileSystem.BuilderImpl.HeadNameResult result4 = + GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("${BRANCH}"), null, null); assertEquals("${BRANCH}", result4.headName); assertEquals(Constants.R_HEADS, result4.prefix); - GitSCMFileSystem.BuilderImpl.HeadNameResult result5 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("*/${BRANCH}"), null, - new EnvVars("BRANCH", "master-d")); + GitSCMFileSystem.BuilderImpl.HeadNameResult result5 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate( + new BranchSpec("*/${BRANCH}"), null, new EnvVars("BRANCH", "master-d")); assertEquals("master-d", result5.headName); assertEquals(Constants.R_HEADS, result5.prefix); - GitSCMFileSystem.BuilderImpl.HeadNameResult result6 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("*/master-e"), null, - new EnvVars("BRANCH", "dummy")); + GitSCMFileSystem.BuilderImpl.HeadNameResult result6 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate( + new BranchSpec("*/master-e"), null, new EnvVars("BRANCH", "dummy")); assertEquals("master-e", result6.headName); assertEquals(Constants.R_HEADS, result6.prefix); } @@ -468,17 +496,21 @@ public void calculate_head_name_with_env() throws Exception { @Test public void null_pointer_exception() throws Exception { File gitDir = new File("."); - GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); + GitClient client = Git.with(TaskListener.NULL, new EnvVars()) + .in(gitDir) + .using("git") + .getClient(); ObjectId git260 = client.revParse(GIT_2_6_0_TAG); AbstractGitSCMSource.SCMRevisionImpl rev260 = new AbstractGitSCMSource.SCMRevisionImpl(new SCMHead("origin"), git260.getName()); - GitSCMFileSystem.BuilderImpl.HeadNameResult result1 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("master-f"), rev260, null); + GitSCMFileSystem.BuilderImpl.HeadNameResult result1 = + GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("master-f"), rev260, null); assertEquals("master-f", result1.headName); assertEquals(Constants.R_HEADS, result1.prefix); } /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; + return java.io.File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java index 1b84d2f82a..679122be23 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java @@ -1,17 +1,18 @@ package jenkins.plugins.git; -import hudson.plugins.git.GitSCM; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; -import org.jvnet.hudson.test.RestartableJenkinsRule; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import hudson.plugins.git.GitSCM; +import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import org.jvnet.hudson.test.RestartableJenkinsRule; + public class GitSCMJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - GitSCM.DescriptorImpl gitSCM = (GitSCM.DescriptorImpl) restartableJenkinsRule.j.jenkins.getScm(GitSCM.class.getSimpleName()); + GitSCM.DescriptorImpl gitSCM = + (GitSCM.DescriptorImpl) restartableJenkinsRule.j.jenkins.getScm(GitSCM.class.getSimpleName()); assertEquals("user_name", gitSCM.getGlobalConfigName()); assertEquals("me@mail.com", gitSCM.getGlobalConfigEmail()); assertTrue("Allow second fetch setting not honored", gitSCM.isAllowSecondFetch()); diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java index d61ec5d72f..9abcf45cb7 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java @@ -7,8 +7,6 @@ public class GitSCMSourceDefaultsTest { @Test public void equalsContract() { - EqualsVerifier.forClass(GitSCMSourceDefaults.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(GitSCMSourceDefaults.class).usingGetClass().verify(); } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java index f0b88cfb07..856986b451 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java @@ -1,34 +1,52 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.cloudbees.plugins.credentials.common.StandardCredentials; import edu.umd.cs.findbugs.annotations.NonNull; +import hudson.EnvVars; +import hudson.FilePath; import hudson.model.Action; import hudson.model.Item; import hudson.model.Node; import hudson.model.TaskListener; import hudson.model.TopLevelItem; -import hudson.EnvVars; -import hudson.FilePath; +import hudson.plugins.git.ApiTokenPropertyConfiguration; import hudson.plugins.git.GitStatus; import hudson.plugins.git.GitTool; -import hudson.plugins.git.ApiTokenPropertyConfiguration; import hudson.scm.SCMDescriptor; import hudson.tools.CommandInstaller; import hudson.tools.InstallSourceProperty; import hudson.tools.ToolInstallation; +import hudson.util.StreamTaskListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; +import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - -import hudson.util.StreamTaskListener; +import javax.servlet.http.HttpServletRequest; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.plugins.git.traits.TagDiscoveryTrait; import jenkins.scm.api.SCMEventListener; @@ -48,29 +66,9 @@ import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.Collections; import org.jvnet.hudson.test.TestExtension; import org.mockito.Mockito; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - /** * @author Robin Müller */ @@ -91,20 +89,21 @@ public void setup() { @Test @Deprecated public void testSourceOwnerTriggeredByDoNotifyCommit() throws Exception { - String notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + String notifyCommitApiToken = + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); GitSCMSource gitSCMSource = new GitSCMSource("id", REMOTE, "", "*", "", false); GitSCMSourceOwner scmSourceOwner = setupGitSCMSourceOwner(gitSCMSource); jenkins.getInstance().add(scmSourceOwner, "gitSourceOwner"); gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "", notifyCommitApiToken); - SCMHeadEvent event = - jenkins.getInstance().getExtensionList(SCMEventListener.class).get(SCMEventListenerImpl.class) - .waitSCMHeadEvent(1, TimeUnit.SECONDS); + SCMHeadEvent event = jenkins.getInstance() + .getExtensionList(SCMEventListener.class) + .get(SCMEventListenerImpl.class) + .waitSCMHeadEvent(1, TimeUnit.SECONDS); assertThat(event, notNullValue()); assertThat((Iterable) event.heads(gitSCMSource).keySet(), hasItem(is(new GitBranchSCMHead("master")))); verify(scmSourceOwner, times(0)).onSCMSourceUpdated(gitSCMSource); - } private GitSCMSourceOwner setupGitSCMSourceOwner(GitSCMSource gitSCMSource) { @@ -129,8 +128,7 @@ private GitSCMSourceOwner setupGitSCMSourceOwner(GitSCMSource gitSCMSource) { * - The thread's context class loader is different than the mock's class loader * */ - public interface GitSCMSourceOwner extends TopLevelItem, SCMSourceOwner { - } + public interface GitSCMSourceOwner extends TopLevelItem, SCMSourceOwner {} @TestExtension public static class SCMEventListenerImpl extends SCMEventListener { @@ -172,40 +170,39 @@ public void telescopeFetch() throws Exception { assertThat(GitSCMTelescope.of(instance), notNullValue()); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); - Map result = instance.fetch(SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ), - new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ))); + Map result = + instance.fetch(SCMHeadObserver.collect(), null).result(); + assertThat( + result.values(), + Matchers.containsInAnyOrder( + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"), + new GitTagSCMRevision( + new GitTagSCMHead("v1.0.0", 15086193840000L), + "315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); instance.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); result = instance.fetch(SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ))); + assertThat( + result.values(), + Matchers.containsInAnyOrder( + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"))); instance.setTraits(Collections.singletonList(new TagDiscoveryTrait())); result = instance.fetch(SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ))); + assertThat( + result.values(), + Matchers.containsInAnyOrder(new GitTagSCMRevision( + new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); } @Issue("JENKINS-47526") @@ -218,44 +215,47 @@ public void telescopeFetchWithCriteria() throws Exception { assertThat(GitSCMTelescope.of(instance), notNullValue()); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); - Map result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), - SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ), - new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ))); - result = instance.fetch(new MySCMSourceCriteria("README.md"), - SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ))); + Map result = instance.fetch( + new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null) + .result(); + assertThat( + result.values(), + Matchers.containsInAnyOrder( + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"), + new GitTagSCMRevision( + new GitTagSCMHead("v1.0.0", 15086193840000L), + "315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); + result = instance.fetch(new MySCMSourceCriteria("README.md"), SCMHeadObserver.collect(), null) + .result(); + assertThat( + result.values(), + Matchers.containsInAnyOrder( + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"))); instance.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); - result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ), - new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ))); + result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null) + .result(); + assertThat( + result.values(), + Matchers.containsInAnyOrder( + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"), + new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"))); instance.setTraits(Collections.singletonList(new TagDiscoveryTrait())); - result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null).result(); - assertThat(result.values(), Matchers.containsInAnyOrder( - new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ))); + result = instance.fetch(new MySCMSourceCriteria("Jenkinsfile"), SCMHeadObserver.collect(), null) + .result(); + assertThat( + result.values(), + Matchers.containsInAnyOrder(new GitTagSCMRevision( + new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); } @Issue("JENKINS-47526") @@ -290,15 +290,20 @@ public void telescopeFetchRevision() throws Exception { assertThat(GitSCMTelescope.of(instance), notNullValue()); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); - assertThat(instance.fetch(new SCMHead("foo"), null), + assertThat( + instance.fetch(new SCMHead("foo"), null), hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480"))); - assertThat(instance.fetch(new GitBranchSCMHead("foo"), null), + assertThat( + instance.fetch(new GitBranchSCMHead("foo"), null), hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480"))); - assertThat(instance.fetch(new SCMHead("bar"), null), + assertThat( + instance.fetch(new SCMHead("bar"), null), hasProperty("hash", is("3f0b897057d8b43d3b9ff55e3fdefbb021493470"))); - assertThat(instance.fetch(new SCMHead("manchu"), null), + assertThat( + instance.fetch(new SCMHead("manchu"), null), hasProperty("hash", is("a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"))); - assertThat(instance.fetch(new GitTagSCMHead("v1.0.0", 0L), null), + assertThat( + instance.fetch(new GitTagSCMHead("v1.0.0", 0L), null), hasProperty("hash", is("315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); } @@ -312,13 +317,15 @@ public void telescopeFetchRevisionByName() throws Exception { assertThat(GitSCMTelescope.of(instance), notNullValue()); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); - assertThat(instance.fetch("foo", null, null), - hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480"))); - assertThat(instance.fetch("bar", null, null), - hasProperty("hash", is("3f0b897057d8b43d3b9ff55e3fdefbb021493470"))); - assertThat(instance.fetch("manchu", null, null), + assertThat( + instance.fetch("foo", null, null), hasProperty("hash", is("6769413a79793e242c73d7377f0006c6aea95480"))); + assertThat( + instance.fetch("bar", null, null), hasProperty("hash", is("3f0b897057d8b43d3b9ff55e3fdefbb021493470"))); + assertThat( + instance.fetch("manchu", null, null), hasProperty("hash", is("a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"))); - assertThat(instance.fetch("v1.0.0", null, null), + assertThat( + instance.fetch("v1.0.0", null, null), hasProperty("hash", is("315fd8b5cae3363b29050f1aabfc27c985e22f7e"))); } @@ -338,21 +345,22 @@ public void telescopeFetchActions() throws Exception { instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); List actions = instance.fetchActions(null, null); - assertThat(actions, + assertThat( + actions, contains(allOf( instanceOf(GitRemoteHeadRefAction.class), hasProperty("remote", is("http://git.test/telescope.git")), - hasProperty("name", is("manchu")) - )) - ); + hasProperty("name", is("manchu"))))); when(owner.getActions(GitRemoteHeadRefAction.class)) .thenReturn(Collections.singletonList((GitRemoteHeadRefAction) actions.get(0))); assertThat(instance.fetchActions(new SCMHead("foo"), null, null), is(Collections.emptyList())); assertThat(instance.fetchActions(new SCMHead("bar"), null, null), is(Collections.emptyList())); - assertThat(instance.fetchActions(new SCMHead("manchu"), null, null), contains( - instanceOf(PrimaryInstanceMetadataAction.class))); - assertThat(instance.fetchActions(new GitTagSCMHead("v1.0.0", 0L), null, null), + assertThat( + instance.fetchActions(new SCMHead("manchu"), null, null), + contains(instanceOf(PrimaryInstanceMetadataAction.class))); + assertThat( + instance.fetchActions(new GitTagSCMHead("v1.0.0", 0L), null, null), is(Collections.emptyList())); } @@ -364,9 +372,10 @@ public void gitSCMSourceShouldResolveToolsForMaster() throws Exception { return; } TaskListener log = StreamTaskListener.fromStdout(); - HelloToolInstaller inst = new HelloToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "git"); - GitTool t = new GitTool("myGit", null, Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + HelloToolInstaller inst = + new HelloToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "git"); + GitTool t = new GitTool( + "myGit", null, Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); t.getDescriptor().setInstallations(t); GitTool defaultTool = GitTool.getDefaultInstallation(); @@ -391,7 +400,8 @@ public boolean isInvoked() { } @Override - public FilePath performInstallation(ToolInstallation toolInstallation, Node node, TaskListener taskListener) throws IOException, InterruptedException { + public FilePath performInstallation(ToolInstallation toolInstallation, Node node, TaskListener taskListener) + throws IOException, InterruptedException { taskListener.error("Hello, world!"); invoked = true; return super.performInstallation(toolInstallation, node, taskListener); @@ -417,13 +427,12 @@ public boolean supportsDescriptor(SCMSourceDescriptor descriptor) { @Override public void validate(@NonNull String remote, StandardCredentials credentials) - throws IOException, InterruptedException { - } + throws IOException, InterruptedException {} @Override - protected SCMFileSystem build(@NonNull String remote, StandardCredentials credentials, - @NonNull SCMHead head, - final SCMRevision rev) throws IOException, InterruptedException { + protected SCMFileSystem build( + @NonNull String remote, StandardCredentials credentials, @NonNull SCMHead head, final SCMRevision rev) + throws IOException, InterruptedException { final String hash; if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl) { hash = ((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(); @@ -500,49 +509,39 @@ public long getTimestamp(@NonNull String remote, StandardCredentials credentials } @Override - public SCMRevision getRevision(@NonNull String remote, StandardCredentials credentials, - @NonNull String refOrHash) + public SCMRevision getRevision( + @NonNull String remote, StandardCredentials credentials, @NonNull String refOrHash) throws IOException, InterruptedException { switch (refOrHash) { case "refs/heads/foo": return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ); + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"); case "refs/heads/bar": return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ); + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"); case "refs/heads/manchu": return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ); + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"); case "refs/tags/v1.0.0": return new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), - "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ); + new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e"); } return null; } @Override - public Iterable getRevisions(@NonNull String remote, StandardCredentials credentials, - @NonNull Set referenceTypes) + public Iterable getRevisions( + @NonNull String remote, StandardCredentials credentials, @NonNull Set referenceTypes) throws IOException, InterruptedException { return Arrays.asList( new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ), + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480"), new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ), + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470"), new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ), + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc"), new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ) - ); + new GitTagSCMHead("v1.0.0", 15086193840000L), "315fd8b5cae3363b29050f1aabfc27c985e22f7e")); } @Override @@ -580,8 +579,7 @@ public Iterable children() throws IOException, InterruptedException { case "6769413a79793e242c73d7377f0006c6aea95480": return Collections.singleton(newChild("Jenkinsfile", false)); case "3f0b897057d8b43d3b9ff55e3fdefbb021493470": - return Arrays.asList(newChild("Jenkinsfile", false), - newChild("README.md", false)); + return Arrays.asList(newChild("Jenkinsfile", false), newChild("README.md", false)); case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc": return Collections.singleton(newChild("README.md", false)); case "315fd8b5cae3363b29050f1aabfc27c985e22f7e": @@ -692,6 +690,6 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java index e3db3797b8..7a66c4c3a2 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java @@ -1,5 +1,17 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; + import hudson.plugins.git.browser.BitbucketWeb; import hudson.plugins.git.extensions.impl.AuthorInChangelog; import hudson.plugins.git.extensions.impl.CheckoutOption; @@ -13,10 +25,8 @@ import hudson.plugins.git.extensions.impl.SubmoduleOption; import hudson.plugins.git.extensions.impl.UserIdentity; import hudson.plugins.git.extensions.impl.WipeWorkspace; - import java.util.Collections; import jenkins.model.Jenkins; - import jenkins.plugins.git.traits.AuthorInChangelogTrait; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.plugins.git.traits.CheckoutOptionTrait; @@ -43,18 +53,6 @@ import org.junit.rules.TestName; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - public class GitSCMSourceTraitsTest { /** * All tests in this class only use Jenkins for the extensions @@ -70,8 +68,8 @@ private GitSCMSource load() { } private GitSCMSource load(String dataSet) { - return (GitSCMSource) Jenkins.XSTREAM2.fromXML( - getClass().getResource(getClass().getSimpleName() + "/" + dataSet + ".xml")); + return (GitSCMSource) + Jenkins.XSTREAM2.fromXML(getClass().getResource(getClass().getSimpleName() + "/" + dataSet + ".xml")); } @Test @@ -109,28 +107,23 @@ public void cleancheckout_v2_trait() { private void verifyCleanCheckoutTraits(boolean deleteUntrackedNestedRepositories) { GitSCMSource instance = load(); - assertThat(instance.getTraits(), + assertThat( + instance.getTraits(), hasItems( allOf( instanceOf(CleanBeforeCheckoutTrait.class), - hasProperty("extension", + hasProperty( + "extension", hasProperty( "deleteUntrackedNestedRepositories", - is(deleteUntrackedNestedRepositories) - ) - ) - ), + is(deleteUntrackedNestedRepositories)))), allOf( instanceOf(CleanAfterCheckoutTrait.class), - hasProperty("extension", + hasProperty( + "extension", hasProperty( "deleteUntrackedNestedRepositories", - is(deleteUntrackedNestedRepositories) - ) - ) - ) - ) - ); + is(deleteUntrackedNestedRepositories)))))); } @Test @@ -140,35 +133,31 @@ public void pimpped_out() throws Exception { assertThat(instance.getId(), is("fd2380f8-d34f-48d5-8006-c34542bc4a89")); assertThat(instance.getRemote(), is("git://git.test/example.git")); assertThat(instance.getCredentialsId(), is("e4d8c11a-0d24-472f-b86b-4b017c160e9a")); - assertThat(instance.getTraits(), + assertThat( + instance.getTraits(), containsInAnyOrder( Matchers.instanceOf(BranchDiscoveryTrait.class), Matchers.allOf( instanceOf(WildcardSCMHeadFilterTrait.class), hasProperty("includes", is("foo/*")), - hasProperty("excludes", is("bar/*")) - ), + hasProperty("excludes", is("bar/*"))), Matchers.allOf( instanceOf(CheckoutOptionTrait.class), - hasProperty("extension", - hasProperty("timeout", is(5)) - ) - ), + hasProperty("extension", hasProperty("timeout", is(5)))), Matchers.allOf( instanceOf(CloneOptionTrait.class), - hasProperty("extension", + hasProperty( + "extension", allOf( hasProperty("shallow", is(true)), hasProperty("noTags", is(true)), hasProperty("reference", is("origin/foo")), hasProperty("timeout", is(3)), - hasProperty("depth", is(3)) - ) - ) - ), + hasProperty("depth", is(3))))), Matchers.allOf( instanceOf(SubmoduleOptionTrait.class), - hasProperty("extension", + hasProperty( + "extension", allOf( hasProperty("disableSubmodules", is(true)), hasProperty("recursiveSubmodules", is(true)), @@ -178,37 +167,23 @@ public void pimpped_out() throws Exception { hasProperty("timeout", is(4)), hasProperty("shallow", is(true)), hasProperty("depth", is(3)), - hasProperty("threads", is(4)) - ) - ) - ), + hasProperty("threads", is(4))))), Matchers.allOf( instanceOf(LocalBranchTrait.class), - hasProperty("extension", - hasProperty("localBranch", is("**")) - ) - ), + hasProperty("extension", hasProperty("localBranch", is("**")))), Matchers.allOf( instanceOf(CleanBeforeCheckoutTrait.class), - hasProperty("extension", - hasProperty("deleteUntrackedNestedRepositories", is(true)) - ) - ), + hasProperty("extension", hasProperty("deleteUntrackedNestedRepositories", is(true)))), Matchers.allOf( instanceOf(CleanAfterCheckoutTrait.class), - hasProperty("extension", - hasProperty("deleteUntrackedNestedRepositories", is(true)) - ) - ), + hasProperty("extension", hasProperty("deleteUntrackedNestedRepositories", is(true)))), Matchers.allOf( instanceOf(UserIdentityTrait.class), - hasProperty("extension", + hasProperty( + "extension", allOf( hasProperty("name", is("bob")), - hasProperty("email", is("bob@example.com")) - ) - ) - ), + hasProperty("email", is("bob@example.com"))))), Matchers.instanceOf(GitLFSPullTrait.class), Matchers.instanceOf(PruneStaleBranchTrait.class), Matchers.instanceOf(IgnoreOnPushNotificationTrait.class), @@ -216,23 +191,12 @@ public void pimpped_out() throws Exception { Matchers.instanceOf(WipeWorkspaceTrait.class), Matchers.allOf( instanceOf(GitBrowserSCMSourceTrait.class), - hasProperty("browser", - allOf( - instanceOf(BitbucketWeb.class), - hasProperty("repoUrl", is("foo")) - ) - ) - ), + hasProperty( + "browser", + allOf(instanceOf(BitbucketWeb.class), hasProperty("repoUrl", is("foo"))))), Matchers.allOf( instanceOf(SparseCheckoutPathsTrait.class), - hasProperty("extension", - allOf( - hasProperty("sparseCheckoutPaths", hasSize(2)) - ) - ) - ) - ) - ); + hasProperty("extension", allOf(hasProperty("sparseCheckoutPaths", hasSize(2))))))); // Legacy API assertThat(instance.getIncludes(), is("foo/*")); assertThat(instance.getExcludes(), is("bar/*")); @@ -240,18 +204,14 @@ public void pimpped_out() throws Exception { "We have trimmed the extension to only those that are supported on GitSCMSource", instance.getExtensions(), containsInAnyOrder( - Matchers.allOf( - instanceOf(CheckoutOption.class), - hasProperty("timeout", is(5)) - ), + Matchers.allOf(instanceOf(CheckoutOption.class), hasProperty("timeout", is(5))), Matchers.allOf( instanceOf(CloneOption.class), hasProperty("shallow", is(true)), hasProperty("noTags", is(true)), hasProperty("reference", is("origin/foo")), hasProperty("timeout", is(3)), - hasProperty("depth", is(3)) - ), + hasProperty("depth", is(3))), Matchers.allOf( instanceOf(SubmoduleOption.class), hasProperty("disableSubmodules", is(true)), @@ -259,33 +219,22 @@ public void pimpped_out() throws Exception { hasProperty("trackingSubmodules", is(true)), hasProperty("reference", is("origin/bar")), hasProperty("parentCredentials", is(true)), - hasProperty("timeout", is(4)) - ), - Matchers.allOf( - instanceOf(LocalBranch.class), - hasProperty("localBranch", is("**")) - ), + hasProperty("timeout", is(4))), + Matchers.allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", is("**"))), Matchers.instanceOf(CleanCheckout.class), Matchers.instanceOf(CleanBeforeCheckout.class), Matchers.allOf( instanceOf(UserIdentity.class), hasProperty("name", is("bob")), - hasProperty("email", is("bob@example.com")) - ), + hasProperty("email", is("bob@example.com"))), Matchers.instanceOf(GitLFSPull.class), Matchers.instanceOf(PruneStaleBranch.class), Matchers.instanceOf(AuthorInChangelog.class), Matchers.instanceOf(WipeWorkspace.class), Matchers.allOf( instanceOf(SparseCheckoutPaths.class), - hasProperty("sparseCheckoutPaths", hasSize(2)) - ) - ) - ); - assertThat(instance.getBrowser(), allOf( - instanceOf(BitbucketWeb.class), - hasProperty("repoUrl", is("foo")) - )); + hasProperty("sparseCheckoutPaths", hasSize(2))))); + assertThat(instance.getBrowser(), allOf(instanceOf(BitbucketWeb.class), hasProperty("repoUrl", is("foo")))); assertThat(instance.isIgnoreOnPushNotifications(), is(true)); assertThat(instance.getRemoteName(), is("origin")); assertThat(instance.getRawRefSpecs(), is("+refs/heads/*:refs/remotes/origin/*")); @@ -300,9 +249,7 @@ public void given__modernCode__when__constructor__then__traitsEmpty() throws Exc @Deprecated // Testing deprecated GitSCMSource constructor public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults1() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "*", "", false); - assertThat(instance.getTraits(), contains( - instanceOf(BranchDiscoveryTrait.class) - )); + assertThat(instance.getTraits(), contains(instanceOf(BranchDiscoveryTrait.class))); assertThat(instance.isIgnoreOnPushNotifications(), is(false)); assertThat(instance.getIncludes(), is("*")); assertThat(instance.getExcludes(), is("")); @@ -314,10 +261,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau @Deprecated // Testing deprecated GitSCMSource constructor public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults2() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "*", "", true); - assertThat(instance.getTraits(), containsInAnyOrder( - instanceOf(BranchDiscoveryTrait.class), - instanceOf(IgnoreOnPushNotificationTrait.class) - )); + assertThat( + instance.getTraits(), + containsInAnyOrder( + instanceOf(BranchDiscoveryTrait.class), instanceOf(IgnoreOnPushNotificationTrait.class))); assertThat(instance.isIgnoreOnPushNotifications(), is(true)); } @@ -325,14 +272,14 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau @Deprecated // Testing deprecated GitSCMSource constructor public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults3() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "foo/*", "", false); - assertThat(instance.getTraits(), contains( - instanceOf(BranchDiscoveryTrait.class), - allOf( - instanceOf(WildcardSCMHeadFilterTrait.class), - hasProperty("includes", is("foo/*")), - hasProperty("excludes", is("")) - ) - )); + assertThat( + instance.getTraits(), + contains( + instanceOf(BranchDiscoveryTrait.class), + allOf( + instanceOf(WildcardSCMHeadFilterTrait.class), + hasProperty("includes", is("foo/*")), + hasProperty("excludes", is(""))))); assertThat(instance.getIncludes(), is("foo/*")); assertThat(instance.getExcludes(), is("")); } @@ -341,14 +288,14 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau @Deprecated // Testing deprecated GitSCMSource constructor public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults4() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "", "foo/*", false); - assertThat(instance.getTraits(), contains( - instanceOf(BranchDiscoveryTrait.class), - allOf( - instanceOf(WildcardSCMHeadFilterTrait.class), - hasProperty("includes", is("*")), - hasProperty("excludes", is("foo/*")) - ) - )); + assertThat( + instance.getTraits(), + contains( + instanceOf(BranchDiscoveryTrait.class), + allOf( + instanceOf(WildcardSCMHeadFilterTrait.class), + hasProperty("includes", is("*")), + hasProperty("excludes", is("foo/*"))))); assertThat(instance.getIncludes(), is("*")); assertThat(instance.getExcludes(), is("foo/*")); } @@ -358,31 +305,28 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults5() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "upstream", null, "*", "", false); - assertThat(instance.getTraits(), contains( - instanceOf(BranchDiscoveryTrait.class), - allOf( - instanceOf(RemoteNameSCMSourceTrait.class), - hasProperty("remoteName", is("upstream")) - ) - )); + assertThat( + instance.getTraits(), + contains( + instanceOf(BranchDiscoveryTrait.class), + allOf(instanceOf(RemoteNameSCMSourceTrait.class), hasProperty("remoteName", is("upstream"))))); assertThat(instance.getRemoteName(), is("upstream")); } @Test @Deprecated // Testing deprecated GitSCMSource constructor public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults6() throws Exception { - GitSCMSource instance = - new GitSCMSource("id", "git://git.test/example.git", null, null, "refs/pulls/*:refs/upstream/*", "*", - "", false); - assertThat(instance.getTraits(), contains( - instanceOf(BranchDiscoveryTrait.class), - allOf( - instanceOf(RefSpecsSCMSourceTrait.class), - hasProperty("templates", contains(hasProperty("value", is("refs/pulls/*:refs/upstream/*")))) - ) - )); + GitSCMSource instance = new GitSCMSource( + "id", "git://git.test/example.git", null, null, "refs/pulls/*:refs/upstream/*", "*", "", false); + assertThat( + instance.getTraits(), + contains( + instanceOf(BranchDiscoveryTrait.class), + allOf( + instanceOf(RefSpecsSCMSourceTrait.class), + hasProperty( + "templates", + contains(hasProperty("value", is("refs/pulls/*:refs/upstream/*"))))))); assertThat(instance.getRawRefSpecs(), is("refs/pulls/*:refs/upstream/*")); } - - } diff --git a/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java b/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java index 0f60c015fa..7dfdd07e8c 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java @@ -23,6 +23,11 @@ */ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import com.cloudbees.plugins.credentials.common.StandardCredentials; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Item; @@ -65,14 +70,10 @@ import jenkins.scm.api.trait.SCMSourceTrait; import jenkins.scm.api.trait.SCMSourceTraitDescriptor; import org.acegisecurity.AccessDeniedException; -import org.junit.Test; -import static org.hamcrest.Matchers.*; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.hamcrest.MatcherAssert.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.ClassRule; +import org.junit.Test; public class GitSCMTelescopeTest /* extends AbstractGitRepository */ { @@ -80,7 +81,7 @@ public class GitSCMTelescopeTest /* extends AbstractGitRepository */ { /* REPO can be allocated once for the whole test suite so long as nothing changes it */ @ClassRule - static public final GitSampleRepoRule READ_ONLY_REPO = new GitSampleRepoRule(); + public static final GitSampleRepoRule READ_ONLY_REPO = new GitSampleRepoRule(); private final String remote; private GitSCMTelescope telescope; @@ -134,11 +135,8 @@ public void testValidate() throws Exception { * @return GitSCM with a single branch in its definition */ private GitSCM getSingleBranchSource(String repoUrl) { - UserRemoteConfig remoteConfig = new UserRemoteConfig( - repoUrl, - "origin", - "+refs/heads/master:refs/remotes/origin/master", - null); + UserRemoteConfig remoteConfig = + new UserRemoteConfig(repoUrl, "origin", "+refs/heads/master:refs/remotes/origin/master", null); List remoteConfigList = new ArrayList<>(); remoteConfigList.add(remoteConfig); BranchSpec masterBranchSpec = new BranchSpec("master"); @@ -147,11 +145,7 @@ private GitSCM getSingleBranchSource(String repoUrl) { GitRepositoryBrowser browser = new GitWeb(repoUrl); String gitTool = "Default"; List extensions = null; - GitSCM singleBranchSource = new GitSCM(remoteConfigList, - branchSpecList, - browser, - gitTool, - extensions); + GitSCM singleBranchSource = new GitSCM(remoteConfigList, branchSpecList, browser, gitTool, extensions); return singleBranchSource; } @@ -323,8 +317,7 @@ public void testGetRevisions_String_StandardCredentials() throws Exception { /* ********************* Test helper classes **************************** */ private static class ItemImpl implements Item { - public ItemImpl() { - } + public ItemImpl() {} @Override public ItemGroup getParent() { @@ -450,11 +443,11 @@ public boolean hasPermission(Permission prmsn) { private static class SCMSourceImpl extends SCMSource { - public SCMSourceImpl() { - } + public SCMSourceImpl() {} @Override - protected void retrieve(SCMSourceCriteria scmsc, SCMHeadObserver scmho, SCMHeadEvent scmhe, TaskListener tl) throws IOException, InterruptedException { + protected void retrieve(SCMSourceCriteria scmsc, SCMHeadObserver scmho, SCMHeadEvent scmhe, TaskListener tl) + throws IOException, InterruptedException { throw new UnsupportedOperationException("Not called."); } @@ -466,8 +459,8 @@ public SCM build(SCMHead scmh, SCMRevision scmr) { private static class GitSCMTelescopeImpl extends GitSCMTelescope { - final private String allowedRemote; - final private SCMRevision revision; + private final String allowedRemote; + private final SCMRevision revision; private List revisionList = new ArrayList<>(); public GitSCMTelescopeImpl(String allowedRemote, SCMRevision revision) { @@ -508,11 +501,11 @@ public boolean supportsDescriptor(SCMSourceDescriptor descriptor) { } @Override - public void validate(String remote, StandardCredentials credentials) throws IOException, InterruptedException { - } + public void validate(String remote, StandardCredentials credentials) throws IOException, InterruptedException {} @Override - public SCMFileSystem build(String remote, StandardCredentials credentials, SCMHead head, SCMRevision rev) throws IOException, InterruptedException { + public SCMFileSystem build(String remote, StandardCredentials credentials, SCMHead head, SCMRevision rev) + throws IOException, InterruptedException { GitClient client = null; AbstractGitSCMSource.SCMRevisionImpl myRev = null; if (rev != null) { @@ -523,22 +516,27 @@ public SCMFileSystem build(String remote, StandardCredentials credentials, SCMHe } @Override - public long getTimestamp(String remote, StandardCredentials credentials, String refOrHash) throws IOException, InterruptedException { + public long getTimestamp(String remote, StandardCredentials credentials, String refOrHash) + throws IOException, InterruptedException { return 12345L; } @Override - public SCMRevision getRevision(String remote, StandardCredentials credentials, String refOrHash) throws IOException, InterruptedException { + public SCMRevision getRevision(String remote, StandardCredentials credentials, String refOrHash) + throws IOException, InterruptedException { return revision; } @Override - public Iterable getRevisions(String remote, StandardCredentials credentials, Set referenceTypes) throws IOException, InterruptedException { + public Iterable getRevisions( + String remote, StandardCredentials credentials, Set referenceTypes) + throws IOException, InterruptedException { return revisionList; } @Override - public String getDefaultTarget(String remote, StandardCredentials credentials) throws IOException, InterruptedException { + public String getDefaultTarget(String remote, StandardCredentials credentials) + throws IOException, InterruptedException { return ""; } } diff --git a/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java b/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java index 91175e6762..a17b2f2f71 100644 --- a/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java +++ b/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java @@ -28,8 +28,8 @@ import com.gargoylesoftware.htmlunit.util.NameValuePair; import hudson.Launcher; import hudson.model.TaskListener; -import hudson.plugins.git.GitSCM; import hudson.plugins.git.ApiTokenPropertyConfiguration; +import hudson.plugins.git.GitSCM; import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; @@ -50,11 +50,13 @@ public final class GitSampleRepoRule extends AbstractSampleDVCSRepoRule { private static final Logger LOGGER = Logger.getLogger(GitSampleRepoRule.class.getName()); + @Override protected void before() throws Throwable { super.before(); GitSCM.ALLOW_LOCAL_CHECKOUT = true; } + @Override protected void after() { super.after(); GitSCM.ALLOW_LOCAL_CHECKOUT = false; @@ -65,7 +67,9 @@ public void git(String... cmds) throws Exception { } private static void checkGlobalConfig() throws Exception { - if (initialized) return; + if (initialized) { + return; + } initialized = true; CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); @@ -75,13 +79,16 @@ private static void checkGlobalConfig() throws Exception { public void init() throws Exception { run(true, tmp.getRoot(), "git", "version"); checkGlobalConfig(); - git("init", "--template="); // initialize without copying the installation defaults to ensure a vanilla repo that behaves the same everywhere - if (gitVersionAtLeast(2, 30)) { - // Force branch name to master even if system default is not master - // Fails on git 2.25, 2.20, 2.17, and 1.8 - // Works on git 2.30 and later + git( + "init", + "--template="); // initialize without copying the installation defaults to ensure a vanilla repo that + // behaves the same everywhere + if (gitVersionAtLeast(2, 30)) { + // Force branch name to master even if system default is not master + // Fails on git 2.25, 2.20, 2.17, and 1.8 + // Works on git 2.30 and later git("branch", "-m", "master"); - } + } write("file", ""); git("add", "file"); git("config", "user.name", "Git SampleRepoRule"); @@ -97,9 +104,12 @@ public final boolean mkdirs(String rel) throws IOException { public void notifyCommit(JenkinsRule r) throws Exception { synchronousPolling(r); - String notifyCommitToken = ApiTokenPropertyConfiguration.get().generateApiToken("notifyCommit").getString("value"); + String notifyCommitToken = ApiTokenPropertyConfiguration.get() + .generateApiToken("notifyCommit") + .getString("value"); WebResponse webResponse = r.createWebClient() - .goTo("git/notifyCommit?url=" + bareUrl() + "&token=" + notifyCommitToken, "text/plain").getWebResponse(); + .goTo("git/notifyCommit?url=" + bareUrl() + "&token=" + notifyCommitToken, "text/plain") + .getWebResponse(); LOGGER.log(Level.FINE, webResponse.getContentAsString()); for (NameValuePair pair : webResponse.getResponseHeaders()) { if (pair.getName().equals("Triggered")) { @@ -110,7 +120,11 @@ public void notifyCommit(JenkinsRule r) throws Exception { } public String head() throws Exception { - return new RepositoryBuilder().setWorkTree(sampleRepo).build().resolve(Constants.HEAD).name(); + return new RepositoryBuilder() + .setWorkTree(sampleRepo) + .build() + .resolve(Constants.HEAD) + .name(); } public File getRoot() { @@ -125,7 +139,11 @@ public boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPat final TaskListener procListener = StreamTaskListener.fromStderr(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { - int returnCode = new Launcher.LocalLauncher(procListener).launch().cmds("git", "--version").stdout(out).join(); + int returnCode = new Launcher.LocalLauncher(procListener) + .launch() + .cmds("git", "--version") + .stdout(out) + .join(); if (returnCode != 0) { LOGGER.log(Level.WARNING, "Command 'git --version' returned " + returnCode); } @@ -133,30 +151,47 @@ public boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPat LOGGER.log(Level.WARNING, "Exception checking git version " + ex); } final String versionOutput = out.toString().trim(); - final String[] fields = versionOutput.split(" ")[2].replaceAll("msysgit.", "").replaceAll("windows.", "").split("\\."); + final String[] fields = versionOutput + .split(" ")[2] + .replaceAll("msysgit.", "") + .replaceAll("windows.", "") + .split("\\."); final int gitMajor = Integer.parseInt(fields[0]); final int gitMinor = Integer.parseInt(fields[1]); final int gitPatch = Integer.parseInt(fields[2]); if (gitMajor < 1 || gitMajor > 3) { - LOGGER.log(Level.WARNING, "Unexpected git major version " + gitMajor + " parsed from '" + versionOutput + "', field:'" + fields[0] + "'"); + LOGGER.log( + Level.WARNING, + "Unexpected git major version " + gitMajor + " parsed from '" + versionOutput + "', field:'" + + fields[0] + "'"); } if (gitMinor < 0 || gitMinor > 50) { - LOGGER.log(Level.WARNING, "Unexpected git minor version " + gitMinor + " parsed from '" + versionOutput + "', field:'" + fields[1] + "'"); + LOGGER.log( + Level.WARNING, + "Unexpected git minor version " + gitMinor + " parsed from '" + versionOutput + "', field:'" + + fields[1] + "'"); } if (gitPatch < 0 || gitPatch > 20) { - LOGGER.log(Level.WARNING, "Unexpected git patch version " + gitPatch + " parsed from '" + versionOutput + "', field:'" + fields[2] + "'"); + LOGGER.log( + Level.WARNING, + "Unexpected git patch version " + gitPatch + " parsed from '" + versionOutput + "', field:'" + + fields[2] + "'"); } - return gitMajor > neededMajor || - (gitMajor == neededMajor && gitMinor > neededMinor) || - (gitMajor == neededMajor && gitMinor == neededMinor && gitPatch >= neededPatch); + return gitMajor > neededMajor + || (gitMajor == neededMajor && gitMinor > neededMinor) + || (gitMajor == neededMajor && gitMinor == neededMinor && gitPatch >= neededPatch); } public boolean hasGitLFS() { final TaskListener procListener = StreamTaskListener.fromStderr(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { - int returnCode = new Launcher.LocalLauncher(procListener).launch().cmds("git", "lfs", "version").stdout(out).join(); + int returnCode = new Launcher.LocalLauncher(procListener) + .launch() + .cmds("git", "lfs", "version") + .stdout(out) + .join(); if (returnCode != 0) { return false; } diff --git a/src/test/java/jenkins/plugins/git/GitStepTest.java b/src/test/java/jenkins/plugins/git/GitStepTest.java index eacc470cef..d514fde381 100644 --- a/src/test/java/jenkins/plugins/git/GitStepTest.java +++ b/src/test/java/jenkins/plugins/git/GitStepTest.java @@ -24,6 +24,10 @@ package jenkins.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.*; +import static org.junit.Assume.assumeTrue; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.IdCredentials; @@ -44,8 +48,6 @@ import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepConfigTester; -import static org.junit.Assert.*; -import static org.junit.Assume.assumeTrue; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; @@ -55,7 +57,6 @@ import org.junit.runner.OrderWith; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static java.util.concurrent.TimeUnit.SECONDS; /** * @author Nicolas De Loof @@ -65,8 +66,10 @@ public class GitStepTest { @Rule public JenkinsRule r = new JenkinsRule(); + @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + @Rule public GitSampleRepoRule otherRepo = new GitSampleRepoRule(); @@ -78,6 +81,7 @@ public static void setGitDefaults() throws Exception { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -104,8 +108,7 @@ public void roundtrip() throws Exception { public void roundtrip_withcredentials() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); IdCredentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, null, "user", "pass"); - CredentialsProvider.lookupStores(r.jenkins).iterator().next() - .addCredentials(Domain.global(), c); + CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); GitStep step = new GitStep("git@github.com:jenkinsci/workflow-plugin.git"); step.setCredentialsId(c.getId()); Step roundtrip = new StepConfigTester(r).configRoundTrip(step); @@ -119,12 +122,12 @@ public void basicCloneAndUpdate() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "demo"); r.createOnlineSlave(Label.get("remote")); p.setDefinition(new CpsFlowDefinition( - "node('remote') {\n" + - " ws {\n" + - " git(url: $/" + sampleRepo + "/$, poll: false, changelog: false)\n" + - " archive '**'\n" + - " }\n" + - "}", true)); + "node('remote') {\n" + " ws {\n" + + " git(url: $/" + + sampleRepo + "/$, poll: false, changelog: false)\n" + " archive '**'\n" + + " }\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("Cloning the remote Git repository", b); // GitSCM.retrieveChanges assertTrue(b.getArtifactManager().root().child("file").isFile()); @@ -144,13 +147,13 @@ public void changelogAndPolling() throws Exception { p.addTrigger(new SCMTrigger("")); // no schedule, use notifyCommit only r.createOnlineSlave(Label.get("remote")); p.setDefinition(new CpsFlowDefinition( - "node('remote') {\n" + - " ws {\n" + - " git($/" + sampleRepo + "/$)\n" + - " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + - " echo \"token macro expanded branch is ${tokenBranch}\"\n" + - " }\n" + - "}", true)); + "node('remote') {\n" + " ws {\n" + + " git($/" + + sampleRepo + "/$)\n" + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + + " echo \"token macro expanded branch is ${tokenBranch}\"\n" + + " }\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior sampleRepo.write("nextfile", ""); @@ -185,17 +188,17 @@ public void multipleSCMs() throws Exception { p.addTrigger(new SCMTrigger("")); p.setQuietPeriod(3); // so it only does one build p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " ws {\n" + - " dir('main') {\n" + - " git($/" + sampleRepo + "/$)\n" + - " }\n" + - " dir('other') {\n" + - " git($/" + otherRepo + "/$)\n" + - " }\n" + - " archive '**'\n" + - " }\n" + - "}", true)); + "node {\n" + " ws {\n" + + " dir('main') {\n" + + " git($/" + + sampleRepo + "/$)\n" + " }\n" + + " dir('other') {\n" + + " git($/" + + otherRepo + "/$)\n" + " }\n" + + " archive '**'\n" + + " }\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); VirtualFile artifacts = b.getArtifactManager().root(); assertTrue(artifacts.child("main/file").isFile()); @@ -215,9 +218,13 @@ public void multipleSCMs() throws Exception { assertTrue(artifacts.child("other/otherfile2").isFile()); Iterator scms = p.getSCMs().iterator(); assertTrue(scms.hasNext()); - assertEquals(sampleRepo.toString(), ((GitSCM) scms.next()).getRepositories().get(0).getURIs().get(0).toString()); + assertEquals( + sampleRepo.toString(), + ((GitSCM) scms.next()).getRepositories().get(0).getURIs().get(0).toString()); assertTrue(scms.hasNext()); - assertEquals(otherRepo.toString(), ((GitSCM) scms.next()).getRepositories().get(0).getURIs().get(0).toString()); + assertEquals( + otherRepo.toString(), + ((GitSCM) scms.next()).getRepositories().get(0).getURIs().get(0).toString()); assertFalse(scms.hasNext()); List> changeSets = b.getChangeSets(); assertEquals(2, changeSets.size()); @@ -248,14 +255,14 @@ public void identicalGitSCMs() throws Exception { otherRepo.git("commit", "--message=init"); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "demo"); p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " dir('main') {\n" + - " git($/" + otherRepo + "/$)\n" + - " }\n" + - " dir('other') {\n" + - " git($/" + otherRepo + "/$)\n" + - " }\n" + - "}", true)); + "node {\n" + " dir('main') {\n" + + " git($/" + + otherRepo + "/$)\n" + " }\n" + + " dir('other') {\n" + + " git($/" + + otherRepo + "/$)\n" + " }\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); assertEquals(1, b.getActions(BuildData.class).size()); assertEquals(0, b.getActions(GitTagAction.class).size()); @@ -279,15 +286,15 @@ public void commitToWorkspace() throws Exception { sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( - "def rungit(cmd) {def gitcmd = \"git ${cmd}\"; if (isUnix()) {sh gitcmd} else {bat gitcmd}}\n" + - "node {\n" + - " git url: $/" + sampleRepo + "/$\n" + - " writeFile file: 'file', text: 'edited by build'\n" + - " rungit 'commit --all --message=edits'\n" + - " rungit 'show master'\n" + - "}", true)); + "def rungit(cmd) {def gitcmd = \"git ${cmd}\"; if (isUnix()) {sh gitcmd} else {bat gitcmd}}\n" + + "node {\n" + + " git url: $/" + + sampleRepo + "/$\n" + " writeFile file: 'file', text: 'edited by build'\n" + + " rungit 'commit --all --message=edits'\n" + + " rungit 'show master'\n" + + "}", + true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.waitForMessage("+edited by build", b); } - } diff --git a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java index 079b4acdf6..e01908a216 100644 --- a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java @@ -1,5 +1,12 @@ package jenkins.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.io.FileMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assume.assumeTrue; + import com.cloudbees.plugins.credentials.*; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; @@ -11,9 +18,14 @@ import hudson.slaves.DumbSlave; import hudson.tools.*; import hudson.util.StreamTaskListener; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.Set; import jenkins.model.Jenkins; import jenkins.plugins.git.traits.BranchDiscoveryTrait; - import org.jenkinsci.plugins.gitclient.JGitApacheTool; import org.jenkinsci.plugins.gitclient.JGitTool; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; @@ -31,20 +43,6 @@ import org.jvnet.hudson.test.TestExtension; import org.mockito.Mockito; -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.Set; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.io.FileMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; - /** * The test aims to functionally validate "estimation of size" and "git implementation recommendation" from a * cached directory and from plugin extensions. @@ -58,7 +56,8 @@ public class GitToolChooserTest { @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + static final String GitBranchSCMHead_DEV_MASTER = + "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; private CredentialsStore store = null; @@ -66,8 +65,8 @@ public class GitToolChooserTest { @Before public void enableSystemCredentialsProvider() { - SystemCredentialsProvider.getInstance().setDomainCredentialsMap( - Collections.singletonMap(Domain.global(), Collections.emptyList())); + SystemCredentialsProvider.getInstance() + .setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; @@ -84,6 +83,7 @@ public void resetRepositorySizeCache() { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -114,7 +114,7 @@ public void testResolveGitTool() throws IOException, InterruptedException { GitTool JTool = new JGitTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, JTool); - GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL,true); + GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL, true); assertThat(r.getGitTool(), containsString(isWindows() ? "git.exe" : "git")); } @@ -137,15 +137,18 @@ public void testResolveGitToolWithJenkins() throws IOException, InterruptedExcep Item context = Mockito.mock(Item.class); String credentialsId = null; - TestToolInstaller inst = new TestToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "updated/git"); - GitTool t = new GitTool("myGit", "default/git", Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + TestToolInstaller inst = + new TestToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "updated/git"); + GitTool t = new GitTool( + "myGit", + "default/git", + Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); GitTool tool = new GitTool("my-git", "git", Collections.emptyList()); GitTool JTool = new JGitTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, JTool, t); - GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL,true); + GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL, true); assertThat(r.getGitTool(), containsString("updated/git")); } @@ -173,26 +176,41 @@ public void testResolutionGitToolOnAgent() throws Exception { agent.setMode(Node.Mode.NORMAL); agent.setLabelString("agent-windows"); - TestToolInstaller inst = new TestToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "myGit/git"); - GitTool toolOnMaster = new GitTool("myGit", "default/git", Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + TestToolInstaller inst = + new TestToolInstaller(jenkins.jenkins.getSelfLabel().getName(), "echo Hello", "myGit/git"); + GitTool toolOnMaster = new GitTool( + "myGit", + "default/git", + Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); TestToolInstaller instonAgent = new TestToolInstaller("agent-windows", "echo Hello", "my-git/git"); - GitTool toolOnAgent = new GitTool("my-git", "git", Collections.singletonList(new InstallSourceProperty(Collections.singletonList(instonAgent)))); + GitTool toolOnAgent = new GitTool( + "my-git", + "git", + Collections.singletonList(new InstallSourceProperty(Collections.singletonList(instonAgent)))); GitTool JTool = new JGitTool(Collections.emptyList()); - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(toolOnMaster, toolOnAgent, JTool); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnMaster.getName(), toolOnMaster.getHome()))); + jenkins.jenkins + .getDescriptorByType(GitTool.DescriptorImpl.class) + .setInstallations(toolOnMaster, toolOnAgent, JTool); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), + toolOnMaster.getName(), + toolOnMaster.getHome()))); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnAgent.getName(), toolOnAgent.getHome()))); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), + toolOnAgent.getName(), + toolOnAgent.getHome()))); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), JTool.getName(), null))); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), JTool.getName(), null))); - GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, agent, TaskListener.NULL,true); + GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, agent, TaskListener.NULL, true); assertThat(r.getGitTool(), containsString("my-git/git")); } @@ -214,10 +232,11 @@ public void testSizeEstimationWithNoGitCache() throws Exception { List list = jenkins.jenkins.getItems(); - //Since no installation is provided, the gitExe will be git + // Since no installation is provided, the gitExe will be git GitTool rTool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - GitToolChooser repoSizeEstimator = new GitToolChooser(instance.getRemote(), list.get(0), "github", rTool, null, TaskListener.NULL, true); + GitToolChooser repoSizeEstimator = + new GitToolChooser(instance.getRemote(), list.get(0), "github", rTool, null, TaskListener.NULL, true); String tool = repoSizeEstimator.getGitTool(); // The class get a size < 5M from APIs and wants to recommend `jgit` but will return NONE instead @@ -265,7 +284,8 @@ public void testSizeEstimationWithGitCache() throws Exception { List list = jenkins.jenkins.getItems(); - GitToolChooser repoSizeEstimator = new GitToolChooser(source.getRemote(), list.get(0), "github", tool, null,TaskListener.NULL,true); + GitToolChooser repoSizeEstimator = + new GitToolChooser(source.getRemote(), list.get(0), "github", tool, null, TaskListener.NULL, true); /* Since the size of repository is 21.785 KiBs, the estimator should suggest "jgit" as an implementation */ @@ -275,13 +295,17 @@ public void testSizeEstimationWithGitCache() throws Exception { String permutedRemote = source.getRemote(); String suffix = ".git"; if (permutedRemote.endsWith(suffix)) { - permutedRemote = permutedRemote.substring(0, permutedRemote.length() - suffix.length()); // Remove trailing ".git" suffix + permutedRemote = permutedRemote.substring( + 0, permutedRemote.length() - suffix.length()); // Remove trailing ".git" suffix } else { permutedRemote = permutedRemote + suffix; // Add trailing ".git" suffix } - GitToolChooser permutedRepoSizeEstimator = new GitToolChooser(permutedRemote, list.get(0), "github", tool, null, TaskListener.NULL, true); - assertThat("Alternative repository name should find the cache", - permutedRepoSizeEstimator.getGitTool(), containsString("jgit")); + GitToolChooser permutedRepoSizeEstimator = + new GitToolChooser(permutedRemote, list.get(0), "github", tool, null, TaskListener.NULL, true); + assertThat( + "Alternative repository name should find the cache", + permutedRepoSizeEstimator.getGitTool(), + containsString("jgit")); } /* Test the remoteAlternatives permutation of git repo URLs */ @@ -291,7 +315,8 @@ public void testRemoteAlternatives() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); GitTool tool = new JGitTool(Collections.emptyList()); - GitToolChooser nullRemoteSizeEstimator = new GitToolChooser("git://example.com/git/git.git", null, null, tool, null, TaskListener.NULL, true); + GitToolChooser nullRemoteSizeEstimator = + new GitToolChooser("git://example.com/git/git.git", null, null, tool, null, TaskListener.NULL, true); assertThat(nullRemoteSizeEstimator.remoteAlternatives(null), is(empty())); assertThat(nullRemoteSizeEstimator.remoteAlternatives(""), is(empty())); @@ -303,18 +328,19 @@ public void testRemoteAlternatives() throws Exception { * a valid alias for every other alternative in the list. */ String[] remoteAlternatives = { - "git://example.com/jenkinsci/git-plugin", - "git://example.com/jenkinsci/git-plugin.git", - "git@example.com:jenkinsci/git-plugin", - "git@example.com:jenkinsci/git-plugin.git", - "https://example.com/jenkinsci/git-plugin", - "https://example.com/jenkinsci/git-plugin.git", - "ssh://git@example.com/jenkinsci/git-plugin", - "ssh://git@example.com/jenkinsci/git-plugin.git", + "git://example.com/jenkinsci/git-plugin", + "git://example.com/jenkinsci/git-plugin.git", + "git@example.com:jenkinsci/git-plugin", + "git@example.com:jenkinsci/git-plugin.git", + "https://example.com/jenkinsci/git-plugin", + "https://example.com/jenkinsci/git-plugin.git", + "ssh://git@example.com/jenkinsci/git-plugin", + "ssh://git@example.com/jenkinsci/git-plugin.git", }; for (String remote : remoteAlternatives) { - GitToolChooser sizeEstimator = new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); Set alternatives = sizeEstimator.remoteAlternatives(remote); assertThat("Remote: " + remote, alternatives, containsInAnyOrder(remoteAlternatives)); } @@ -322,7 +348,8 @@ public void testRemoteAlternatives() throws Exception { /* Test remote that ends with '/' */ for (String remote : remoteAlternatives) { remote = remote + "/"; - GitToolChooser sizeEstimator = new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); Set alternatives = sizeEstimator.remoteAlternatives(remote); assertThat("Remote+'/': " + remote, alternatives, containsInAnyOrder(remoteAlternatives)); } @@ -335,28 +362,31 @@ public void testConvertToCanonicalURL() throws Exception { GitTool tool = new JGitTool(Collections.emptyList()); String[] remoteAlternatives = { - "git://example.com/jenkinsci/git-plugin", - "git://example.com/jenkinsci/git-plugin.git", - "git@example.com:jenkinsci/git-plugin", - "git@example.com:jenkinsci/git-plugin.git", - "https://example.com/jenkinsci/git-plugin", - "https://example.com/jenkinsci/git-plugin.git", - "ssh://git@example.com/jenkinsci/git-plugin", - "ssh://git@example.com/jenkinsci/git-plugin.git", + "git://example.com/jenkinsci/git-plugin", + "git://example.com/jenkinsci/git-plugin.git", + "git@example.com:jenkinsci/git-plugin", + "git@example.com:jenkinsci/git-plugin.git", + "https://example.com/jenkinsci/git-plugin", + "https://example.com/jenkinsci/git-plugin.git", + "ssh://git@example.com/jenkinsci/git-plugin", + "ssh://git@example.com/jenkinsci/git-plugin.git", }; String actualNormalizedURL = "https://example.com/jenkinsci/git-plugin.git"; for (String remote : remoteAlternatives) { - GitToolChooser sizeEstimator = new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); String expectedNormalizedURL = sizeEstimator.convertToCanonicalURL(remote); assertThat("Remote: " + remote, expectedNormalizedURL, is(actualNormalizedURL)); } /* Check behavior in case of any other format of git repo URL*/ String otherRemote = "file://srv/git/repo"; - GitToolChooser sizeEstimator = new GitToolChooser(otherRemote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); - assertThat("Remote: " + otherRemote, sizeEstimator.convertToCanonicalURL(otherRemote), is(otherRemote + ".git")); + GitToolChooser sizeEstimator = + new GitToolChooser(otherRemote, null, null, tool, null, TaskListener.NULL, random.nextBoolean()); + assertThat( + "Remote: " + otherRemote, sizeEstimator.convertToCanonicalURL(otherRemote), is(otherRemote + ".git")); } /* @@ -377,8 +407,8 @@ public void testSizeEstimationWithAPIForGit() throws Exception { // Assuming no tool is installed and git is present in the machine GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), containsString("git")); } @@ -398,11 +428,11 @@ public void testSizeEstimationWithAPIForJGit() throws Exception { GitTool tool = new JGitTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); - buildAProject(sampleRepo, false); List list = jenkins.jenkins.getItems(); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), containsString("jgit")); } @@ -423,7 +453,8 @@ public void testSizeEstimationWithBitbucketAPIs() throws Exception { // Assuming no tool is installed by user and git is present in the machine GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool,null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is("NONE")); } @@ -445,7 +476,8 @@ public void testSizeEstimationWithException() throws Exception { // Assuming no tool is installed by user and git is present in the machine GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool,null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is("NONE")); } @@ -465,7 +497,8 @@ public void testSizeEstimationWithNoCredentials() throws Exception { // Assuming no tool is installed by user and git is present in the machine GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - GitToolChooser sizeEstimator = new GitToolChooser(sampleRepo.toString(), list.get(0), null, tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(sampleRepo.toString(), list.get(0), null, tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is("NONE")); } @@ -485,12 +518,12 @@ public void testGitToolChooserWithCustomGitTool() throws Exception { GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); - GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true); + GitToolChooser gitToolChooser = + new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL, true); - //According to size of repo, "jgit" should be recommended but it is not installed by the user - //Hence, in this case GitToolChooser should return a NONE + // According to size of repo, "jgit" should be recommended but it is not installed by the user + // Hence, in this case GitToolChooser should return a NONE assertThat(gitToolChooser.getGitTool(), is("NONE")); - } @Test @@ -505,7 +538,8 @@ public void testGitToolChooserWithBothGitAndJGit() throws Exception { GitTool jgitTool = new JGitTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool); - GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true); + GitToolChooser gitToolChooser = + new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL, true); assertThat(gitToolChooser.getGitTool(), is("jgit")); } @@ -523,9 +557,12 @@ public void testGitToolChooserWithAllTools() throws Exception { GitTool tool = new GitTool("my-git", "/usr/bin/git", Collections.emptyList()); GitTool jgitTool = new JGitTool(Collections.emptyList()); GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool, jGitApacheTool); + jenkins.jenkins + .getDescriptorByType(GitTool.DescriptorImpl.class) + .setInstallations(tool, jgitTool, jGitApacheTool); - GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true); + GitToolChooser gitToolChooser = + new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL, true); assertThat(gitToolChooser.getGitTool(), is("jgit")); } @@ -545,7 +582,8 @@ public void testGitToolChooserWithJGitApache() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jGitApacheTool); - GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL,true); + GitToolChooser gitToolChooser = + new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL, true); assertThat(gitToolChooser.getGitTool(), is("jgitapache")); } @@ -563,7 +601,8 @@ public void testGitToolChooserWithJGitApacheAndGit() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(jGitApacheTool); - GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL,true); + GitToolChooser gitToolChooser = + new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL, true); assertThat(gitToolChooser.getGitTool(), is("jgitapache")); } @@ -585,7 +624,8 @@ public void testGitToolChooserWithDefaultTool() throws Exception { // Assuming no tool is installed and git is present in the machine GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), containsString("git")); } @@ -608,8 +648,11 @@ public void testGitToolChooserWithOnlyJGit() throws Exception { // Assuming no tool is installed and git is present in the machine String gitExe = jGitTool.getGitExe(); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", jGitTool, null, TaskListener.NULL,true); - assertThat(sizeEstimator.getGitTool(), is("jgit")); // Since git is not available, we suggest `jgit` which doesn't make any difference + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", jGitTool, null, TaskListener.NULL, true); + assertThat( + sizeEstimator.getGitTool(), + is("jgit")); // Since git is not available, we suggest `jgit` which doesn't make any difference } @Test @@ -631,7 +674,8 @@ public void testGitToolChooserWithCustomGitTool_2() throws Exception { // Assuming no tool is installed and git is present in the machine String gitExe = tool.getGitExe(); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is(isWindows() ? "git.exe" : "git")); } @@ -647,7 +691,9 @@ public void testGitToolChooserWithAllTools_2() throws Exception { GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); GitTool jgitTool = new JGitTool(Collections.emptyList()); GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); - jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool, jGitApacheTool); + jenkins.jenkins + .getDescriptorByType(GitTool.DescriptorImpl.class) + .setInstallations(tool, jgitTool, jGitApacheTool); buildAProject(sampleRepo, false); @@ -656,7 +702,8 @@ public void testGitToolChooserWithAllTools_2() throws Exception { // Assuming no tool is installed and git is present in the machine String gitExe = tool.getGitExe(); - GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true); + GitToolChooser sizeEstimator = + new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is(isWindows() ? "git.exe" : "git")); } @@ -697,7 +744,8 @@ public void testSizeEstimationWithNoRemoteConfig() throws Exception { // Use JGit as the git tool for this NPE check GitTool jgitTool = new JGitTool(Collections.emptyList()); - GitToolChooser sizeEstimator = new GitToolChooser(sampleRepo.toString(), list.get(0), null, jgitTool, null, TaskListener.NULL, true); + GitToolChooser sizeEstimator = + new GitToolChooser(sampleRepo.toString(), list.get(0), null, jgitTool, null, TaskListener.NULL, true); assertThat(sizeEstimator.getGitTool(), is("NONE")); } @@ -771,14 +819,14 @@ public boolean isInvoked() { } @Override - public FilePath performInstallation(ToolInstallation toolInstallation, Node node, TaskListener taskListener) throws IOException, InterruptedException { + public FilePath performInstallation(ToolInstallation toolInstallation, Node node, TaskListener taskListener) + throws IOException, InterruptedException { taskListener.error("Hello, world!"); invoked = true; return super.performInstallation(toolInstallation, node, taskListener); } } - private void buildAProject(GitSampleRepoRule sampleRepo, boolean noCredentials) throws Exception { WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( @@ -789,22 +837,22 @@ private void buildAProject(GitSampleRepoRule sampleRepo, boolean noCredentials) + " )\n" + " def tokenBranch = tm '${GIT_BRANCH,fullName=false}'\n" + " echo \"token macro expanded branch is ${tokenBranch}\"\n" - + "}", true)); + + "}", + true)); WorkflowRun b = jenkins.buildAndAssertSuccess(p); if (!noCredentials) { jenkins.waitForMessage("using credential github", b); } - jenkins.waitForMessage("token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior + jenkins.waitForMessage( + "token macro expanded branch is remotes/origin/master", b); // Unexpected but current behavior } /* Attempt to perform a checkout without defining a remote repository. Expected to fail, but should not report NPE */ private void failAProject(GitSampleRepoRule sampleRepo) throws Exception { - WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "intentionally-failing-job-without-remote-config"); - p.setDefinition(new CpsFlowDefinition("node {\n" - + " checkout(\n" - + " [$class: 'GitSCM']\n" - + " )\n" - + "}", true)); + WorkflowJob p = + jenkins.jenkins.createProject(WorkflowJob.class, "intentionally-failing-job-without-remote-config"); + p.setDefinition( + new CpsFlowDefinition("node {\n" + " checkout(\n" + " [$class: 'GitSCM']\n" + " )\n" + "}", true)); WorkflowRun b = jenkins.buildAndAssertStatus(hudson.model.Result.FAILURE, p); jenkins.waitForMessage("Couldn't find any revision to build", b); } @@ -815,6 +863,6 @@ private StandardCredentials createCredential(CredentialsScope scope, String id) /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } } diff --git a/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java index 18891a961c..b73e1ed47a 100644 --- a/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java @@ -1,5 +1,15 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertEquals; + import hudson.plugins.git.GitTool; import hudson.tools.BatchCommandInstaller; import hudson.tools.CommandInstaller; @@ -13,20 +23,11 @@ import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; import org.jvnet.hudson.test.RestartableJenkinsRule; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.core.AllOf.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - public class GitToolJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - final ToolDescriptor descriptor = (ToolDescriptor) restartableJenkinsRule.j.jenkins.getDescriptor(GitTool.class); + final ToolDescriptor descriptor = + (ToolDescriptor) restartableJenkinsRule.j.jenkins.getDescriptor(GitTool.class); final ToolInstallation[] installations = descriptor.getInstallations(); assertThat(installations, arrayWithSize(1)); assertEquals("Default", installations[0].getName()); @@ -34,21 +35,24 @@ protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenk final DescribableList, ToolPropertyDescriptor> properties = installations[0].getProperties(); assertThat(properties, hasSize(1)); final ToolProperty property = properties.get(0); - assertThat(((InstallSourceProperty)property).installers, + assertThat( + ((InstallSourceProperty) property).installers, containsInAnyOrder( - allOf(instanceOf(CommandInstaller.class), + allOf( + instanceOf(CommandInstaller.class), hasProperty("command", equalTo("install git")), hasProperty("toolHome", equalTo("/my/path/1")), hasProperty("label", equalTo("git command"))), - allOf(instanceOf(ZipExtractionInstaller.class), + allOf( + instanceOf(ZipExtractionInstaller.class), hasProperty("url", equalTo("http://fake.com")), hasProperty("subdir", equalTo("/my/path/2")), hasProperty("label", equalTo("git zip"))), - allOf(instanceOf(BatchCommandInstaller.class), + allOf( + instanceOf(BatchCommandInstaller.class), hasProperty("command", equalTo("run batch command")), hasProperty("toolHome", equalTo("/my/path/3")), - hasProperty("label", equalTo("git batch"))) - )); + hasProperty("label", equalTo("git batch"))))); } @Override diff --git a/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java b/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java index c6cd22103a..49f0442cbc 100644 --- a/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java +++ b/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java @@ -1,5 +1,10 @@ package jenkins.plugins.git; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assume.assumeTrue; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; @@ -7,7 +12,6 @@ import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import hudson.EnvVars; import hudson.FilePath; - import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Item; @@ -15,6 +19,14 @@ import hudson.plugins.git.GitTool; import hudson.tasks.BatchFile; import hudson.tasks.Shell; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Random; import jenkins.model.Jenkins; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FilenameUtils; @@ -39,20 +51,6 @@ import org.jvnet.hudson.test.BuildWatcher; import org.jvnet.hudson.test.JenkinsRule; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Collection; -import java.util.Random; - -import static org.junit.Assume.assumeTrue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static java.util.concurrent.TimeUnit.SECONDS; - @OrderWith(RandomOrder.class) @RunWith(Parameterized.class) public class GitUsernamePasswordBindingTest { @@ -76,6 +74,7 @@ public static Collection data() { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -96,7 +95,8 @@ private boolean isTimeAvailable() { private final GitTool gitToolInstance; - private final String credentialID = DigestUtils.sha256Hex(("Git Usernanme and Password Binding").getBytes(StandardCharsets.UTF_8)); + private final String credentialID = + DigestUtils.sha256Hex(("Git Usernanme and Password Binding").getBytes(StandardCharsets.UTF_8)); private File rootDir = null; private FilePath rootFilePath = null; @@ -106,30 +106,27 @@ private boolean isTimeAvailable() { private static final Random random = new Random(); private static String[] userNames = { - "adwesw-unique", - "bceas-unique", - "many-words-in-a-user-name-because-we-can", - "r-Name", - "randomName", + "adwesw-unique", "bceas-unique", "many-words-in-a-user-name-because-we-can", "r-Name", "randomName", }; private static String[] passwords = { - "&Ampersand&", - "He said \"Hello\", then left.", - "default=@#(*^!", - "here's-a-quote", - "special%%_342@**", + "&Ampersand&", "He said \"Hello\", then left.", "default=@#(*^!", "here's-a-quote", "special%%_342@**", }; private static GitTool[] gitTools = { - new GitTool("Default", "git", null), - new GitTool("git", "git", null), - new JGitApacheTool(), - new JGitTool(), + new GitTool("Default", "git", null), new GitTool("git", "git", null), new JGitApacheTool(), new JGitTool(), }; /* Create two test data items using random selections from the larger set of data */ - private static Object[][] testData = new Object[][]{ - {userNames[random.nextInt(userNames.length)], passwords[random.nextInt(passwords.length)], gitTools[random.nextInt(gitTools.length)]}, - {userNames[random.nextInt(userNames.length)], passwords[random.nextInt(passwords.length)], gitTools[random.nextInt(gitTools.length)]}, + private static Object[][] testData = new Object[][] { + { + userNames[random.nextInt(userNames.length)], + passwords[random.nextInt(passwords.length)], + gitTools[random.nextInt(gitTools.length)] + }, + { + userNames[random.nextInt(userNames.length)], + passwords[random.nextInt(passwords.length)], + gitTools[random.nextInt(gitTools.length)] + }, }; public GitUsernamePasswordBindingTest(String username, String password, GitTool gitToolInstance) { @@ -140,20 +137,28 @@ public GitUsernamePasswordBindingTest(String username, String password, GitTool @Before public void basicSetup() throws IOException { - //File init + // File init rootDir = tempFolder.getRoot(); rootFilePath = new FilePath(rootDir.getAbsoluteFile()); - //Credential init - credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, credentialID, "Git Username and Password Binding Test", this.username, this.password); + // Credential init + credentials = new UsernamePasswordCredentialsImpl( + CredentialsScope.GLOBAL, + credentialID, + "Git Username and Password Binding Test", + this.username, + this.password); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), credentials); - //GitUsernamePasswordBinding instance + // GitUsernamePasswordBinding instance gitCredBind = new GitUsernamePasswordBinding(gitToolInstance.getName(), credentials.getId()); assertThat(gitCredBind.type(), is(StandardUsernamePasswordCredentials.class)); - //Setting Git Tool - Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getDefaultInstallers().clear(); + // Setting Git Tool + Jenkins.get() + .getDescriptorByType(GitTool.DescriptorImpl.class) + .getDefaultInstallers() + .clear(); Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(gitToolInstance); } @@ -171,8 +176,9 @@ private String shellCheck() { public void test_EnvironmentVariables_FreeStyleProject() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject prj = r.createFreeStyleProject(); - prj.getBuildWrappersList().add(new SecretBuildWrapper(Collections.> - singletonList(new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); + prj.getBuildWrappersList() + .add(new SecretBuildWrapper(Collections.>singletonList( + new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); prj.getBuildersList().add(isWindows() ? new BatchFile(batchCheck(isCliGitTool())) : new Shell(shellCheck())); r.configRoundtrip((Item) prj); @@ -181,14 +187,14 @@ public void test_EnvironmentVariables_FreeStyleProject() throws Exception { List> bindings = wrapper.getBindings(); assertThat(bindings.size(), is(1)); MultiBinding binding = bindings.get(0); - if(isCliGitTool()) { + if (isCliGitTool()) { assertThat(((GitUsernamePasswordBinding) binding).getGitToolName(), equalTo(gitToolInstance.getName())); - }else { + } else { assertThat(((GitUsernamePasswordBinding) binding).getGitToolName(), equalTo("")); } FreeStyleBuild b = r.buildAndAssertSuccess(prj); - if(credentials.isUsernameSecret()) { + if (credentials.isUsernameSecret()) { r.assertLogNotContains(this.username, b); r.assertLogContains("GIT_USERNAME=****", b); } else { @@ -197,16 +203,16 @@ public void test_EnvironmentVariables_FreeStyleProject() throws Exception { r.assertLogNotContains(this.password, b); r.assertLogContains("GIT_PASSWORD=****", b); - //Assert Keys + // Assert Keys assertThat(binding.variables(b), hasItem("GIT_USERNAME")); assertThat(binding.variables(b), hasItem("GIT_PASSWORD")); - //Assert credential values + // Assert credential values String fileContents = b.getWorkspace().child("auth.txt").readToString().trim(); - if(credentials.isUsernameSecret()) { + if (credentials.isUsernameSecret()) { assertThat(fileContents, containsString("GIT_USERNAME=" + this.username)); } assertThat(fileContents, containsString("GIT_PASSWORD=" + this.password)); - //Assert Git specific env variables based on its version + // Assert Git specific env variables based on its version if (isCliGitTool()) { if (isWindows()) { assertThat(fileContents, containsString("GCM_INTERACTIVE=false")); @@ -229,7 +235,8 @@ public void test_EnvironmentVariables_PipelineJob() throws Exception { String pipeline = "" + "node {\n" - + " withCredentials([" + keyword + "(credentialsId: '" + credentialID + "'" + gitToolNameArg + ")]) {\n" + + " withCredentials([" + keyword + "(credentialsId: '" + credentialID + "'" + gitToolNameArg + + ")]) {\n" + " if (isUnix()) {\n" + " sh '" + shellCheck() + "'\n" + " } else {\n" @@ -241,7 +248,7 @@ public void test_EnvironmentVariables_PipelineJob() throws Exception { WorkflowRun b = project.scheduleBuild2(0).waitForStart(); r.waitForCompletion(b); r.assertBuildStatusSuccess(b); - if(credentials.isUsernameSecret()) { + if (credentials.isUsernameSecret()) { r.assertLogNotContains(this.username, b); r.assertLogContains("GIT_USERNAME=****", b); } else { @@ -249,9 +256,13 @@ public void test_EnvironmentVariables_PipelineJob() throws Exception { } r.assertLogContains("GIT_PASSWORD=****", b); r.assertLogNotContains(this.password, b); - //Assert credential values - String fileContents = r.jenkins.getWorkspaceFor(project).child("auth.txt").readToString().trim(); - if(credentials.isUsernameSecret()) { + // Assert credential values + String fileContents = r.jenkins + .getWorkspaceFor(project) + .child("auth.txt") + .readToString() + .trim(); + if (credentials.isUsernameSecret()) { assertThat(fileContents, containsString("GIT_USERNAME=" + this.username)); } assertThat(fileContents, containsString("GIT_PASSWORD=" + this.password)); @@ -266,7 +277,7 @@ public void test_EnvironmentVariables_PipelineJob() throws Exception { } @Test - public void test_isCurrentNodeOSUnix(){ + public void test_isCurrentNodeOSUnix() { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); assertThat(gitCredBind.isCurrentNodeOSUnix(r.createLocalLauncher()), not(equalTo(isWindows()))); } @@ -275,8 +286,9 @@ public void test_isCurrentNodeOSUnix(){ public void test_getCliGitTool_using_FreeStyleProject() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject prj = r.createFreeStyleProject(); - prj.getBuildWrappersList().add(new SecretBuildWrapper(Collections.> - singletonList(new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); + prj.getBuildWrappersList() + .add(new SecretBuildWrapper(Collections.>singletonList( + new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); prj.getBuildersList().add(isWindows() ? new BatchFile(batchCheck(false)) : new Shell(shellCheck())); r.configRoundtrip((Item) prj); SecretBuildWrapper wrapper = prj.getBuildWrappersList().get(SecretBuildWrapper.class); @@ -286,10 +298,16 @@ public void test_getCliGitTool_using_FreeStyleProject() throws Exception { MultiBinding binding = bindings.get(0); FreeStyleBuild run = prj.scheduleBuild2(0).waitForStart(); if (isCliGitTool()) { - assertThat(((GitUsernamePasswordBinding) binding).getCliGitTool(run, ((GitUsernamePasswordBinding) binding).getGitToolName(), TaskListener.NULL), + assertThat( + ((GitUsernamePasswordBinding) binding) + .getCliGitTool( + run, ((GitUsernamePasswordBinding) binding).getGitToolName(), TaskListener.NULL), is(notNullValue())); } else { - assertThat(((GitUsernamePasswordBinding) binding).getCliGitTool(run, ((GitUsernamePasswordBinding) binding).getGitToolName(), TaskListener.NULL), + assertThat( + ((GitUsernamePasswordBinding) binding) + .getCliGitTool( + run, ((GitUsernamePasswordBinding) binding).getGitToolName(), TaskListener.NULL), is(nullValue())); } r.waitForCompletion(run); @@ -300,18 +318,23 @@ public void test_getCliGitTool_using_FreeStyleProject() throws Exception { public void test_getGitClientInstance() throws IOException, InterruptedException { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); if (isCliGitTool()) { - assertThat(gitCredBind.getGitClientInstance(gitToolInstance.getGitExe(), rootFilePath, - new EnvVars(), TaskListener.NULL), instanceOf(CliGitAPIImpl.class)); + assertThat( + gitCredBind.getGitClientInstance( + gitToolInstance.getGitExe(), rootFilePath, new EnvVars(), TaskListener.NULL), + instanceOf(CliGitAPIImpl.class)); } else { - assertThat(gitCredBind.getGitClientInstance(gitToolInstance.getGitExe(), rootFilePath, - new EnvVars(), TaskListener.NULL), not(instanceOf(CliGitAPIImpl.class))); + assertThat( + gitCredBind.getGitClientInstance( + gitToolInstance.getGitExe(), rootFilePath, new EnvVars(), TaskListener.NULL), + not(instanceOf(CliGitAPIImpl.class))); } } @Test public void test_GenerateGitScript_write() throws IOException, InterruptedException { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - GitUsernamePasswordBinding.GenerateGitScript tempGenScript = new GitUsernamePasswordBinding.GenerateGitScript(this.username, this.password, credentials.getId(), !isWindows()); + GitUsernamePasswordBinding.GenerateGitScript tempGenScript = new GitUsernamePasswordBinding.GenerateGitScript( + this.username, this.password, credentials.getId(), !isWindows()); assertThat(tempGenScript.type(), is(StandardUsernamePasswordCredentials.class)); FilePath tempScriptFile = tempGenScript.write(credentials, rootFilePath); if (!isWindows()) { diff --git a/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java index 3b04744c94..3475c046ff 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java @@ -1,5 +1,16 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import hudson.plugins.git.BranchSpec; import hudson.plugins.git.ChangelogToBranchOptions; import hudson.plugins.git.GitSCM; @@ -32,6 +43,7 @@ import hudson.plugins.git.extensions.impl.WipeWorkspace; import hudson.scm.SCM; import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import java.util.List; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; @@ -39,32 +51,20 @@ import org.jenkinsci.plugins.workflow.libs.SCMRetriever; import org.jvnet.hudson.test.RestartableJenkinsRule; -import java.util.List; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.core.AllOf.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - public class GlobalLibraryWithLegacyJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); + final LibraryConfiguration library = + GlobalLibraries.get().getLibraries().get(0); assertEquals("My Git Lib", library.getName()); assertEquals("1.2.3", library.getDefaultVersion()); assertTrue(library.isImplicit()); final LibraryRetriever retriever = library.getRetriever(); assertThat(retriever, instanceOf(SCMRetriever.class)); - final SCM scm = ((SCMRetriever) retriever).getScm(); + final SCM scm = ((SCMRetriever) retriever).getScm(); assertThat(scm, instanceOf(GitSCM.class)); - final GitSCM gitSCM = (GitSCM)scm; + final GitSCM gitSCM = (GitSCM) scm; assertThat(gitSCM.getUserRemoteConfigs(), hasSize(1)); final UserRemoteConfig userRemoteConfig = gitSCM.getUserRemoteConfigs().get(0); @@ -74,12 +74,11 @@ protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenk assertEquals("https://git.acmecorp/myGitLib.git", userRemoteConfig.getUrl()); assertThat(gitSCM.getBranches(), hasSize(2)); - assertThat(gitSCM.getBranches(), containsInAnyOrder( - allOf(instanceOf(BranchSpec.class), - hasProperty("name", equalTo("master"))), - allOf(instanceOf(BranchSpec.class), - hasProperty("name", equalTo("myprodbranch"))) - )); + assertThat( + gitSCM.getBranches(), + containsInAnyOrder( + allOf(instanceOf(BranchSpec.class), hasProperty("name", equalTo("master"))), + allOf(instanceOf(BranchSpec.class), hasProperty("name", equalTo("myprodbranch"))))); assertThat(gitSCM.getBrowser(), instanceOf(AssemblaWeb.class)); assertEquals("assemblaweb.url", gitSCM.getBrowser().getRepoUrl()); @@ -87,142 +86,107 @@ protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenk assertFalse(gitSCM.isDoGenerateSubmoduleConfigurations()); assertThat(gitSCM.getExtensions(), hasSize(23)); - assertThat(gitSCM.getExtensions(), containsInAnyOrder( - // Advanced checkout behaviours - allOf( - instanceOf(CheckoutOption.class), - hasProperty("timeout", equalTo(1)) - ), - // Advanced clone behaviours - allOf( - instanceOf(CloneOption.class), - hasProperty("shallow", equalTo(true)), - hasProperty("noTags", equalTo(false)), - hasProperty("reference", equalTo("/my/path/2")), - hasProperty("timeout", equalTo(2)), - hasProperty("depth", equalTo(2)), - hasProperty("honorRefspec", equalTo(true)) - ), - // Advanced sub-modules behaviours - allOf( - instanceOf(SubmoduleOption.class), - hasProperty("disableSubmodules", equalTo(true)), - hasProperty("parentCredentials", equalTo(true)), - hasProperty("recursiveSubmodules", equalTo(true)), - hasProperty("reference", equalTo("/my/path/3")), - hasProperty("timeout", equalTo(3)), - hasProperty("trackingSubmodules", equalTo(true)) - ), - // Calculate changelog against a specific branch - allOf( - instanceOf(ChangelogToBranch.class), - hasProperty("options", instanceOf(ChangelogToBranchOptions.class)), - hasProperty("options", hasProperty("compareRemote", equalTo("myrepo"))), - hasProperty("options", hasProperty("compareTarget", equalTo("mybranch"))) - ), - // Check out to a sub-directory - allOf( - instanceOf(RelativeTargetDirectory.class), - hasProperty("relativeTargetDir", equalTo("/my/path/5")) - ), - // Check out to specific local branch - allOf( - instanceOf(LocalBranch.class), - hasProperty("localBranch", equalTo("local_branch")) - ), - // Clean after checkout - allOf( - instanceOf(CleanCheckout.class) - ), - // Clean before checkout - allOf( - instanceOf(CleanBeforeCheckout.class) - ), - // Create a tag for every build - allOf( - instanceOf(PerBuildTag.class) - ), - // Don't trigger a build on commit notifications - allOf( - instanceOf(IgnoreNotifyCommit.class) - ), - // Force polling using workspace - allOf( - instanceOf(DisableRemotePoll.class) - ), - // Git LFS pull after checkout - allOf( - instanceOf(GitLFSPull.class) - ), - // Prune stale remote-tracking branches - allOf( - instanceOf(PruneStaleBranch.class) - ), - // Prune stale tags - allOf( - instanceOf(PruneStaleTag.class) - ), - // Use commit author in changelog - allOf( - instanceOf(AuthorInChangelog.class) - ), - // Wipe out repository & force clone - allOf( - instanceOf(WipeWorkspace.class) - ), - // Custom SCM name - allOf( - instanceOf(ScmName.class), - hasProperty("name", equalTo("my_scm")) - ), - // Custom user name/e-mail address - allOf( - instanceOf(UserIdentity.class), - hasProperty("name", equalTo("custom_name")), - hasProperty("email", equalTo("custom@mail.com")) - ), - // Polling ignores commits from certain users - allOf( - instanceOf(UserExclusion.class), - hasProperty("excludedUsers", equalTo("me")) - ), - // Polling ignores commits in certain paths - allOf( - instanceOf(PathRestriction.class), - hasProperty("excludedRegions", equalTo("/path/excluded")), - hasProperty("includedRegions", equalTo("/path/included")) - ), - // Polling ignores commits with certain messages - allOf( - instanceOf(MessageExclusion.class), - hasProperty("excludedMessage", equalTo("message_excluded")) - ), - // Merge before build - allOf( - instanceOf(PreBuildMerge.class), - hasProperty("options", instanceOf(UserMergeOptions.class)), - hasProperty("options", hasProperty("fastForwardMode", equalTo(MergeCommand.GitPluginFastForwardMode.FF_ONLY))), - hasProperty("options", hasProperty("mergeRemote", equalTo("repo_merge"))), - hasProperty("options", hasProperty("mergeTarget", equalTo("branch_merge"))), - hasProperty("options", hasProperty("mergeStrategy", equalTo(MergeCommand.Strategy.OCTOPUS))) - ), - // Sparse Checkout paths - allOf( - instanceOf(SparseCheckoutPaths.class), - hasProperty("sparseCheckoutPaths", instanceOf(List.class)), - hasProperty("sparseCheckoutPaths", hasSize(2)), - hasProperty("sparseCheckoutPaths", containsInAnyOrder( - allOf( - instanceOf(SparseCheckoutPath.class), - hasProperty("path", equalTo("/first/last")) - ), - allOf( - instanceOf(SparseCheckoutPath.class), - hasProperty("path", equalTo("/other/path")) - ) - )) - ) - )); + assertThat( + gitSCM.getExtensions(), + containsInAnyOrder( + // Advanced checkout behaviours + allOf(instanceOf(CheckoutOption.class), hasProperty("timeout", equalTo(1))), + // Advanced clone behaviours + allOf( + instanceOf(CloneOption.class), + hasProperty("shallow", equalTo(true)), + hasProperty("noTags", equalTo(false)), + hasProperty("reference", equalTo("/my/path/2")), + hasProperty("timeout", equalTo(2)), + hasProperty("depth", equalTo(2)), + hasProperty("honorRefspec", equalTo(true))), + // Advanced sub-modules behaviours + allOf( + instanceOf(SubmoduleOption.class), + hasProperty("disableSubmodules", equalTo(true)), + hasProperty("parentCredentials", equalTo(true)), + hasProperty("recursiveSubmodules", equalTo(true)), + hasProperty("reference", equalTo("/my/path/3")), + hasProperty("timeout", equalTo(3)), + hasProperty("trackingSubmodules", equalTo(true))), + // Calculate changelog against a specific branch + allOf( + instanceOf(ChangelogToBranch.class), + hasProperty("options", instanceOf(ChangelogToBranchOptions.class)), + hasProperty("options", hasProperty("compareRemote", equalTo("myrepo"))), + hasProperty("options", hasProperty("compareTarget", equalTo("mybranch")))), + // Check out to a sub-directory + allOf( + instanceOf(RelativeTargetDirectory.class), + hasProperty("relativeTargetDir", equalTo("/my/path/5"))), + // Check out to specific local branch + allOf(instanceOf(LocalBranch.class), hasProperty("localBranch", equalTo("local_branch"))), + // Clean after checkout + allOf(instanceOf(CleanCheckout.class)), + // Clean before checkout + allOf(instanceOf(CleanBeforeCheckout.class)), + // Create a tag for every build + allOf(instanceOf(PerBuildTag.class)), + // Don't trigger a build on commit notifications + allOf(instanceOf(IgnoreNotifyCommit.class)), + // Force polling using workspace + allOf(instanceOf(DisableRemotePoll.class)), + // Git LFS pull after checkout + allOf(instanceOf(GitLFSPull.class)), + // Prune stale remote-tracking branches + allOf(instanceOf(PruneStaleBranch.class)), + // Prune stale tags + allOf(instanceOf(PruneStaleTag.class)), + // Use commit author in changelog + allOf(instanceOf(AuthorInChangelog.class)), + // Wipe out repository & force clone + allOf(instanceOf(WipeWorkspace.class)), + // Custom SCM name + allOf(instanceOf(ScmName.class), hasProperty("name", equalTo("my_scm"))), + // Custom user name/e-mail address + allOf( + instanceOf(UserIdentity.class), + hasProperty("name", equalTo("custom_name")), + hasProperty("email", equalTo("custom@mail.com"))), + // Polling ignores commits from certain users + allOf(instanceOf(UserExclusion.class), hasProperty("excludedUsers", equalTo("me"))), + // Polling ignores commits in certain paths + allOf( + instanceOf(PathRestriction.class), + hasProperty("excludedRegions", equalTo("/path/excluded")), + hasProperty("includedRegions", equalTo("/path/included"))), + // Polling ignores commits with certain messages + allOf( + instanceOf(MessageExclusion.class), + hasProperty("excludedMessage", equalTo("message_excluded"))), + // Merge before build + allOf( + instanceOf(PreBuildMerge.class), + hasProperty("options", instanceOf(UserMergeOptions.class)), + hasProperty( + "options", + hasProperty( + "fastForwardMode", + equalTo(MergeCommand.GitPluginFastForwardMode.FF_ONLY))), + hasProperty("options", hasProperty("mergeRemote", equalTo("repo_merge"))), + hasProperty("options", hasProperty("mergeTarget", equalTo("branch_merge"))), + hasProperty( + "options", + hasProperty("mergeStrategy", equalTo(MergeCommand.Strategy.OCTOPUS)))), + // Sparse Checkout paths + allOf( + instanceOf(SparseCheckoutPaths.class), + hasProperty("sparseCheckoutPaths", instanceOf(List.class)), + hasProperty("sparseCheckoutPaths", hasSize(2)), + hasProperty( + "sparseCheckoutPaths", + containsInAnyOrder( + allOf( + instanceOf(SparseCheckoutPath.class), + hasProperty("path", equalTo("/first/last"))), + allOf( + instanceOf(SparseCheckoutPath.class), + hasProperty("path", equalTo("/other/path")))))))); } @Override diff --git a/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java index d2ba122324..fd9949695f 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java @@ -1,5 +1,15 @@ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import hudson.plugins.git.browser.BitbucketWeb; import hudson.plugins.git.extensions.impl.CheckoutOption; import hudson.plugins.git.extensions.impl.CloneOption; @@ -33,152 +43,117 @@ import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; import org.jvnet.hudson.test.RestartableJenkinsRule; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.collection.IsCollectionWithSize.hasSize; -import static org.hamcrest.core.AllOf.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; - public class GlobalLibraryWithModernJCasCCompatibilityTest extends RoundTripAbstractTest { @Override protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); + final LibraryConfiguration library = + GlobalLibraries.get().getLibraries().get(0); assertEquals("My Git Lib", library.getName()); assertEquals("1.2.3", library.getDefaultVersion()); assertTrue(library.isImplicit()); final LibraryRetriever retriever = library.getRetriever(); assertThat(retriever, instanceOf(SCMSourceRetriever.class)); - final SCMSource scm = ((SCMSourceRetriever) retriever).getScm(); + final SCMSource scm = ((SCMSourceRetriever) retriever).getScm(); assertThat(scm, instanceOf(GitSCMSource.class)); - final GitSCMSource gitSCMSource = (GitSCMSource)scm; + final GitSCMSource gitSCMSource = (GitSCMSource) scm; assertEquals("acmeuser-cred-Id", gitSCMSource.getCredentialsId()); assertEquals("https://git.acmecorp/myGitLib.git", gitSCMSource.getRemote()); assertThat(gitSCMSource.getTraits(), hasSize(20)); - assertThat(gitSCMSource.getTraits(), containsInAnyOrder( - //Discover branches - allOf( - new SimpleNameMatcher("BranchDiscoveryTrait") - // TODO after JENKINS-67309 instanceOf(BranchDiscoveryTrait.class) - ), - // Discover tags - allOf( - new SimpleNameMatcher("TagDiscoveryTrait") - // TODO after JENKINS-67309 instanceOf(TagDiscoveryTrait.class) - ), - // Check out to matching local branch - allOf( - instanceOf(LocalBranchTrait.class) - ), - // Clean after checkout - allOf( - instanceOf(CleanAfterCheckoutTrait.class) - ), - // Clean before checkout - allOf( - instanceOf(CleanBeforeCheckoutTrait.class) - ), - // Git LFS pull after checkout - allOf( - instanceOf(GitLFSPullTrait.class) - ), - // Ignore on push notifications - allOf( - instanceOf(IgnoreOnPushNotificationTrait.class) - ), - // Prune stale remote-tracking branches - allOf( - instanceOf(PruneStaleBranchTrait.class) - ), - // Use commit author in changelog - allOf( - instanceOf(AuthorInChangelogTrait.class) - ), - // Wipe out repository & force clone - allOf( - instanceOf(WipeWorkspaceTrait.class) - ), - // Discover other refs - allOf( - instanceOf(DiscoverOtherRefsTrait.class), - hasProperty("nameMapping", equalTo("mapping")), - hasProperty("ref", equalTo("other/refs")) - ), - // Filter by name (with regular expression) - allOf( - instanceOf(RegexSCMHeadFilterTrait.class), - hasProperty("regex", equalTo(".*acme*")) - ), - // Filter by name (with wildcards) - allOf( - instanceOf(WildcardSCMHeadFilterTrait.class), - hasProperty("excludes", equalTo("excluded")), - hasProperty("includes", equalTo("master")) - ), - // Configure remote name - allOf( - instanceOf(RemoteNameSCMSourceTrait.class), - hasProperty("remoteName", equalTo("other_remote")) - ), - // Advanced checkout behaviours - allOf( - instanceOf(CheckoutOptionTrait.class), - hasProperty("extension", instanceOf(CheckoutOption.class)), - hasProperty("extension", hasProperty("timeout", equalTo(1))) - ), - // Advanced clone behaviours - allOf( - instanceOf(CloneOptionTrait.class), - hasProperty("extension", instanceOf(CloneOption.class)), - hasProperty("extension", hasProperty("depth", equalTo(2))), - hasProperty("extension", hasProperty("honorRefspec", equalTo(true))), - hasProperty("extension", hasProperty("noTags", equalTo(false))), - hasProperty("extension", hasProperty("reference", equalTo("/my/path/2"))), - hasProperty("extension", hasProperty("shallow", equalTo(true))), - hasProperty("extension", hasProperty("timeout", equalTo(2))) - ), - // Advanced sub-modules behaviours - allOf( - instanceOf(SubmoduleOptionTrait.class), - hasProperty("extension", instanceOf(SubmoduleOption.class)), - hasProperty("extension", hasProperty("disableSubmodules", equalTo(true))), - hasProperty("extension", hasProperty("parentCredentials", equalTo(true))), - hasProperty("extension", hasProperty("recursiveSubmodules", equalTo(true))), - hasProperty("extension", hasProperty("reference", equalTo("/my/path/3"))), - hasProperty("extension", hasProperty("timeout", equalTo(3))), - hasProperty("extension", hasProperty("trackingSubmodules", equalTo(true))) - ), - // Configure Repository Browser - allOf( - instanceOf(GitBrowserSCMSourceTrait.class), - hasProperty("browser", instanceOf(BitbucketWeb.class)), - hasProperty("browser", hasProperty("repoUrl", equalTo("bitbucketweb.url"))) - ), - // Custom user name/e-mail address - allOf( - instanceOf(UserIdentityTrait.class), - hasProperty("extension", instanceOf(UserIdentity.class)), - hasProperty("extension", hasProperty("name", equalTo("my_user"))), - hasProperty("extension", hasProperty("email", equalTo("my@email.com"))) - ), - // Specify ref specs - allOf( - instanceOf(RefSpecsSCMSourceTrait.class), - hasProperty("templates", hasSize(1)), - hasProperty("templates", containsInAnyOrder( - allOf( - instanceOf(RefSpecsSCMSourceTrait.RefSpecTemplate.class), - hasProperty("value", equalTo("+refs/heads/*:refs/remotes/@{remote}/*")) - ) - )) - ) - )); + assertThat( + gitSCMSource.getTraits(), + containsInAnyOrder( + // Discover branches + allOf( + new SimpleNameMatcher("BranchDiscoveryTrait") + // TODO after JENKINS-67309 instanceOf(BranchDiscoveryTrait.class) + ), + // Discover tags + allOf( + new SimpleNameMatcher("TagDiscoveryTrait") + // TODO after JENKINS-67309 instanceOf(TagDiscoveryTrait.class) + ), + // Check out to matching local branch + allOf(instanceOf(LocalBranchTrait.class)), + // Clean after checkout + allOf(instanceOf(CleanAfterCheckoutTrait.class)), + // Clean before checkout + allOf(instanceOf(CleanBeforeCheckoutTrait.class)), + // Git LFS pull after checkout + allOf(instanceOf(GitLFSPullTrait.class)), + // Ignore on push notifications + allOf(instanceOf(IgnoreOnPushNotificationTrait.class)), + // Prune stale remote-tracking branches + allOf(instanceOf(PruneStaleBranchTrait.class)), + // Use commit author in changelog + allOf(instanceOf(AuthorInChangelogTrait.class)), + // Wipe out repository & force clone + allOf(instanceOf(WipeWorkspaceTrait.class)), + // Discover other refs + allOf( + instanceOf(DiscoverOtherRefsTrait.class), + hasProperty("nameMapping", equalTo("mapping")), + hasProperty("ref", equalTo("other/refs"))), + // Filter by name (with regular expression) + allOf(instanceOf(RegexSCMHeadFilterTrait.class), hasProperty("regex", equalTo(".*acme*"))), + // Filter by name (with wildcards) + allOf( + instanceOf(WildcardSCMHeadFilterTrait.class), + hasProperty("excludes", equalTo("excluded")), + hasProperty("includes", equalTo("master"))), + // Configure remote name + allOf( + instanceOf(RemoteNameSCMSourceTrait.class), + hasProperty("remoteName", equalTo("other_remote"))), + // Advanced checkout behaviours + allOf( + instanceOf(CheckoutOptionTrait.class), + hasProperty("extension", instanceOf(CheckoutOption.class)), + hasProperty("extension", hasProperty("timeout", equalTo(1)))), + // Advanced clone behaviours + allOf( + instanceOf(CloneOptionTrait.class), + hasProperty("extension", instanceOf(CloneOption.class)), + hasProperty("extension", hasProperty("depth", equalTo(2))), + hasProperty("extension", hasProperty("honorRefspec", equalTo(true))), + hasProperty("extension", hasProperty("noTags", equalTo(false))), + hasProperty("extension", hasProperty("reference", equalTo("/my/path/2"))), + hasProperty("extension", hasProperty("shallow", equalTo(true))), + hasProperty("extension", hasProperty("timeout", equalTo(2)))), + // Advanced sub-modules behaviours + allOf( + instanceOf(SubmoduleOptionTrait.class), + hasProperty("extension", instanceOf(SubmoduleOption.class)), + hasProperty("extension", hasProperty("disableSubmodules", equalTo(true))), + hasProperty("extension", hasProperty("parentCredentials", equalTo(true))), + hasProperty("extension", hasProperty("recursiveSubmodules", equalTo(true))), + hasProperty("extension", hasProperty("reference", equalTo("/my/path/3"))), + hasProperty("extension", hasProperty("timeout", equalTo(3))), + hasProperty("extension", hasProperty("trackingSubmodules", equalTo(true)))), + // Configure Repository Browser + allOf( + instanceOf(GitBrowserSCMSourceTrait.class), + hasProperty("browser", instanceOf(BitbucketWeb.class)), + hasProperty("browser", hasProperty("repoUrl", equalTo("bitbucketweb.url")))), + // Custom user name/e-mail address + allOf( + instanceOf(UserIdentityTrait.class), + hasProperty("extension", instanceOf(UserIdentity.class)), + hasProperty("extension", hasProperty("name", equalTo("my_user"))), + hasProperty("extension", hasProperty("email", equalTo("my@email.com")))), + // Specify ref specs + allOf( + instanceOf(RefSpecsSCMSourceTrait.class), + hasProperty("templates", hasSize(1)), + hasProperty( + "templates", + containsInAnyOrder(allOf( + instanceOf(RefSpecsSCMSourceTrait.RefSpecTemplate.class), + hasProperty( + "value", + equalTo("+refs/heads/*:refs/remotes/@{remote}/*")))))))); } @Override diff --git a/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java b/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java index a060442df9..19bb989a33 100644 --- a/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java +++ b/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java @@ -1,5 +1,7 @@ package jenkins.plugins.git; +import static org.junit.Assert.*; + import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; @@ -12,8 +14,6 @@ import org.eclipse.jgit.lib.Constants; import org.junit.Test; -import static org.junit.Assert.*; - public class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { private FreeStyleProject project; @@ -23,6 +23,7 @@ public class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { private String baseHash; private String MASTER_FILE = "commitFileBase"; + @Override public void before() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); // make an initial commit to master and get hash @@ -32,8 +33,8 @@ public void before() throws Exception { project = setupBasicProject(repo); // create integration branch repo.git.branch("integration"); - } + @Test public void testBasicMergeWithSCMExtension() throws Exception { FreeStyleBuild baseBuild = build(project, Result.SUCCESS); @@ -43,7 +44,7 @@ public void testBasicMergeWithSCMExtension() throws Exception { public void testFailedMergeWithSCMExtension() throws Exception { FreeStyleBuild firstBuild = build(project, Result.SUCCESS); assertEquals(GitSCM.class, project.getScm().getClass()); - GitSCM gitSCM = (GitSCM)project.getScm(); + GitSCM gitSCM = (GitSCM) project.getScm(); BuildData buildData = gitSCM.getBuildData(firstBuild); assertNotNull("Build data not found", buildData); assertEquals(firstBuild.getNumber(), buildData.lastBuild.getBuildNumber()); @@ -61,26 +62,35 @@ public void testFailedMergeWithSCMExtension() throws Exception { repo.git.checkout().ref("master").execute(); // as baseName and baseHash don't change in master branch, this commit should merge ! - assertFalse("SCM polling should not detect any more changes after build", project.poll(listener).hasChanges()); - String conflictSha1= repo.commit(MASTER_FILE, "new John Doe content will conflict", repo.johnDoe, repo.johnDoe, "Commit success!"); + assertFalse( + "SCM polling should not detect any more changes after build", + project.poll(listener).hasChanges()); + String conflictSha1 = repo.commit( + MASTER_FILE, "new John Doe content will conflict", repo.johnDoe, repo.johnDoe, "Commit success!"); assertTrue("SCM polling should detect changes", project.poll(listener).hasChanges()); - FreeStyleBuild secondBuild = build(project, Result.SUCCESS); - assertEquals(secondBuild.getNumber(), gitSCM.getBuildData(secondBuild).lastBuild.getBuildNumber()); + assertEquals( + secondBuild.getNumber(), + gitSCM.getBuildData(secondBuild).lastBuild.getBuildNumber()); // buildData should mark this as built - assertEquals(conflictSha1, gitSCM.getBuildData(secondBuild).lastBuild.getMarked().getSha1String()); - assertEquals(conflictSha1, gitSCM.getBuildData(secondBuild).lastBuild.getRevision().getSha1String()); + assertEquals( + conflictSha1, + gitSCM.getBuildData(secondBuild).lastBuild.getMarked().getSha1String()); + assertEquals( + conflictSha1, + gitSCM.getBuildData(secondBuild).lastBuild.getRevision().getSha1String()); // Check to see that build data is not corrupted (JENKINS-44037) - assertEquals(firstBuild.getNumber(), gitSCM.getBuildData(firstBuild).lastBuild.getBuildNumber()); + assertEquals( + firstBuild.getNumber(), + gitSCM.getBuildData(firstBuild).lastBuild.getBuildNumber()); assertEquals(firstMarked, gitSCM.getBuildData(firstBuild).lastBuild.getMarked()); assertEquals(firstRevision, gitSCM.getBuildData(firstBuild).lastBuild.getRevision()); } @Override protected GitSCMExtension getExtension() { - return new MergeWithGitSCMExtension(baseName,baseHash); + return new MergeWithGitSCMExtension(baseName, baseHash); } - } diff --git a/src/test/java/jenkins/plugins/git/ModernScmTest.java b/src/test/java/jenkins/plugins/git/ModernScmTest.java index e00f17ad42..840f0797d3 100644 --- a/src/test/java/jenkins/plugins/git/ModernScmTest.java +++ b/src/test/java/jenkins/plugins/git/ModernScmTest.java @@ -24,6 +24,10 @@ */ package jenkins.plugins.git; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.instanceOf; + import hudson.ExtensionList; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; import org.junit.Rule; @@ -31,10 +35,6 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; - public class ModernScmTest { @Rule @@ -43,7 +43,8 @@ public class ModernScmTest { @Test @Issue("JENKINS-58964") public void gitIsModernScm() { - SCMSourceRetriever.DescriptorImpl descriptor = ExtensionList.lookupSingleton(SCMSourceRetriever.DescriptorImpl.class); + SCMSourceRetriever.DescriptorImpl descriptor = + ExtensionList.lookupSingleton(SCMSourceRetriever.DescriptorImpl.class); assertThat(descriptor.getSCMDescriptors(), hasItem(instanceOf(GitSCMSource.DescriptorImpl.class))); } } diff --git a/src/test/java/jenkins/plugins/git/RandomOrder.java b/src/test/java/jenkins/plugins/git/RandomOrder.java index a293f783bf..860776151a 100644 --- a/src/test/java/jenkins/plugins/git/RandomOrder.java +++ b/src/test/java/jenkins/plugins/git/RandomOrder.java @@ -1,11 +1,11 @@ package jenkins.plugins.git; -import org.junit.runner.manipulation.Ordering; - import java.util.Random; +import org.junit.runner.manipulation.Ordering; public class RandomOrder implements Ordering.Factory { private static final long SEED = new Random().nextLong(); + @Override public Ordering create(Ordering.Context context) { return Ordering.shuffledBy(new Random(SEED)); diff --git a/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java b/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java index 611e4ba8ce..da9b6a5e4d 100644 --- a/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java @@ -23,10 +23,10 @@ */ package jenkins.plugins.git.traits; -import org.junit.Test; - import static org.junit.Assert.*; +import org.junit.Test; + public class DiscoverOtherRefsTraitTest { @Test @@ -46,5 +46,4 @@ public void getNameMapping() throws Exception { t = new DiscoverOtherRefsTrait("refs/bobby/all"); assertEquals("other-ref", t.getNameMapping()); } - } diff --git a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java index 9fc9122d74..69fb2287d4 100644 --- a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java @@ -1,5 +1,8 @@ package jenkins.plugins.git.traits; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import hudson.Util; import hudson.model.Descriptor; import hudson.plugins.git.extensions.GitSCMExtension; @@ -10,9 +13,6 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - public class GitSCMExtensionTraitTest { @ClassRule public static JenkinsRule j = new JenkinsRule(); @@ -30,7 +30,8 @@ public List descriptors() { @Test public void extensionClassesOverrideEquals() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { - assertThat(d.getExtensionClass().getName() + " overrides equals(Object)", + assertThat( + d.getExtensionClass().getName() + " overrides equals(Object)", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "equals", Object.class), is(true)); } @@ -39,7 +40,8 @@ public void extensionClassesOverrideEquals() { @Test public void extensionClassesOverrideHashCode() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { - assertThat(d.getExtensionClass().getName() + " overrides hashCode()", + assertThat( + d.getExtensionClass().getName() + " overrides hashCode()", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "hashCode"), is(true)); } @@ -48,7 +50,8 @@ public void extensionClassesOverrideHashCode() { @Test public void extensionClassesOverrideToString() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { - assertThat(d.getExtensionClass().getName() + " overrides toString()", + assertThat( + d.getExtensionClass().getName() + " overrides toString()", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "toString"), is(true)); } diff --git a/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java b/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java index 89328e4226..915c41b655 100644 --- a/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java @@ -1,11 +1,13 @@ package jenkins.plugins.git.traits; -import jenkins.plugins.git.GitSampleRepoRule; +import java.util.Collections; +import java.util.Random; import jenkins.plugins.git.GitSCMSource; +import jenkins.plugins.git.GitSampleRepoRule; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; -import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; +import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; import org.junit.Before; @@ -13,12 +15,10 @@ import org.junit.Test; import org.jvnet.hudson.test.RestartableJenkinsRule; -import java.util.Collections; -import java.util.Random; - public class MultibranchProjectTraitsTest { @Rule public RestartableJenkinsRule story = new RestartableJenkinsRule(); + @Rule public GitSampleRepoRule sharedLibrarySampleRepo = new GitSampleRepoRule(); @@ -35,24 +35,29 @@ public void setUpTestRepositories() throws Exception { } /* - Tests a checkout step in a pipeline using Symbol names instead of $class - */ + Tests a checkout step in a pipeline using Symbol names instead of $class + */ @Test public void basicSharedLibrarySymbolsTest() throws Exception { - story.then( r -> { - GlobalLibraries.get().setLibraries(Collections.singletonList( // TODO: Something more interesting with traits, maybe gitBranchDiscovery - new LibraryConfiguration("thelibrary", new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString())))));; + story.then(r -> { + GlobalLibraries.get() + .setLibraries(Collections.singletonList( // TODO: Something more interesting with traits, maybe + // gitBranchDiscovery + new LibraryConfiguration( + "thelibrary", + new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString()))))); + ; WorkflowJob job = story.j.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); job.setDefinition(new CpsFlowDefinition( - "library 'thelibrary@libraryBranch'\n" + "library 'thelibrary@libraryBranch'\n" + "node() {\n" + " book()\n" + " checkout scmGit(\n" + randomBrowserSymbolName() + " userRemoteConfigs: [[url: $/" + sharedLibrarySampleRepo + "/$]]\n" + " )" - + "}" - , true)); + + "}", + true)); WorkflowRun run = story.j.waitForCompletion(job.scheduleBuild2(0).waitForStart()); story.j.waitForCompletion(run); story.j.waitForMessage("Finished: SUCCESS", run); @@ -65,8 +70,11 @@ public void basicSharedLibrarySymbolsTest() throws Exception { */ @Test public void basicSharedLibraryClassTest() throws Exception { - story.then( r -> { - GlobalLibraries.get().setLibraries(Collections.singletonList(new LibraryConfiguration("thelibrary", new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString()))))); + story.then(r -> { + GlobalLibraries.get() + .setLibraries(Collections.singletonList(new LibraryConfiguration( + "thelibrary", + new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString()))))); WorkflowJob job = story.j.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); job.setDefinition(new CpsFlowDefinition( "library 'thelibrary@libraryBranch'\n" @@ -77,7 +85,8 @@ public void basicSharedLibraryClassTest() throws Exception { + randomBrowserClass() + " userRemoteConfigs: [[url: $/" + sharedLibrarySampleRepo + "/$]]]\n" + " )" - + "}", true)); + + "}", + true)); WorkflowRun run = story.j.waitForCompletion(job.scheduleBuild2(0).waitForStart()); story.j.waitForCompletion(run); story.j.waitForMessage("Finished: SUCCESS", run); @@ -86,57 +95,58 @@ public void basicSharedLibraryClassTest() throws Exception { } /* - Returns a randomly selected browser for use in a pipeline checkout, using Symbol names - */ + Returns a randomly selected browser for use in a pipeline checkout, using Symbol names + */ private String randomBrowserSymbolName() { String[] browsersBySymbolName = { - " browser: assembla('https://app.assembla.com/spaces/git-plugin/git/source'),\n", - " browser: bitbucket('https://markewaite@bitbucket.org/markewaite/git-plugin'),\n", - " browser: cgit('https://git.zx2c4.com/cgit'),\n", - " browser: fisheye('https://fisheye.apache.org/browse/ant-git'),\n", - " browser: gitblit(repoUrl: 'https://github.com/MarkEWaite/git-client-plugin', projectName: 'git-plugin-project-name-value'),\n", - " browser: gitLab(repoUrl: 'https://gitlab.com/MarkEWaite/git-client-plugin', version: '12.10.1'),\n", - " browser: gitList('http://gitlist.org/'),\n", // Not a real gitlist site, just the org home page - " browser: gitWeb('https://git.ti.com/gitweb'),\n", - " browser: github('https://github.com/jenkinsci/git-plugin'),\n", - " browser: gitiles('https://gerrit.googlesource.com/gitiles/'),\n", - // No symbol for gitorious - dead site - // " browser: gitoriousWeb('https://gerrit.googlesource.com/gitiles/'),\n", - " browser: gogs('https://try.gogs.io/MarkEWaite/git-plugin'),\n", // Should this be gogsGit? - " browser: kiln('https://kiln.example.com/MarkEWaite/git-plugin'),\n", - " browser: teamFoundation('https://markwaite.visualstudio.com/DefaultCollection/git-plugin/_git/git-plugin'),\n", - " browser: phabricator(repo: 'source/tool-spacemedia', repoUrl: 'https://phabricator.wikimedia.org/source/tool-spacemedia/'),\n", - " browser: redmine('https://www.redmine.org/projects/redmine/repository'),\n", - " browser: rhodeCode('https://code.rhodecode.com/rhodecode-enterprise-ce'),\n", - " browser: viewgit(repoUrl: 'https://repo.or.cz/viewgit.git', projectName: 'viewgit-project-name-value'),\n", // Not likely a viewgit site, but reasonable approximation + " browser: assembla('https://app.assembla.com/spaces/git-plugin/git/source'),\n", + " browser: bitbucket('https://markewaite@bitbucket.org/markewaite/git-plugin'),\n", + " browser: cgit('https://git.zx2c4.com/cgit'),\n", + " browser: fisheye('https://fisheye.apache.org/browse/ant-git'),\n", + " browser: gitblit(repoUrl: 'https://github.com/MarkEWaite/git-client-plugin', projectName: 'git-plugin-project-name-value'),\n", + " browser: gitLab(repoUrl: 'https://gitlab.com/MarkEWaite/git-client-plugin', version: '12.10.1'),\n", + " browser: gitList('http://gitlist.org/'),\n", // Not a real gitlist site, just the org home page + " browser: gitWeb('https://git.ti.com/gitweb'),\n", + " browser: github('https://github.com/jenkinsci/git-plugin'),\n", + " browser: gitiles('https://gerrit.googlesource.com/gitiles/'),\n", + // No symbol for gitorious - dead site + // " browser: gitoriousWeb('https://gerrit.googlesource.com/gitiles/'),\n", + " browser: gogs('https://try.gogs.io/MarkEWaite/git-plugin'),\n", // Should this be gogsGit? + " browser: kiln('https://kiln.example.com/MarkEWaite/git-plugin'),\n", + " browser: teamFoundation('https://markwaite.visualstudio.com/DefaultCollection/git-plugin/_git/git-plugin'),\n", + " browser: phabricator(repo: 'source/tool-spacemedia', repoUrl: 'https://phabricator.wikimedia.org/source/tool-spacemedia/'),\n", + " browser: redmine('https://www.redmine.org/projects/redmine/repository'),\n", + " browser: rhodeCode('https://code.rhodecode.com/rhodecode-enterprise-ce'),\n", + " browser: viewgit(repoUrl: 'https://repo.or.cz/viewgit.git', projectName: 'viewgit-project-name-value'),\n", // Not likely a viewgit site, but reasonable approximation }; String browser = browsersBySymbolName[random.nextInt(browsersBySymbolName.length)]; return browser; } /* - Returns a randomly selected browser for use in a pipeline checkout, using the $class syntax - */ + Returns a randomly selected browser for use in a pipeline checkout, using the $class syntax + */ private String randomBrowserClass() { String[] browsersByClass = { - " browser: [$class: 'AssemblaWeb', repoUrl: 'https://app.assembla.com/spaces/git-plugin/git/source'],\n", - " browser: [$class: 'BitbucketWeb', repoUrl: 'https://markewaite@bitbucket.org/markewaite/git-plugin'],\n", - " browser: [$class: 'CGit', repoUrl: 'https://git.zx2c4.com/cgit'],\n", - " browser: [$class: 'FisheyeGitRepositoryBrowser', repoUrl: 'https://fisheye.apache.org/browse/ant-git'],\n", - " browser: [$class: 'GitBlitRepositoryBrowser', repoUrl: 'https://github.com/MarkEWaite/git-plugin', projectName: 'git-plugin-project-name-value'],\n", - " browser: [$class: 'GitLab', repoUrl: 'https://gitlab.com/MarkEWaite/git-client-plugin', version: '12.10.1'],\n", - " browser: [$class: 'GitList', repoUrl: 'http://gitlist.org/'],\n", // Not a real gitlist site, just the org home page - " browser: [$class: 'GitWeb', repoUrl: 'https://git.ti.com/gitweb'],\n", - " browser: [$class: 'GithubWeb', repoUrl: 'https://github.com/jenkinsci/git-plugin'],\n", - " browser: [$class: 'Gitiles', repoUrl: 'https://gerrit.googlesource.com/gitiles/'],\n", - " browser: [$class: 'GogsGit', repoUrl: 'https://try.gogs.io/MarkEWaite/git-plugin'],\n", - " browser: [$class: 'KilnGit', repoUrl: 'https://kiln.example.com/MarkEWaite/git-plugin'],\n", - " browser: [$class: 'Phabricator', repo: 'source/tool-spacemedia', repoUrl: 'https://phabricator.wikimedia.org/source/tool-spacemedia/'],\n", - " browser: [$class: 'RedmineWeb', repoUrl: 'https://www.redmine.org/projects/redmine/repository'],\n", - " browser: [$class: 'Stash', repoUrl: 'https://markewaite@bitbucket.org/markewaite/git-plugin'],\n", - " browser: [$class: 'TFS2013GitRepositoryBrowser', repoUrl: 'https://markwaite.visualstudio.com/DefaultCollection/git-plugin/_git/git-plugin'],\n", - " browser: [$class: 'RhodeCode', repoUrl: 'https://code.rhodecode.com/rhodecode-enterprise-ce'],\n", - " browser: [$class: 'ViewGitWeb', repoUrl: 'https://git.ti.com/gitweb', projectName: 'viewgitweb-project-name-value'],\n", // Not likely a viewgit site, but reasonable approximation + " browser: [$class: 'AssemblaWeb', repoUrl: 'https://app.assembla.com/spaces/git-plugin/git/source'],\n", + " browser: [$class: 'BitbucketWeb', repoUrl: 'https://markewaite@bitbucket.org/markewaite/git-plugin'],\n", + " browser: [$class: 'CGit', repoUrl: 'https://git.zx2c4.com/cgit'],\n", + " browser: [$class: 'FisheyeGitRepositoryBrowser', repoUrl: 'https://fisheye.apache.org/browse/ant-git'],\n", + " browser: [$class: 'GitBlitRepositoryBrowser', repoUrl: 'https://github.com/MarkEWaite/git-plugin', projectName: 'git-plugin-project-name-value'],\n", + " browser: [$class: 'GitLab', repoUrl: 'https://gitlab.com/MarkEWaite/git-client-plugin', version: '12.10.1'],\n", + " browser: [$class: 'GitList', repoUrl: 'http://gitlist.org/'],\n", // Not a real gitlist site, just the + // org home page + " browser: [$class: 'GitWeb', repoUrl: 'https://git.ti.com/gitweb'],\n", + " browser: [$class: 'GithubWeb', repoUrl: 'https://github.com/jenkinsci/git-plugin'],\n", + " browser: [$class: 'Gitiles', repoUrl: 'https://gerrit.googlesource.com/gitiles/'],\n", + " browser: [$class: 'GogsGit', repoUrl: 'https://try.gogs.io/MarkEWaite/git-plugin'],\n", + " browser: [$class: 'KilnGit', repoUrl: 'https://kiln.example.com/MarkEWaite/git-plugin'],\n", + " browser: [$class: 'Phabricator', repo: 'source/tool-spacemedia', repoUrl: 'https://phabricator.wikimedia.org/source/tool-spacemedia/'],\n", + " browser: [$class: 'RedmineWeb', repoUrl: 'https://www.redmine.org/projects/redmine/repository'],\n", + " browser: [$class: 'Stash', repoUrl: 'https://markewaite@bitbucket.org/markewaite/git-plugin'],\n", + " browser: [$class: 'TFS2013GitRepositoryBrowser', repoUrl: 'https://markwaite.visualstudio.com/DefaultCollection/git-plugin/_git/git-plugin'],\n", + " browser: [$class: 'RhodeCode', repoUrl: 'https://code.rhodecode.com/rhodecode-enterprise-ce'],\n", + " browser: [$class: 'ViewGitWeb', repoUrl: 'https://git.ti.com/gitweb', projectName: 'viewgitweb-project-name-value'],\n", // Not likely a viewgit site, but reasonable approximation }; String browser = browsersByClass[random.nextInt(browsersByClass.length)]; return browser; diff --git a/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java b/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java index 1b6f0abc2e..23a66db835 100644 --- a/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java @@ -1,5 +1,8 @@ package jenkins.plugins.git.traits; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; + import hudson.model.TaskListener; import jenkins.plugins.git.GitSCMSourceContext; import jenkins.scm.api.SCMHeadObserver; @@ -7,9 +10,6 @@ import jenkins.scm.api.SCMSourceCriteria; import jenkins.scm.api.trait.SCMSourceContext; import jenkins.scm.api.trait.SCMSourceRequest; - -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -21,8 +21,7 @@ */ public class PruneStaleBranchTraitTest { - public PruneStaleBranchTraitTest() { - } + public PruneStaleBranchTraitTest() {} @Test public void testDecorateContextWithGitSCMSourceContent() { diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java b/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java index 2283c836a2..c4f2290284 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java @@ -36,5 +36,4 @@ public class TestCliGitAPIImpl extends CliGitAPIImpl { public TestCliGitAPIImpl(String gitExe, File workspace, TaskListener listener, EnvVars environment) { super(gitExe, workspace, listener, environment); } - } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java b/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java index 3dddfcc599..edf5b59eff 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java @@ -1,11 +1,10 @@ package org.jenkinsci.plugins.gitclient; import hudson.model.TaskListener; +import java.io.File; import jenkins.plugins.git.AbstractGitSCMSourceTest; import org.jenkinsci.plugins.gitclient.jgit.PreemptiveAuthHttpClientConnectionFactory; -import java.io.File; - /** * This is just here to make the constructors public * @see AbstractGitSCMSourceTest#when_commits_added_during_discovery_we_do_not_crash() @@ -15,7 +14,8 @@ public TestJGitAPIImpl(File workspace, TaskListener listener) { super(workspace, listener); } - public TestJGitAPIImpl(File workspace, TaskListener listener, PreemptiveAuthHttpClientConnectionFactory httpConnectionFactory) { + public TestJGitAPIImpl( + File workspace, TaskListener listener, PreemptiveAuthHttpClientConnectionFactory httpConnectionFactory) { super(workspace, listener, httpConnectionFactory); } } diff --git a/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java b/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java index 33bf86492e..d89ea31be7 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java @@ -1,11 +1,14 @@ package org.jenkinsci.plugins.gittagmessage; +import static org.junit.Assert.assertNotNull; + import hudson.model.Job; import hudson.model.Queue; import hudson.model.Run; import hudson.plugins.git.GitSCM; import hudson.plugins.git.util.BuildData; import hudson.plugins.git.util.GitUtilsTest; +import java.io.IOException; import jenkins.model.ParameterizedJobMixIn; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.util.SystemReader; @@ -18,15 +21,14 @@ import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.JenkinsRule; -import java.io.IOException; - -import static org.junit.Assert.assertNotNull; - -public abstract class AbstractGitTagMessageExtensionTest & ParameterizedJobMixIn.ParameterizedJob, R extends Run & Queue.Executable> { +public abstract class AbstractGitTagMessageExtensionTest< + J extends Job & ParameterizedJobMixIn.ParameterizedJob, R extends Run & Queue.Executable> { - @Rule public final JenkinsRule jenkins = new JenkinsRule(); + @Rule + public final JenkinsRule jenkins = new JenkinsRule(); - @Rule public final TemporaryFolder repoDir = new TemporaryFolder(); + @Rule + public final TemporaryFolder repoDir = new TemporaryFolder(); private GitClient repo; @@ -36,7 +38,8 @@ public abstract class AbstractGitTagMessageExtensionTest & P * @param useMostRecentTag true to use the most recent tag rather than the exact one. * @return A job configured with the test Git repo, given settings, and the Git Tag Message extension. */ - protected abstract J configureGitTagMessageJob(String refSpec, String branchSpec, boolean useMostRecentTag) throws Exception; + protected abstract J configureGitTagMessageJob(String refSpec, String branchSpec, boolean useMostRecentTag) + throws Exception; /** @return A job configured with the test Git repo, default settings, and the Git Tag Message extension. */ private J configureGitTagMessageJob() throws Exception { @@ -50,7 +53,9 @@ private J configureGitTagMessageJob() throws Exception { public void setUp() throws IOException, InterruptedException, ConfigInvalidException { SystemReader.getInstance().getUserConfig().clear(); // Set up a temporary git repository for each test case - repo = Git.with(jenkins.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()).in(repoDir.getRoot()).getClient(); + repo = Git.with(jenkins.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()) + .in(repoDir.getRoot()) + .getClient(); repo.init(); } @@ -130,8 +135,7 @@ public void jobWithMatchingTagShouldExportThatTagMessage() throws Exception { repo.tag("gamma/1", "Gamma #1"); // When a build is executed which is configured to only build beta/* tags - J job = configureGitTagMessageJob("+refs/tags/beta/*:refs/remotes/origin/tags/beta/*", - "*/tags/beta/*", false); + J job = configureGitTagMessageJob("+refs/tags/beta/*:refs/remotes/origin/tags/beta/*", "*/tags/beta/*", false); R run = buildJobAndAssertSuccess(job); // Then the selected tag info should be exported, even although it's not the latest tag @@ -154,7 +158,8 @@ public void commitWithTagOnPreviousCommitWithConfigurationOptInShouldExportThatT } @Test - public void commitWithMultipleTagsOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() throws Exception { + public void commitWithMultipleTagsOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() + throws Exception { // Given a git repo which has been tagged on a previous commit with multiple tags repo.commit("commit 1"); repo.tag("release-candidate-1.0", "This is the first release candidate."); @@ -180,5 +185,4 @@ private R buildJobAndAssertSuccess(J job) throws Exception { assertNotNull(build.getAction(BuildData.class)); return build; } - } diff --git a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java index a216d6ea9b..e54a4156e3 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java @@ -1,5 +1,8 @@ package org.jenkinsci.plugins.gittagmessage; +import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_MESSAGE; +import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_TAG; + import hudson.Functions; import hudson.Util; import hudson.model.FreeStyleBuild; @@ -10,12 +13,8 @@ import hudson.tasks.BatchFile; import hudson.tasks.Builder; import hudson.tasks.Shell; - import java.util.Collections; -import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_MESSAGE; -import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_TAG; - public class GitTagMessageExtensionTest extends AbstractGitTagMessageExtensionTest { /** @@ -24,14 +23,17 @@ public class GitTagMessageExtensionTest extends AbstractGitTagMessageExtensionTe * @param useMostRecentTag true to use the most recent tag rather than the exact one. * @return A job configured with the test Git repo, given settings, and the Git Tag Message extension. */ - protected FreeStyleProject configureGitTagMessageJob(String refSpec, String branchSpec, boolean useMostRecentTag) throws Exception { + @Override + protected FreeStyleProject configureGitTagMessageJob(String refSpec, String branchSpec, boolean useMostRecentTag) + throws Exception { GitTagMessageExtension extension = new GitTagMessageExtension(); extension.setUseMostRecentTag(useMostRecentTag); UserRemoteConfig remote = new UserRemoteConfig(repoDir.getRoot().getAbsolutePath(), "origin", refSpec, null); GitSCM scm = new GitSCM( Collections.singletonList(remote), Collections.singletonList(new BranchSpec(branchSpec)), - null, null, + null, + null, Collections.singletonList(extension)); FreeStyleProject job = jenkins.createFreeStyleProject(); @@ -42,6 +44,7 @@ protected FreeStyleProject configureGitTagMessageJob(String refSpec, String bran } /** Asserts that the given build exported tag information, or not, if {@code null}. */ + @Override protected void assertBuildEnvironment(FreeStyleBuild build, String expectedName, String expectedMessage) throws Exception { // In the freestyle shell step, unknown environment variables are returned as empty strings @@ -55,5 +58,4 @@ private static Builder createEnvEchoBuilder(String key, String envVarName) { } return new Shell(String.format("echo \"%s='${%s}'\"", key, envVarName)); } - }