From 3e62161d3165aad0617173bf53f345d0b67433da Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Tue, 19 Mar 2024 23:43:04 -0400 Subject: [PATCH 01/30] Add files via upload --- .../extensions/impl/FirstBuildChangelog.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java new file mode 100644 index 0000000000..13c3a5c87d --- /dev/null +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -0,0 +1,78 @@ +package hudson.plugins.git.extensions.impl; + +import hudson.Extension; +import hudson.plugins.git.extensions.GitSCMExtension; +import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; +import java.util.Objects; + +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; +import org.kohsuke.stapler.DataBoundSetter; + +/** + * First Build generates a changelog. + * + * @author Derek Inskeep + */ +public class FirstBuildChangelog extends GitSCMExtension { + private boolean makeChangelog; + + @DataBoundConstructor + public FirstBuildChangelog() { + } + + public boolean isMakeChangelog() { + return makeChangelog; + } + + @DataBoundSetter + public void setMakeChangelog(boolean makeChangelog) { + this.makeChangelog = makeChangelog; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FirstBuildChangelog that = (FirstBuildChangelog) o; + return makeChangelog == that.makeChangelog; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return Objects.hash(makeChangelog); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "FirstBuildChangelog{" + + "makeChangelog=" + makeChangelog + + '}'; + } + + @Extension + @Symbol("FirstBuildChangelog") + public static class DescriptorImpl extends GitSCMExtensionDescriptor { + + /** + * {@inheritDoc} + */ + @Override + public String getDisplayName() { + return "First Build Changelog"; + } + } +} From 838cc41f842b2e6968fbb6c1ac4a7b924dbdc277 Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Tue, 19 Mar 2024 23:44:46 -0400 Subject: [PATCH 02/30] code for gui --- .../git/extensions/impl/FirstBuildChangelog/config.groovy | 7 +++++++ .../impl/FirstBuildChangelog/help-makeChangelog.html | 3 +++ .../git/extensions/impl/FirstBuildChangelog/help.html | 3 +++ 3 files changed, 13 insertions(+) create mode 100644 src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy create mode 100644 src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html create mode 100644 src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy new file mode 100644 index 0000000000..c18ee67750 --- /dev/null +++ b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy @@ -0,0 +1,7 @@ +package hudson.plugins.git.extensions.impl.FirstBuildChangelog + +def f = namespace(lib.FormTagLib) + +f.entry(field: "makeChangelog") { + f.checkbox(title: _("Make Changelog")) +} diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html new file mode 100644 index 0000000000..cc172dcebc --- /dev/null +++ b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html @@ -0,0 +1,3 @@ +
+ First builds create changelog of latest commit, if any. +
diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html new file mode 100644 index 0000000000..0f4355d596 --- /dev/null +++ b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html @@ -0,0 +1,3 @@ +
+ First builds will populate the changelog with the latest commit, if any, to allow for pipelines to consistently check and test for file changes. +
From d76a507bb858863893e5de2e630c1d956ee811e0 Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Tue, 19 Mar 2024 23:45:50 -0400 Subject: [PATCH 03/30] trait file --- .../git/traits/FirstBuildChangelogTrait.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java new file mode 100644 index 0000000000..03834f0175 --- /dev/null +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -0,0 +1,75 @@ +/* + * The MIT License + * + * Copyright (c) 2017 CloudBees, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package jenkins.plugins.git.traits; + +import hudson.Extension; +import hudson.plugins.git.extensions.impl.FirstBuildChangelog; +import jenkins.scm.api.trait.SCMSourceTrait; +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; + +import edu.umd.cs.findbugs.annotations.CheckForNull; + +/** + * Exposes {@link FirstBuildChangelog} as a {@link SCMSourceTrait}. + * + * @since 3.4.0 + */ +public class FirstBuildChangelogTrait extends GitSCMExtensionTrait { + + /** + * @deprecated Use constructor that accepts extension instead. + */ + @Deprecated + public FirstBuildChangelogTrait() { + this(null); + } + + /** + * Stapler constructor. + * + * @param extension the option to clean subdirectories which contain git repositories. + */ + @DataBoundConstructor + public FirstBuildChangelogTrait(@CheckForNull FirstBuildChangelog extension) { + super(extension == null ? new FirstBuildChangelog() : extension); + } + + /** + * Our {@link hudson.model.Descriptor} + */ + @Extension + @Symbol("FirstBuildChangelog") + public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { + /** + * {@inheritDoc} + */ + @Override + public String getDisplayName() { + return "First Build Changelog"; + } + } +} From 5f681b3b44c579aa731b7ceac766a62cf4ded9b8 Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Tue, 19 Mar 2024 23:46:42 -0400 Subject: [PATCH 04/30] gitscm changes --- src/main/java/hudson/plugins/git/GitSCM.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/hudson/plugins/git/GitSCM.java b/src/main/java/hudson/plugins/git/GitSCM.java index d101a3456f..dfe6671865 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -28,6 +28,7 @@ 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.FirstBuildChangelog; import hudson.plugins.git.extensions.impl.PathRestriction; import hudson.plugins.git.extensions.impl.LocalBranch; import hudson.plugins.git.extensions.impl.RelativeTargetDirectory; @@ -1493,9 +1494,18 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l } if (!exclusion) { - // this is the first time we are building this branch, so there's no base line to compare against. - // if we force the changelog, it'll contain all the changes in the repo, which is not what we want. - listener.getLogger().println("First time build. Skipping changelog."); + FirstBuildChangelog firstBuildChangelog = getExtensions().get(FirstBuildChangelog.class); + if (firstBuildChangelog.isMakeChangelog()) { + changelog.to(out).max(1).execute(); + executed = true; + listener.getLogger().println("First time build. Latest changes added to changelog."); + } else { + // this is the first time we are building this branch, so there's no base line + // to compare against. + // if we force the changelog, it'll contain all the changes in the repo, which + // is not what we want. + listener.getLogger().println("First time build. Skipping changelog."); + } } else { changelog.to(out).max(MAX_CHANGELOG).execute(); executed = true; From 756f77ce4c56613f24db219a2d77728164eb73d0 Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Wed, 20 Mar 2024 00:00:56 -0400 Subject: [PATCH 05/30] testing for new trait behavior --- .../java/hudson/plugins/git/GitSCMTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index cfc0e82f8b..7a5cd68a41 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -1188,6 +1188,26 @@ public void testCleanBeforeCheckout() throws Exception { assertThat("Cleaning should happen before fetch", cleaningLogLine, is(lessThan(fetchingLogLine))); } + @Test + public void testFirstBuiltChangelog() throws Exception { + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); + FirstBuildChangelog fbc = new FirstBuildChangelog(); + fbc.setMakeChangelog(true); + ((GitSCM) p.getScm()).getExtensions().add(fbc); + + /* First build should should generate a changelog */ + final String commitFile1 = "commitFile1"; + commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); + final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1); + assertThat(firstBuild.getLog(50), hasItem("First time build. Latest changes added to changelog.")); + /* Second build should have normal behavior */ + final String commitFile2 = "commitFile2"; + commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); + final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2); + assertThat(secondBuild.getLog(50), not(hasItem("First time build. Latest changes added to changelog."))); + } + @Issue("JENKINS-8342") @Test public void testExcludedRegionMultiCommit() throws Exception { From d6f6cf9c4884f6a2bba24accaf1c3b531bab2e8a Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Wed, 20 Mar 2024 00:51:55 -0400 Subject: [PATCH 06/30] null check time --- src/main/java/hudson/plugins/git/GitSCM.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/hudson/plugins/git/GitSCM.java b/src/main/java/hudson/plugins/git/GitSCM.java index dfe6671865..8e95b481f7 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -1495,7 +1495,7 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l if (!exclusion) { FirstBuildChangelog firstBuildChangelog = getExtensions().get(FirstBuildChangelog.class); - if (firstBuildChangelog.isMakeChangelog()) { + if (firstBuildChangelog!=null&&firstBuildChangelog.isMakeChangelog()) { changelog.to(out).max(1).execute(); executed = true; listener.getLogger().println("First time build. Latest changes added to changelog."); From 27d5942b46f15a645e2acc1ab16a1eb24bab0d6c Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Fri, 22 Mar 2024 12:12:51 -0400 Subject: [PATCH 07/30] update to proper version number Co-authored-by: UltimateGeek <10050028+UltimateGeek@users.noreply.github.com> --- .../jenkins/plugins/git/traits/FirstBuildChangelogTrait.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java index 03834f0175..aea0f28c8f 100644 --- a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -36,7 +36,7 @@ /** * Exposes {@link FirstBuildChangelog} as a {@link SCMSourceTrait}. * - * @since 3.4.0 + * @since 5.2.0 */ public class FirstBuildChangelogTrait extends GitSCMExtensionTrait { From ce2fd99a123c28302fa589b76401d4932fc0de85 Mon Sep 17 00:00:00 2001 From: Derek Inskeep <77685829+rhit-inskeeda@users.noreply.github.com> Date: Fri, 22 Mar 2024 12:32:12 -0400 Subject: [PATCH 08/30] Update FirstBuildChangelogTrait Removed improper CloudBees copyright documentation, updated @param for the constructor --- .../git/traits/FirstBuildChangelogTrait.java | 27 +------------------ 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java index aea0f28c8f..28fdf4b90d 100644 --- a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -1,28 +1,3 @@ -/* - * The MIT License - * - * Copyright (c) 2017 CloudBees, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - package jenkins.plugins.git.traits; import hudson.Extension; @@ -51,7 +26,7 @@ public FirstBuildChangelogTrait() { /** * Stapler constructor. * - * @param extension the option to clean subdirectories which contain git repositories. + * @param extension the option to force first build to have a non-empty changelog. */ @DataBoundConstructor public FirstBuildChangelogTrait(@CheckForNull FirstBuildChangelog extension) { From 370d763b642f356830541006ccc876b14ddc396e Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 1 Apr 2024 19:57:58 -0600 Subject: [PATCH 09/30] Format new files with spotless:apply Use line termination that is consistent with the other files in the repository. Use import ordering as defined by spotless. --- .../extensions/impl/FirstBuildChangelog.java | 152 +++++++++--------- .../git/traits/FirstBuildChangelogTrait.java | 99 ++++++------ 2 files changed, 123 insertions(+), 128 deletions(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index 13c3a5c87d..b47f6f9d36 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -1,78 +1,74 @@ -package hudson.plugins.git.extensions.impl; - -import hudson.Extension; -import hudson.plugins.git.extensions.GitSCMExtension; -import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; -import java.util.Objects; - -import org.jenkinsci.Symbol; -import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.DataBoundSetter; - -/** - * First Build generates a changelog. - * - * @author Derek Inskeep - */ -public class FirstBuildChangelog extends GitSCMExtension { - private boolean makeChangelog; - - @DataBoundConstructor - public FirstBuildChangelog() { - } - - public boolean isMakeChangelog() { - return makeChangelog; - } - - @DataBoundSetter - public void setMakeChangelog(boolean makeChangelog) { - this.makeChangelog = makeChangelog; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FirstBuildChangelog that = (FirstBuildChangelog) o; - return makeChangelog == that.makeChangelog; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return Objects.hash(makeChangelog); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "FirstBuildChangelog{" + - "makeChangelog=" + makeChangelog + - '}'; - } - - @Extension - @Symbol("FirstBuildChangelog") - public static class DescriptorImpl extends GitSCMExtensionDescriptor { - - /** - * {@inheritDoc} - */ - @Override - public String getDisplayName() { - return "First Build Changelog"; - } - } -} +package hudson.plugins.git.extensions.impl; + +import hudson.Extension; +import hudson.plugins.git.extensions.GitSCMExtension; +import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; +import java.util.Objects; +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; +import org.kohsuke.stapler.DataBoundSetter; + +/** + * First Build generates a changelog. + * + * @author Derek Inskeep + */ +public class FirstBuildChangelog extends GitSCMExtension { + private boolean makeChangelog; + + @DataBoundConstructor + public FirstBuildChangelog() {} + + public boolean isMakeChangelog() { + return makeChangelog; + } + + @DataBoundSetter + public void setMakeChangelog(boolean makeChangelog) { + this.makeChangelog = makeChangelog; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FirstBuildChangelog that = (FirstBuildChangelog) o; + return makeChangelog == that.makeChangelog; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return Objects.hash(makeChangelog); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "FirstBuildChangelog{" + "makeChangelog=" + makeChangelog + '}'; + } + + @Extension + @Symbol("FirstBuildChangelog") + public static class DescriptorImpl extends GitSCMExtensionDescriptor { + + /** + * {@inheritDoc} + */ + @Override + public String getDisplayName() { + return "First Build Changelog"; + } + } +} diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java index 28fdf4b90d..06b794c718 100644 --- a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -1,50 +1,49 @@ -package jenkins.plugins.git.traits; - -import hudson.Extension; -import hudson.plugins.git.extensions.impl.FirstBuildChangelog; -import jenkins.scm.api.trait.SCMSourceTrait; -import org.jenkinsci.Symbol; -import org.kohsuke.stapler.DataBoundConstructor; - -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * Exposes {@link FirstBuildChangelog} as a {@link SCMSourceTrait}. - * - * @since 5.2.0 - */ -public class FirstBuildChangelogTrait extends GitSCMExtensionTrait { - - /** - * @deprecated Use constructor that accepts extension instead. - */ - @Deprecated - public FirstBuildChangelogTrait() { - this(null); - } - - /** - * Stapler constructor. - * - * @param extension the option to force first build to have a non-empty changelog. - */ - @DataBoundConstructor - public FirstBuildChangelogTrait(@CheckForNull FirstBuildChangelog extension) { - super(extension == null ? new FirstBuildChangelog() : extension); - } - - /** - * Our {@link hudson.model.Descriptor} - */ - @Extension - @Symbol("FirstBuildChangelog") - public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { - /** - * {@inheritDoc} - */ - @Override - public String getDisplayName() { - return "First Build Changelog"; - } - } -} +package jenkins.plugins.git.traits; + +import edu.umd.cs.findbugs.annotations.CheckForNull; +import hudson.Extension; +import hudson.plugins.git.extensions.impl.FirstBuildChangelog; +import jenkins.scm.api.trait.SCMSourceTrait; +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; + +/** + * Exposes {@link FirstBuildChangelog} as a {@link SCMSourceTrait}. + * + * @since 5.2.0 + */ +public class FirstBuildChangelogTrait extends GitSCMExtensionTrait { + + /** + * @deprecated Use constructor that accepts extension instead. + */ + @Deprecated + public FirstBuildChangelogTrait() { + this(null); + } + + /** + * Stapler constructor. + * + * @param extension the option to force first build to have a non-empty changelog. + */ + @DataBoundConstructor + public FirstBuildChangelogTrait(@CheckForNull FirstBuildChangelog extension) { + super(extension == null ? new FirstBuildChangelog() : extension); + } + + /** + * Our {@link hudson.model.Descriptor} + */ + @Extension + @Symbol("FirstBuildChangelog") + public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { + /** + * {@inheritDoc} + */ + @Override + public String getDisplayName() { + return "First Build Changelog"; + } + } +} From c66d1399462905e3fa712fe07a9acda9c9603fca Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 1 Apr 2024 20:06:11 -0600 Subject: [PATCH 10/30] Remove trailing space characters --- src/test/java/hudson/plugins/git/GitSCMTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index 7a5cd68a41..82d7509216 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -1195,7 +1195,7 @@ public void testFirstBuiltChangelog() throws Exception { FirstBuildChangelog fbc = new FirstBuildChangelog(); fbc.setMakeChangelog(true); ((GitSCM) p.getScm()).getExtensions().add(fbc); - + /* First build should should generate a changelog */ final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); From 88640c5205a8b5a036415254e90771e3c5e5d378 Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Mon, 1 Apr 2024 22:36:47 -0400 Subject: [PATCH 11/30] Changed equals to use proper equals method --- .../plugins/git/extensions/impl/FirstBuildChangelog.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index b47f6f9d36..5532c4c309 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -1,5 +1,6 @@ package hudson.plugins.git.extensions.impl; +import com.google.common.base.Objects; import hudson.Extension; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; @@ -33,14 +34,14 @@ public void setMakeChangelog(boolean makeChangelog) { */ @Override public boolean equals(Object o) { - if (this == o) { + if (this==o ) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FirstBuildChangelog that = (FirstBuildChangelog) o; - return makeChangelog == that.makeChangelog; + return Objects.equals(that.makeChangelog,makeChangelog); } /** From 62aad20b7cae79a4052aa6b46e895a0ba11ec5f0 Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Mon, 1 Apr 2024 22:36:47 -0400 Subject: [PATCH 12/30] Changed equals to use proper equals method --- .../plugins/git/extensions/impl/FirstBuildChangelog.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index b47f6f9d36..536f89d4f3 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -1,5 +1,6 @@ package hudson.plugins.git.extensions.impl; +import com.google.common.base.Objects; import hudson.Extension; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; @@ -33,14 +34,14 @@ public void setMakeChangelog(boolean makeChangelog) { */ @Override public boolean equals(Object o) { - if (this == o) { + if (this==o ) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FirstBuildChangelog that = (FirstBuildChangelog) o; - return makeChangelog == that.makeChangelog; + return Objects.equal(that.makeChangelog,makeChangelog); } /** From cab31cca7cdb9392211de140ff139d927a0dd572 Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Mon, 1 Apr 2024 22:41:43 -0400 Subject: [PATCH 13/30] Changed equals to use proper equals method --- .../hudson/plugins/git/extensions/impl/FirstBuildChangelog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index 536f89d4f3..5f9010b312 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } FirstBuildChangelog that = (FirstBuildChangelog) o; - return Objects.equal(that.makeChangelog,makeChangelog); + return Objects.equal(makeChangelog,that.makeChangelog); } /** From 84846d78adbf4cc56f70c7955f386d44cc08c412 Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Mon, 1 Apr 2024 22:44:09 -0400 Subject: [PATCH 14/30] changed to compatible equal --- .../hudson/plugins/git/extensions/impl/FirstBuildChangelog.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index 5f9010b312..511c9c39eb 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -41,6 +41,7 @@ public boolean equals(Object o) { return false; } FirstBuildChangelog that = (FirstBuildChangelog) o; + //changed to proper equals return Objects.equal(makeChangelog,that.makeChangelog); } From 6f4fa4d07d4c77e7f91a5b1c44115fcb2b86a1ea Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 1 Apr 2024 22:18:17 -0600 Subject: [PATCH 15/30] Fix Mark's poor code review --- .../plugins/git/extensions/impl/FirstBuildChangelog.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index 511c9c39eb..b47f6f9d36 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -1,6 +1,5 @@ package hudson.plugins.git.extensions.impl; -import com.google.common.base.Objects; import hudson.Extension; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; @@ -34,15 +33,14 @@ public void setMakeChangelog(boolean makeChangelog) { */ @Override public boolean equals(Object o) { - if (this==o ) { + if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FirstBuildChangelog that = (FirstBuildChangelog) o; - //changed to proper equals - return Objects.equal(makeChangelog,that.makeChangelog); + return makeChangelog == that.makeChangelog; } /** From 1664429828642f15483726abe56eaf1be28c1cec Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 1 Apr 2024 22:18:47 -0600 Subject: [PATCH 16/30] Use leading lower case letter for the symbol Jenkins symbol names consistently start with a lower case letter. --- .../hudson/plugins/git/extensions/impl/FirstBuildChangelog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index b47f6f9d36..da24f1e444 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -60,7 +60,7 @@ public String toString() { } @Extension - @Symbol("FirstBuildChangelog") + @Symbol("firstBuildChangelog") public static class DescriptorImpl extends GitSCMExtensionDescriptor { /** From 47ab82b2316a869599551ef1bea950b427ac8b98 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 1 Apr 2024 22:19:32 -0600 Subject: [PATCH 17/30] Use sentence case for display name --- .../hudson/plugins/git/extensions/impl/FirstBuildChangelog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index da24f1e444..d95855339c 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -68,7 +68,7 @@ public static class DescriptorImpl extends GitSCMExtensionDescriptor { */ @Override public String getDisplayName() { - return "First Build Changelog"; + return "First build changelog"; } } } From a9eacdf8770c16bc777b380e8f79399c1334571a Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Tue, 2 Apr 2024 16:30:36 -0600 Subject: [PATCH 18/30] Set API release to 5.3.0 --- .../jenkins/plugins/git/traits/FirstBuildChangelogTrait.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java index 06b794c718..1fd20bb380 100644 --- a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -10,7 +10,7 @@ /** * Exposes {@link FirstBuildChangelog} as a {@link SCMSourceTrait}. * - * @since 5.2.0 + * @since 5.3.0 */ public class FirstBuildChangelogTrait extends GitSCMExtensionTrait { From 143b0d2f524129d9e5e16fc06365235c02ebbfe8 Mon Sep 17 00:00:00 2001 From: Derek Inskeep Date: Mon, 15 Apr 2024 21:11:22 -0400 Subject: [PATCH 19/30] removed groovy and checkbox --- .../plugins/git/extensions/impl/FirstBuildChangelog.java | 4 +++- .../git/extensions/impl/FirstBuildChangelog/config.groovy | 7 ------- .../impl/FirstBuildChangelog/help-makeChangelog.html | 3 --- src/test/java/hudson/plugins/git/GitSCMTest.java | 1 - 4 files changed, 3 insertions(+), 12 deletions(-) delete mode 100644 src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy delete mode 100644 src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html diff --git a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java index d95855339c..91301c0f2a 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/FirstBuildChangelog.java @@ -17,7 +17,9 @@ public class FirstBuildChangelog extends GitSCMExtension { private boolean makeChangelog; @DataBoundConstructor - public FirstBuildChangelog() {} + public FirstBuildChangelog() { + makeChangelog = true; + } public boolean isMakeChangelog() { return makeChangelog; diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy deleted file mode 100644 index c18ee67750..0000000000 --- a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/config.groovy +++ /dev/null @@ -1,7 +0,0 @@ -package hudson.plugins.git.extensions.impl.FirstBuildChangelog - -def f = namespace(lib.FormTagLib) - -f.entry(field: "makeChangelog") { - f.checkbox(title: _("Make Changelog")) -} diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html deleted file mode 100644 index cc172dcebc..0000000000 --- a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help-makeChangelog.html +++ /dev/null @@ -1,3 +0,0 @@ -
- First builds create changelog of latest commit, if any. -
diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index 82d7509216..7efada4462 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -1193,7 +1193,6 @@ public void testFirstBuiltChangelog() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); FirstBuildChangelog fbc = new FirstBuildChangelog(); - fbc.setMakeChangelog(true); ((GitSCM) p.getScm()).getExtensions().add(fbc); /* First build should should generate a changelog */ From 5dfe120bda71a399ebab798ae48a5a48fa561fcb Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Tue, 16 Apr 2024 22:14:36 -0400 Subject: [PATCH 20/30] Update to documentation and applying spotless --- README.adoc | 16 + pom.xml | 130 +- .../git/ApiTokenPropertyConfiguration.java | 30 +- .../java/hudson/plugins/git/BranchSpec.java | 51 +- .../plugins/git/ChangelogToBranchOptions.java | 10 +- .../plugins/git/GitBranchSpecifierColumn.java | 16 +- .../plugins/git/GitBranchTokenMacro.java | 21 +- .../plugins/git/GitChangeLogParser.java | 29 +- .../java/hudson/plugins/git/GitChangeSet.java | 107 +- .../hudson/plugins/git/GitChangeSetList.java | 9 +- .../java/hudson/plugins/git/GitPublisher.java | 233 ++- .../git/GitRevisionBuildParameters.java | 63 +- .../plugins/git/GitRevisionTokenMacro.java | 19 +- src/main/java/hudson/plugins/git/GitSCM.java | 697 +++++---- .../git/GitSCMBackwardCompatibility.java | 89 +- .../java/hudson/plugins/git/GitStatus.java | 178 ++- .../plugins/git/GitStatusCrumbExclusion.java | 3 +- .../java/hudson/plugins/git/GitTagAction.java | 42 +- .../hudson/plugins/git/ObjectIdConverter.java | 19 +- .../plugins/git/RemoteConfigConverter.java | 109 +- .../plugins/git/RevisionParameterAction.java | 63 +- .../plugins/git/SubmoduleCombinator.java | 34 +- .../hudson/plugins/git/SubmoduleConfig.java | 20 +- .../hudson/plugins/git/UserMergeOptions.java | 42 +- .../hudson/plugins/git/UserRemoteConfig.java | 102 +- .../plugins/git/browser/AssemblaWeb.java | 31 +- .../plugins/git/browser/BitbucketServer.java | 22 +- .../plugins/git/browser/BitbucketWeb.java | 20 +- .../java/hudson/plugins/git/browser/CGit.java | 24 +- .../browser/FisheyeGitRepositoryBrowser.java | 208 ++- .../git/browser/GitBlitRepositoryBrowser.java | 57 +- .../hudson/plugins/git/browser/GitLab.java | 24 +- .../hudson/plugins/git/browser/GitList.java | 23 +- .../git/browser/GitRepositoryBrowser.java | 47 +- .../hudson/plugins/git/browser/GitWeb.java | 49 +- .../hudson/plugins/git/browser/GithubWeb.java | 32 +- .../hudson/plugins/git/browser/Gitiles.java | 24 +- .../plugins/git/browser/GitoriousWeb.java | 24 +- .../hudson/plugins/git/browser/GogsGit.java | 22 +- .../hudson/plugins/git/browser/KilnGit.java | 23 +- .../plugins/git/browser/Phabricator.java | 14 +- .../plugins/git/browser/RedmineWeb.java | 27 +- .../hudson/plugins/git/browser/RhodeCode.java | 20 +- .../hudson/plugins/git/browser/Stash.java | 36 +- .../browser/TFS2013GitRepositoryBrowser.java | 67 +- .../plugins/git/browser/ViewGitWeb.java | 57 +- .../git/browser/casc/GitLabConfigurator.java | 4 +- .../git/extensions/FakeGitSCMExtension.java | 3 +- .../GitClientConflictException.java | 3 +- .../plugins/git/extensions/GitClientType.java | 10 +- .../git/extensions/GitSCMExtension.java | 148 +- .../extensions/GitSCMExtensionDescriptor.java | 2 +- .../extensions/impl/AuthorInChangelog.java | 3 +- .../extensions/impl/BuildChooserSetting.java | 6 +- .../impl/BuildSingleRevisionOnly.java | 3 +- .../extensions/impl/ChangelogToBranch.java | 5 +- .../git/extensions/impl/CheckoutOption.java | 17 +- .../extensions/impl/CleanBeforeCheckout.java | 11 +- .../git/extensions/impl/CleanCheckout.java | 11 +- .../git/extensions/impl/CloneOption.java | 32 +- .../extensions/impl/DisableRemotePoll.java | 3 +- .../git/extensions/impl/GitLFSPull.java | 11 +- .../extensions/impl/IgnoreNotifyCommit.java | 3 +- .../git/extensions/impl/LocalBranch.java | 10 +- .../git/extensions/impl/MessageExclusion.java | 97 +- .../git/extensions/impl/PathRestriction.java | 35 +- .../git/extensions/impl/PerBuildTag.java | 11 +- .../git/extensions/impl/PreBuildMerge.java | 67 +- .../git/extensions/impl/PruneStaleBranch.java | 8 +- .../git/extensions/impl/PruneStaleTag.java | 16 +- .../impl/RelativeTargetDirectory.java | 7 +- .../extensions/impl/SparseCheckoutPath.java | 19 +- .../extensions/impl/SparseCheckoutPaths.java | 31 +- .../git/extensions/impl/SubmoduleOption.java | 49 +- .../git/extensions/impl/UserExclusion.java | 17 +- .../git/extensions/impl/UserIdentity.java | 24 +- .../git/extensions/impl/WipeWorkspace.java | 6 +- .../plugins/git/opt/PreBuildMergeOptions.java | 25 +- .../git/util/AncestryBuildChooser.java | 72 +- .../java/hudson/plugins/git/util/Build.java | 29 +- .../hudson/plugins/git/util/BuildChooser.java | 64 +- .../plugins/git/util/BuildChooserContext.java | 10 +- .../git/util/BuildChooserDescriptor.java | 4 +- .../hudson/plugins/git/util/BuildData.java | 104 +- .../git/util/CommitTimeComparator.java | 15 +- .../plugins/git/util/DefaultBuildChooser.java | 92 +- .../hudson/plugins/git/util/GitUtils.java | 126 +- .../plugins/git/util/InverseBuildChooser.java | 22 +- .../plugins/git/AbstractGitSCMSource.java | 937 ++++++------ .../jenkins/plugins/git/GitBranchSCMHead.java | 7 +- .../plugins/git/GitBranchSCMRevision.java | 3 - .../plugins/git/GitCredentialBindings.java | 34 +- .../plugins/git/GitHooksConfiguration.java | 34 +- .../plugins/git/GitRemoteHeadRefAction.java | 11 +- .../jenkins/plugins/git/GitSCMBuilder.java | 18 +- .../java/jenkins/plugins/git/GitSCMFile.java | 12 +- .../jenkins/plugins/git/GitSCMFileSystem.java | 86 +- .../jenkins/plugins/git/GitSCMMatrixUtil.java | 8 +- .../jenkins/plugins/git/GitSCMSource.java | 141 +- .../plugins/git/GitSCMSourceContext.java | 18 +- .../plugins/git/GitSCMSourceDefaults.java | 12 +- .../plugins/git/GitSCMSourceRequest.java | 4 +- .../jenkins/plugins/git/GitSCMTelescope.java | 89 +- .../java/jenkins/plugins/git/GitStep.java | 20 +- .../jenkins/plugins/git/GitTagSCMHead.java | 1 - .../jenkins/plugins/git/GitToolChooser.java | 114 +- .../git/GitUsernamePasswordBinding.java | 131 +- .../plugins/git/MatrixGitPublisher.java | 3 +- .../plugins/git/MergeWithGitSCMExtension.java | 21 +- .../git/traits/BranchDiscoveryTrait.java | 5 +- .../git/traits/CleanAfterCheckoutTrait.java | 3 +- .../git/traits/CleanBeforeCheckoutTrait.java | 3 +- .../git/traits/DiscoverOtherRefsTrait.java | 15 +- .../git/traits/GitBrowserSCMSourceTrait.java | 3 +- .../git/traits/GitSCMExtensionTrait.java | 2 +- .../GitSCMExtensionTraitDescriptor.java | 48 +- .../git/traits/GitToolSCMSourceTrait.java | 9 +- .../traits/IgnoreOnPushNotificationTrait.java | 5 +- .../plugins/git/traits/LocalBranchTrait.java | 2 +- .../git/traits/PruneStaleTagTrait.java | 5 +- .../git/traits/RefSpecsSCMSourceTrait.java | 4 +- .../git/traits/RemoteNameSCMSourceTrait.java | 14 +- .../plugins/git/traits/TagDiscoveryTrait.java | 8 +- .../plugins/git/AbstractGitProject.java | 200 ++- .../plugins/git/AbstractGitRepository.java | 23 +- .../plugins/git/AbstractGitTestCase.java | 305 ++-- .../hudson/plugins/git/BranchSpecTest.java | 88 +- .../git/ChangelogToBranchOptionsTest.java | 3 +- .../git/CheckoutStepSnippetizerTest.java | 186 +-- .../git/CliGitSCMTriggerLocalPollTest.java | 10 +- .../git/CliGitSCMTriggerRemotePollTest.java | 7 +- .../git/CredentialsUserRemoteConfigTest.java | 48 +- .../git/GitBranchSpecifierColumnTest.java | 12 +- .../plugins/git/GitChangeLogParserTest.java | 29 +- .../plugins/git/GitChangeSetBadArgsTest.java | 18 +- .../plugins/git/GitChangeSetBasicTest.java | 142 +- .../plugins/git/GitChangeSetEmptyTest.java | 7 +- .../plugins/git/GitChangeSetEuroTest.java | 3 +- .../plugins/git/GitChangeSetListTest.java | 14 +- .../git/GitChangeSetPluginHistoryTest.java | 32 +- .../plugins/git/GitChangeSetSimpleTest.java | 101 +- .../hudson/plugins/git/GitChangeSetTest.java | 97 +- .../git/GitChangeSetTimestampTest.java | 5 +- .../plugins/git/GitChangeSetTruncateTest.java | 76 +- .../hudson/plugins/git/GitChangeSetUtil.java | 118 +- .../java/hudson/plugins/git/GitHooksTest.java | 124 +- .../hudson/plugins/git/GitPublisherTest.java | 520 ++++--- .../git/GitRevisionTokenMacroTest.java | 18 +- .../hudson/plugins/git/GitSCMBrowserTest.java | 11 +- .../hudson/plugins/git/GitSCMSlowTest.java | 99 +- .../java/hudson/plugins/git/GitSCMTest.java | 1346 ++++++++++------- .../hudson/plugins/git/GitSCMUnitTest.java | 92 +- .../git/GitStatusCrumbExclusionTest.java | 14 +- .../plugins/git/GitStatusSimpleTest.java | 2 +- .../hudson/plugins/git/GitStatusTest.java | 107 +- .../plugins/git/GitStatusTheoriesTest.java | 47 +- .../hudson/plugins/git/GitTagActionTest.java | 54 +- .../git/JGitSCMTriggerLocalPollTest.java | 14 +- .../git/JGitSCMTriggerRemotePollTest.java | 12 +- .../RevisionParameterActionRemoteUrlTest.java | 14 +- .../git/RevisionParameterActionTest.java | 28 +- .../hudson/plugins/git/Security2478Test.java | 38 +- .../plugins/git/SubmoduleCombinatorTest.java | 9 +- .../plugins/git/SubmoduleConfigTest.java | 7 +- .../java/hudson/plugins/git/TestGitRepo.java | 82 +- .../plugins/git/UserMergeOptionsTest.java | 43 +- .../git/UserRemoteConfigRefSpecTest.java | 46 +- .../plugins/git/UserRemoteConfigTest.java | 50 +- .../browser/AssemblaWebDoCheckURLTest.java | 47 +- .../plugins/git/browser/AssemblaWebTest.java | 4 +- .../git/browser/BitbucketServerTest.java | 33 +- .../plugins/git/browser/BitbucketWebTest.java | 33 +- .../hudson/plugins/git/browser/CGitTest.java | 4 +- .../FisheyeGitRepositoryBrowserTest.java | 6 +- .../browser/GitBlitRepositoryBrowserTest.java | 14 +- .../git/browser/GitChangeSetSample.java | 16 +- .../plugins/git/browser/GitLabTest.java | 36 +- .../git/browser/GitLabWorkflowTest.java | 21 +- .../plugins/git/browser/GitListTest.java | 35 +- .../git/browser/GitRepositoryBrowserTest.java | 15 +- .../plugins/git/browser/GitWebTest.java | 34 +- .../plugins/git/browser/GithubWebTest.java | 118 +- .../plugins/git/browser/GitilesTest.java | 9 +- .../plugins/git/browser/GitoriousWebTest.java | 45 +- .../plugins/git/browser/GogsGitTest.java | 36 +- .../plugins/git/browser/KilnGitTest.java | 38 +- .../plugins/git/browser/PhabricatorTest.java | 10 +- .../plugins/git/browser/RedmineWebTest.java | 47 +- .../plugins/git/browser/RhodeCodeTest.java | 40 +- .../hudson/plugins/git/browser/StashTest.java | 9 +- .../TFS2013GitRepositoryBrowserTest.java | 28 +- .../TFS2013GitRepositoryBrowserXSSTest.java | 12 +- .../plugins/git/browser/ViewGitWebTest.java | 42 +- .../browser/casc/GitLabConfiguratorTest.java | 18 +- .../git/extensions/GitSCMExtensionTest.java | 116 +- .../impl/AuthorInChangelogTest.java | 11 +- .../impl/BuildSingleRevisionOnlyTest.java | 21 +- .../impl/ChangelogToBranchTest.java | 11 +- .../extensions/impl/CheckoutOptionTest.java | 6 +- .../impl/CheckoutOptionWorkflowTest.java | 16 +- .../extensions/impl/CleanCheckoutTest.java | 6 +- .../extensions/impl/CloneOptionDepthTest.java | 5 +- .../impl/CloneOptionHonorRefSpecTest.java | 41 +- .../impl/CloneOptionNoTagsTest.java | 30 +- .../CloneOptionShallowDefaultTagsTest.java | 16 +- .../git/extensions/impl/CloneOptionTest.java | 5 +- .../git/extensions/impl/EnforceGitClient.java | 11 +- .../git/extensions/impl/GitLFSPullTest.java | 4 +- .../impl/IgnoreNotifyCommitTest.java | 4 +- .../git/extensions/impl/LocalBranchTest.java | 10 +- .../git/extensions/impl/LogHandler.java | 3 +- .../extensions/impl/MessageExclusionTest.java | 66 +- .../extensions/impl/PathRestrictionTest.java | 91 +- .../extensions/impl/PreBuildMergeTest.java | 52 +- .../extensions/impl/PruneStaleBranchTest.java | 4 +- .../impl/PruneStaleTagPipelineTest.java | 40 +- .../extensions/impl/PruneStaleTagTest.java | 50 +- .../impl/SparseCheckoutPathTest.java | 4 +- .../impl/SparseCheckoutPathsTest.java | 17 +- .../impl/SubmoduleOptionDepthTest.java | 5 +- .../extensions/impl/SubmoduleOptionTest.java | 88 +- .../extensions/impl/UserExclusionTest.java | 63 +- .../git/extensions/impl/UserIdentityTest.java | 18 +- .../extensions/impl/WipeWorkspaceTest.java | 10 +- .../git/opt/PreBuildMergeOptionsTest.java | 22 +- .../ApiTokenPropertyConfigurationTest.java | 85 +- .../git/util/AncestryBuildChooserTest.java | 133 +- .../git/util/BuildDataLoggingTest.java | 14 +- .../plugins/git/util/BuildDataTest.java | 41 +- .../hudson/plugins/git/util/BuildTest.java | 6 +- .../git/util/CandidateRevisionsTest.java | 22 +- .../git/util/CommitTimeComparatorTest.java | 27 +- .../git/util/DefaultBuildChooserTest.java | 43 +- .../git/util/GitUtilsJenkinsRuleTest.java | 6 +- .../hudson/plugins/git/util/GitUtilsTest.java | 22 +- .../plugins/git/AbstractGitSCMSourceTest.java | 328 ++-- .../git/AbstractGitSCMSourceTrivialTest.java | 10 +- .../git/BrowsersJCasCCompatibilityTest.java | 304 ++-- .../jenkins/plugins/git/CliGitCommand.java | 33 +- .../plugins/git/GitBranchSCMHeadTest.java | 24 +- .../git/GitHooksConfigurationTest.java | 15 +- .../git/GitJCasCCompatibilityTest.java | 7 +- .../git/GitRemoteHeadRefActionTest.java | 4 +- .../plugins/git/GitSCMBuilderTest.java | 722 ++++----- .../plugins/git/GitSCMFileSystemTest.java | 128 +- .../git/GitSCMJCasCCompatibilityTest.java | 11 +- .../plugins/git/GitSCMSourceDefaultsTest.java | 4 +- .../jenkins/plugins/git/GitSCMSourceTest.java | 290 ++-- .../plugins/git/GitSCMSourceTraitsTest.java | 228 ++- .../plugins/git/GitSCMTelescopeTest.java | 58 +- .../plugins/git/GitSampleRepoRule.java | 73 +- .../java/jenkins/plugins/git/GitStepTest.java | 105 +- .../plugins/git/GitToolChooserTest.java | 220 +-- .../git/GitToolJCasCCompatibilityTest.java | 38 +- .../git/GitUsernamePasswordBindingTest.java | 149 +- ...braryWithLegacyJCasCCompatibilityTest.java | 280 ++-- ...braryWithModernJCasCCompatibilityTest.java | 237 ++- .../git/MergeWithGitSCMExtensionTest.java | 35 +- .../jenkins/plugins/git/ModernScmTest.java | 11 +- .../java/jenkins/plugins/git/RandomOrder.java | 4 +- .../traits/DiscoverOtherRefsTraitTest.java | 5 +- .../git/traits/GitSCMExtensionTraitTest.java | 15 +- .../traits/MultibranchProjectTraitsTest.java | 126 +- .../git/traits/PruneStaleBranchTraitTest.java | 9 +- .../plugins/gitclient/TestCliGitAPIImpl.java | 1 - .../plugins/gitclient/TestJGitAPIImpl.java | 6 +- .../AbstractGitTagMessageExtensionTest.java | 30 +- .../GitTagMessageExtensionTest.java | 14 +- 268 files changed, 8588 insertions(+), 7280 deletions(-) diff --git a/README.adoc b/README.adoc index 9d4aae7d1d..18c12088b9 100644 --- a/README.adoc +++ b/README.adoc @@ -1220,6 +1220,21 @@ Inverse:: This is useful, for example, when you have jobs building your master and various release branches and you want a second job which builds all new feature branches. For example, branches which do not match these patterns without redundantly building master and the release branches again each time they change. +[#firstBuildBehavior] +==== First Build Changelog behavior + +image:/images/git-extension-for-first-build.png[First Build Changelog behavior] + +The Jenkins git plugin provides an option to trigger pipeline build process on the first commit on a branch. By default, no changelog is generated causing any pipeline process to not be triggered but with this option selected changes are found between the new branch and its parent commit. + +[source,groovy] +---- + checkout scmGit(branches: [[name: 'master']], + extensions: [firstBuildChangelog()], + userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]) + + +---- [#merge-extensions] === Merge Extensions @@ -1424,6 +1439,7 @@ For example, they might choose to place the cache directories in `/var/cache/jen The default git cache directory location can be overridden by setting the property `jenkins.plugins.git.AbstractGitSCMSource.cacheRootDir=/var/cache/jenkins`. + [#git-publisher] == Git Publisher diff --git a/pom.xml b/pom.xml index 30de966abe..5452f78b81 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,88 @@ + + + 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 + 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 + token-macro + true + + + org.jenkins-ci.plugins.workflow + workflow-scm-step + + + org.jenkins-ci.plugins.workflow + workflow-step-api + + + io.jenkins.configuration-as-code + test-harness test - junit - junit + io.jenkins.plugins + pipeline-groovy-lib test - org.mockito - mockito-core + junit + junit test @@ -164,32 +185,21 @@ 3.16.1 test - - org.jenkins-ci.plugins - credentials-binding - - - - org.jenkins-ci.plugins - parameterized-trigger - true + org.jenkins-ci.main + jenkins-test-harness + test 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 @@ -200,12 +210,13 @@ org.jenkins-ci.plugins.workflow - workflow-job + workflow-basic-steps test org.jenkins-ci.plugins.workflow - workflow-basic-steps + workflow-cps + tests test @@ -215,34 +226,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..12442298af 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,9 @@ public String getName() { } public void setName(String name) { - if(name == null) - throw new IllegalArgumentException(); - else if(name.length() == 0) - this.name = "**"; - else - this.name = name.trim(); + if (name == null) throw new IllegalArgumentException(); + else if (name.length() == 0) this.name = "**"; + else this.name = name.trim(); } @DataBoundConstructor @@ -97,7 +92,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 +109,14 @@ public List filterMatching(Collection branches) { public List filterMatching(Collection branches, EnvVars env) { List items = new ArrayList<>(); - - for(String b : branches) { - if(matches(b, env)) - items.add(b); + + 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 +124,11 @@ 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)) - items.add(b); + + for (Branch b : branches) { + if (matches(b.getName(), env)) items.add(b); } - + return items; } @@ -172,7 +166,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 +183,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 +197,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 +213,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..ae24a32d73 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,26 @@ 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 +88,7 @@ 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..47be7d92cb 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,8 @@ 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,8 +178,7 @@ private void parseCommit(List lines) { StringBuilder message = new StringBuilder(); for (String line : lines) { - if( line.length() < 1) - continue; + if (line.length() < 1) continue; if (line.startsWith("commit ")) { String[] split = line.split(" "); if (split.length > 1) this.id = split[1]; @@ -193,8 +190,7 @@ private void parseCommit(List lines) { 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 +213,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 +239,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 +253,16 @@ 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 +283,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 +326,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 +348,7 @@ public void setParent(ChangeLogSet parent) { super.setParent(parent); } - public @CheckForNull - String getParentCommit() { + public @CheckForNull String getParentCommit() { return parentCommit; } @@ -434,8 +431,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 +456,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 +469,7 @@ public User findOrCreateUser(String csAuthor, String csAuthorEmail, boolean crea } if (user != null && setUserDetails) { user.setFullName(csAuthor); - if (hasMailerPlugin()) - setMail(user, csAuthorEmail); + if (hasMailerPlugin()) setMail(user, csAuthorEmail); user.save(); } } catch (AuthenticationException authException) { @@ -578,13 +577,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,7 +621,7 @@ 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()); @@ -636,7 +635,7 @@ public String getBranch() { return null; } - @ExportedBean(defaultVisibility=999) + @ExportedBean(defaultVisibility = 999) public static class Path implements AffectedFile { private String src; @@ -661,7 +660,7 @@ public String getDst() { return dst; } - @Exported(name="file") + @Exported(name = "file") public String getPath() { return path; } @@ -673,12 +672,12 @@ public GitChangeSet getChangeSet() { @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..9911bce0d3 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,10 +17,9 @@ 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) - log.setParent(this); + for (GitChangeSet log : logs) log.setParent(this); } public boolean isEmptySet() { @@ -40,5 +38,4 @@ public List getLogs() { 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 bbb8332dff..1972f5b4b1 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,23 +125,22 @@ public List getNotesToPush() { return notesToPush; } - - + 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; @@ -156,10 +155,9 @@ protected GitClient getGitClient( throws IOException, InterruptedException { return gitSCM.createClient(listener, environment, build, build.getWorkspace(), cmd); } - + @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, @@ -182,15 +180,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 = getGitClient(gitSCM, listener, environment, build, cmd); + final GitClient git = getGitClient(gitSCM, listener, environment, build, cmd); URIish remoteURI; @@ -201,8 +200,7 @@ 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)) - git.deleteTag(buildnumber); + if (git.tagExists(buildnumber)) git.deleteTag(buildnumber); // And add the success / fail state into the tag. buildnumber += "-" + buildResult.toString(); @@ -221,14 +219,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")); @@ -238,18 +241,16 @@ public boolean perform(AbstractBuild build, if (isPushTags()) { for (final TagToPush t : tagsToPush) { - if (t.getTagName() == null) - throw new AbortException("No tag to push defined"); + if (t.getTagName() == null) throw new AbortException("No tag to push defined"); - if (t.getTargetRepoName() == null) - throw new AbortException("No target repo to push to defined"); + 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) @@ -261,21 +262,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); @@ -286,20 +287,18 @@ else if (!tagExists) { } } } - + if (isPushBranches()) { for (final BranchToPush b : branchesToPush) { - if (b.getBranchName() == null) - throw new AbortException("No branch to push defined"); + if (b.getBranchName() == null) throw new AbortException("No branch to push defined"); - if (b.getTargetRepoName() == null) - throw new AbortException("No branch repo to push to defined"); + 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) @@ -311,17 +310,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)); @@ -329,11 +335,10 @@ else if (!tagExists) { } } } - + if (isPushNotes()) { for (final NoteToPush b : notesToPush) { - if (b.getnoteMsg() == null) - throw new AbortException("No note to push defined"); + if (b.getnoteMsg() == null) throw new AbortException("No note to push defined"); b.setEmptyTargetRepoToOrigin(); String noteMsgTmp = environment.expand(b.getnoteMsg()); @@ -341,9 +346,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) { @@ -354,23 +359,24 @@ 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; } } @@ -382,8 +388,7 @@ else if (!tagExists) { */ protected Object readResolve() { // Default unspecified to v0 - if(configVersion == null) - this.configVersion = 0L; + if (configVersion == null) this.configVersion = 0L; if (this.configVersion < 1L) { if (tagsToPush == null) { @@ -393,8 +398,8 @@ protected Object readResolve() { return this; } - - @Extension(ordinal=-1) + + @Extension(ordinal = -1) public static class DescriptorImpl extends BuildStepDescriptor { public String getDisplayName() { return "Git Publisher"; @@ -415,8 +420,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) { @@ -426,40 +431,35 @@ 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) - return FormValidation.ok(); + if (remote.length() == 0 && isMerge) return FormValidation.ok(); - FormValidation validation = checkFieldNotEmpty(remote, - Messages.GitPublisher_Check_RemoteName()); - if (validation.kind != FormValidation.Kind.OK) - return validation; + 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 + "'"); + return FormValidation.error("No remote repository configured with name '" + remote + "'"); return FormValidation.ok(); } - + public boolean isApplicable(Class jobType) { return true; } @@ -476,15 +476,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; } @@ -492,10 +492,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"; } } } @@ -555,7 +555,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; @@ -571,7 +572,6 @@ public String getDisplayName() { } } } - public static final class NoteToPush extends PushConfig { @@ -582,26 +582,24 @@ 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 @@ -612,5 +610,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..a946d0a3ab 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,23 @@ 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 8e95b481f7..57b9bb4e90 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -1,26 +1,29 @@ package hudson.plugins.git; -import com.cloudbees.plugins.credentials.CredentialsMatcher; -import com.cloudbees.plugins.credentials.CredentialsMatchers; +import static hudson.init.InitMilestone.JOB_LOADED; +import static hudson.init.InitMilestone.PLUGINS_STARTED; +import static hudson.scm.PollingResult.*; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; -import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import com.google.common.collect.Iterables; - import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; +import hudson.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; @@ -29,13 +32,14 @@ import hudson.plugins.git.extensions.impl.ChangelogToBranch; import hudson.plugins.git.extensions.impl.CloneOption; import hudson.plugins.git.extensions.impl.FirstBuildChangelog; -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; @@ -50,30 +54,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; @@ -95,22 +76,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. @@ -124,6 +116,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); @@ -137,17 +130,21 @@ 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 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"; @@ -160,8 +157,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 @@ -170,8 +167,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<>(); @@ -189,7 +185,9 @@ public GitSCM(String repositoryUrl) { this( createRepoList(repositoryUrl, null), Collections.singletonList(new BranchSpec("")), - null, null, Collections.emptyList()); + null, + null, + Collections.emptyList()); } @Deprecated @@ -228,7 +226,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. } @@ -291,7 +289,6 @@ public Object readResolve() throws IOException { } } - if (configVersion < 1 && branches != null) { // Migrate the branch specs from // single * wildcard, to ** wildcard. @@ -304,7 +301,7 @@ 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) @@ -329,12 +326,11 @@ public Object readResolve() throws IOException { } } - if (extensions==null) - extensions = new DescribableList<>(Saveable.NOOP); + 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 { @@ -361,36 +357,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) { @@ -460,14 +453,14 @@ 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)); @@ -490,7 +483,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 @@ -508,7 +502,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); @@ -528,7 +523,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])); @@ -556,7 +551,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<>(); } @@ -633,17 +629,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); @@ -667,7 +662,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; } @@ -686,17 +683,25 @@ boolean requiresWorkspaceForPolling(EnvVars environment) { } @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 Jenkins ought to build ? listener.getLogger().println("Using strategy: " + getBuildChooser().getDisplayName()); @@ -713,13 +718,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); @@ -730,12 +739,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()) { @@ -748,7 +757,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(); } } @@ -761,10 +772,13 @@ 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()); + if (matcher.matches()) + name = remote + + head.substring(matcher.group(1).length()); else name = remote + "/" + head; if (!branchSpec.matches(name, environment)) continue; @@ -773,11 +787,15 @@ private PollingResult compareRemoteRevisionWithImpl(Job project, Launcher 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; } } @@ -787,9 +805,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()) { @@ -811,8 +831,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)) { @@ -839,13 +865,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); } /** @@ -862,23 +890,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 */ @@ -900,13 +943,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; } @@ -916,7 +966,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()) { @@ -928,13 +978,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); } } } @@ -944,9 +996,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 { @@ -976,10 +1027,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()) { @@ -997,7 +1047,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); } } } @@ -1010,9 +1060,7 @@ 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) - str.add(rs.toString()); + 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); @@ -1039,7 +1087,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(); @@ -1051,10 +1099,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) { @@ -1063,11 +1113,13 @@ public GitTool getGitTool(Node builtOn, EnvVars env, TaskListener listener) { this.environment = environment; } - public T actOnBuild(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException { + 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 { + public T actOnProject(@NonNull ContextCallable, T> callable) + throws IOException, InterruptedException { return callable.invoke(project, FilePath.localChannel); } @@ -1084,13 +1136,15 @@ 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() { + 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()); + public T actOnProject(@NonNull ContextCallable, T> callable) + throws IOException, InterruptedException { + return callable.invoke(project, Channel.current()); } public Run getBuild() { @@ -1114,11 +1168,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); @@ -1129,7 +1185,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 @@ -1138,35 +1194,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); @@ -1182,9 +1241,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()); } } } @@ -1198,25 +1260,25 @@ 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) - log.println("Fetching changes from the remote Git repository"); - else - log.println(MessageFormat.format("Fetching changes from {0} remote Git repositories", repos.size())); + if (repos.size() == 1) log.println("Fetching changes from the remote Git repository"); + 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); } @@ -1234,7 +1296,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; } @@ -1274,7 +1336,13 @@ 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()) { @@ -1282,9 +1350,10 @@ public void checkout(Run build, Launcher launcher, FilePath workspace, Tas } if (VERBOSE) - listener.getLogger().println("Using checkout strategy: " + getBuildChooser().getDisplayName()); + 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) { @@ -1295,8 +1364,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) { @@ -1310,14 +1383,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 @@ -1328,7 +1401,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); @@ -1338,22 +1411,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); @@ -1382,24 +1458,31 @@ 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); } } /* 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."); } } } @@ -1472,7 +1555,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()); @@ -1485,7 +1575,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; @@ -1495,7 +1586,7 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l if (!exclusion) { FirstBuildChangelog firstBuildChangelog = getExtensions().get(FirstBuildChangelog.class); - if (firstBuildChangelog!=null&&firstBuildChangelog.isMakeChangelog()) { + if (firstBuildChangelog != null && firstBuildChangelog.isMakeChangelog()) { changelog.to(out).max(1).execute(); executed = true; listener.getLogger().println("First time build. Latest changes added to changelog."); @@ -1526,30 +1617,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); @@ -1573,20 +1664,21 @@ public void buildEnvironment(Run build, java.util.Map env) /* 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++; } } @@ -1597,11 +1689,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; @@ -1610,7 +1701,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) { @@ -1624,7 +1716,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) { @@ -1639,10 +1732,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); } @@ -1651,13 +1750,14 @@ public ChangeLogParser createChangeLogParser() { @Symbol({"scmGit", "gitSCM"}) // Cannot use "git" because there is already a `git` pipeline step public static final class DescriptorImpl extends SCMDescriptor { - @SuppressFBWarnings(value="UUF_UNUSED_FIELD", justification="Do not risk compatibility") + @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "Do not risk compatibility") private String gitExe; + private String globalConfigName; 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; @@ -1694,7 +1794,9 @@ public boolean isShowEntireCommitSummaryInChanges() { return showEntireCommitSummaryInChanges; } - public boolean isHideCredentials() { return hideCredentials; } + public boolean isHideCredentials() { + return hideCredentials; + } public void setHideCredentials(boolean hideCredentials) { this.hideCredentials = hideCredentials; @@ -1708,7 +1810,8 @@ public String getDisplayName() { return "Git"; } - @Override public boolean isApplicable(Job project) { + @Override + public boolean isApplicable(Job project) { return true; } @@ -1717,7 +1820,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; } /** @@ -1725,7 +1832,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); } @@ -1796,19 +1905,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 @@ -1819,9 +1938,8 @@ public String getOldGitExe() { return null; } - 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(); @@ -1844,7 +1962,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 { @@ -1855,9 +1974,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; @@ -1873,7 +1991,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()); @@ -1884,8 +2003,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; @@ -1898,8 +2016,7 @@ public FormValidation doGitRemoteNameCheck(StaplerRequest req) String[] names = req.getParameterValues("repo.name"); if (urls != null && names != null) for (String name : GitUtils.fixupNames(names, urls)) - if (name.equals(mergeRemoteName)) - return FormValidation.ok(); + if (name.equals(mergeRemoteName)) return FormValidation.ok(); return FormValidation.error("No remote repository configured with name '" + mergeRemoteName + "'"); } @@ -1915,26 +2032,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; @@ -1951,7 +2068,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(); @@ -1977,8 +2095,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; } } @@ -2006,12 +2124,11 @@ 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) - return new BuildData(scmName, getUserRemoteConfigs()); + if (base == null) return new BuildData(scmName, getUserRemoteConfigs()); else { - BuildData buildData = base.clone(); - buildData.setScmName(scmName); - return buildData; + BuildData buildData = base.clone(); + buildData.setScmName(scmName); + return buildData; } } @@ -2076,7 +2193,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; @@ -2084,7 +2203,7 @@ 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; } @@ -2097,48 +2216,52 @@ 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) - break; + 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. } } @@ -2153,8 +2276,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. @@ -2165,7 +2287,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); @@ -2176,11 +2298,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)); @@ -2193,11 +2316,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..240f23a336 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,75 @@ 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) - getExtensions().add(ext); + 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 +354,38 @@ 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 +395,7 @@ public UserMergeOptions getUserMergeOptions() { */ @Deprecated public boolean getClean() { - return getExtensions().get(CleanCheckout.class)!=null; + return getExtensions().get(CleanCheckout.class) != null; } /** @@ -405,7 +405,7 @@ public boolean getClean() { */ @Deprecated public boolean getWipeOutWorkspace() { - return getExtensions().get(WipeWorkspace.class)!=null; + return getExtensions().get(WipeWorkspace.class) != null; } /** @@ -416,7 +416,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 +427,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 +437,7 @@ public String getReference() { */ @Deprecated public boolean getRemotePoll() { - return getExtensions().get(DisableRemotePoll.class)==null; + return getExtensions().get(DisableRemotePoll.class) == null; } /** @@ -450,7 +450,7 @@ public boolean getRemotePoll() { */ @Deprecated public boolean getAuthorOrCommitter() { - return getExtensions().get(AuthorInChangelog.class)!=null; + return getExtensions().get(AuthorInChangelog.class) != null; } /** @@ -460,7 +460,7 @@ public boolean getAuthorOrCommitter() { */ @Deprecated public boolean isIgnoreNotifyCommit() { - return getExtensions().get(IgnoreNotifyCommit.class)!=null; + return getExtensions().get(IgnoreNotifyCommit.class) != null; } /** @@ -471,7 +471,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 +482,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 29e3b824cb..13070b0b11 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,16 +22,12 @@ 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.model.ParameterizedJobMixIn; 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.*; @@ -62,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; @@ -114,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"); @@ -128,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); @@ -154,8 +162,11 @@ 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])); } } @@ -204,14 +215,14 @@ 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; } @@ -228,8 +239,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. @@ -249,8 +259,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) {} } /** @@ -258,7 +267,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...)} @@ -298,7 +307,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); } @@ -317,15 +327,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); } - - } /** @@ -341,11 +350,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(); @@ -355,8 +367,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"); @@ -367,7 +378,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; } @@ -375,8 +387,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)) { @@ -386,28 +397,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; @@ -415,7 +432,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; @@ -426,19 +448,22 @@ public List onNotifyCommit(String origin, URIish uri, Strin } if (!branchFound) continue; urlFound = true; - if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob && ((ParameterizedJobMixIn.ParameterizedJob) project).isDisabled())) { - //JENKINS-30178 Add default parameters defined in the job + if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob + && ((ParameterizedJobMixIn.ParameterizedJob) project).isDisabled())) { + // 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); @@ -450,10 +475,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 @@ -461,23 +490,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; @@ -489,12 +521,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 { @@ -504,7 +536,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); @@ -633,7 +665,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]"); @@ -641,8 +674,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()); @@ -665,8 +698,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. @@ -684,8 +719,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; } @@ -712,5 +749,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 cc31924127..425a13959c 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 */ @@ -65,8 +64,7 @@ public boolean isTagged() { @Override public String getIconFileName() { - if (!isTagged() && !getACL().hasPermission(getPermission())) - return null; + if (!isTagged() && !getACL().hasPermission(getPermission())) return null; return "save.gif"; } @@ -76,16 +74,12 @@ public String getDisplayName() { for (List v : tags.values()) { if (!v.isEmpty()) { nonNullTag += v.size(); - if (nonNullTag > 1) - break; + if (nonNullTag > 1) break; } } - if (nonNullTag == 0) - return "No Tags"; - if (nonNullTag == 1) - return "One tag"; - else - return "Multiple tags"; + if (nonNullTag == 0) return "No Tags"; + if (nonNullTag == 1) return "One tag"; + else return "Multiple tags"; } /** @@ -101,8 +95,7 @@ public List getTagInfo() { List data = new ArrayList<>(); for (Map.Entry> e : tags.entrySet()) { String module = e.getKey(); - for (String tag : e.getValue()) - data.add(new TagInfo(module, tag)); + for (String tag : e.getValue()) data.add(new TagInfo(module, tag)); } return data; } @@ -188,16 +181,14 @@ void scheduleTagCreation(Map newTags, String comment) throws IOE public 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; } protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) throws IOException, InterruptedException { - return Git.with(listener, environment) - .in(workspace) - .getClient(); + return Git.with(listener, environment).in(workspace).getClient(); } @Override @@ -208,9 +199,8 @@ protected void perform(final TaskListener listener) throws Exception { 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(); @@ -219,8 +209,7 @@ protected void perform(final TaskListener listener) throws Exception { 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 @@ -230,7 +219,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..36d3deb898 100644 --- a/src/main/java/hudson/plugins/git/ObjectIdConverter.java +++ b/src/main/java/hudson/plugins/git/ObjectIdConverter.java @@ -30,43 +30,38 @@ public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return ObjectId.class == type; } - public void marshal(Object source, HierarchicalStreamWriter writer, - MarshallingContext context) { + 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)) - return legacyUnmarshal(reader, context); + 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 cf95e3eebb..774773f7e0 100644 --- a/src/main/java/hudson/plugins/git/RemoteConfigConverter.java +++ b/src/main/java/hudson/plugins/git/RemoteConfigConverter.java @@ -12,9 +12,6 @@ import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.transport.RemoteConfig; - import java.io.*; import java.net.URISyntaxException; import java.util.ArrayList; @@ -22,6 +19,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 @@ -32,8 +31,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"; @@ -67,23 +65,16 @@ public RemoteConfigProxy() { } public String getString(String section, String subsection, String name) { - if (KEY_UPLOADPACK.equals(name)) - return uploadpack; - if (KEY_RECEIVEPACK.equals(name)) - return receivepack; - if (KEY_TAGOPT.equals(name)) - return tagopt; + if (KEY_UPLOADPACK.equals(name)) return uploadpack; + if (KEY_RECEIVEPACK.equals(name)) return receivepack; + 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)) - return uris; - if (KEY_FETCH.equals(name)) - return fetch; - if (KEY_PUSH.equals(name)) - return push; + public String[] getStringList(String section, String subsection, String name) { + if (KEY_URL.equals(name)) return uris; + if (KEY_FETCH.equals(name)) return fetch; + if (KEY_PUSH.equals(name)) return push; return super.getStringList(section, subsection, name); } @@ -93,36 +84,32 @@ private void fromMap(Map> map) { Collection values = entry.getValue(); 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; + } } } - @SuppressFBWarnings(value="SE_PREVENT_EXT_OBJ_OVERWRITE", justification="Used during version upgrade") - public void readExternal(ObjectInput in) throws IOException, - ClassNotFoundException { + @SuppressFBWarnings(value = "SE_PREVENT_EXT_OBJ_OVERWRITE", justification = "Used during version upgrade") + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = in.readUTF(); final int items = in.readInt(); Map> map = new HashMap<>(); @@ -153,14 +140,13 @@ 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; } @@ -168,32 +154,29 @@ public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return RemoteConfig.class == type; } - public void marshal(Object source, HierarchicalStreamWriter writer, - MarshallingContext context) { + 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() { public Object readFromStream() { @@ -214,8 +197,7 @@ public void defaultReadObject() { throw new UnsupportedOperationException(); } - public void registerValidation(ObjectInputValidation validation, - int priority) throws NotActiveException { + public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException(); } @@ -225,8 +207,7 @@ public void close() { }; try { @SuppressWarnings("deprecation") - CustomObjectInputStream objectInput = CustomObjectInputStream - .getInstance(context, callback); + CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback); proxy.readExternal(objectInput); objectInput.popCallback(); return proxy.toRemote(); @@ -235,10 +216,8 @@ public void close() { } } - public Object unmarshal(final HierarchicalStreamReader reader, - final UnmarshallingContext context) { - if (isLegacyNode(reader, context)) - return legacyUnmarshal(reader, context); + 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..2fde7756e1 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,30 @@ 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} - */ + */ 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) - return false; + if (otherActions.size() != 0) return false; } else { - for (RevisionParameterAction action: otherActions) { - if(this.commit.equals(action.commit)) - return false; + 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 @@ -193,8 +188,8 @@ public boolean shouldSchedule(List actions) { */ 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..3f3fe7d1c3 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,20 @@ public String getRef() { } public MergeCommand.Strategy getMergeStrategy() { - for (MergeCommand.Strategy strategy: MergeCommand.Strategy.values()) - if (strategy.toString().equals(mergeStrategy)) - return strategy; + 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)) - return ffMode; + if (ffMode.equals(fastForwardMode)) return ffMode; return MergeCommand.GitPluginFastForwardMode.FF; } @@ -126,12 +131,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 +177,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 6f1dd6e33b..90b3ccd128 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 - .listCredentialsInItem(StandardUsernameCredentials.class, project, project instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) project) - : ACL.SYSTEM2, - GitURIRequirementsBuilder.fromUri(url).build(), - GitClient.CREDENTIALS_MATCHER)) { + for (ListBoxModel.Option o : CredentialsProvider.listCredentialsInItem( + StandardUsernameCredentials.class, + project, + project instanceof Queue.Task ? Tasks.getAuthenticationOf2((Queue.Task) project) : ACL.SYSTEM2, + 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,20 +164,21 @@ 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) - return FormValidation.error(Messages.UserRemoteConfig_CheckUrl_UrlIsNull()); + if (url == null) return FormValidation.error(Messages.UserRemoteConfig_CheckUrl_UrlIsNull()); if (url.indexOf('$') >= 0) // set by variable, can't validate @@ -226,18 +224,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 +245,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 +255,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.lookupCredentialsInItem(StandardCredentials.class, project, ACL.SYSTEM2, - 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.lookupCredentialsInItem( + StandardCredentials.class, + project, + ACL.SYSTEM2, + 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 243df70372..7f1025086c 100644 --- a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java +++ b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -11,21 +13,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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 @@ -96,19 +95,20 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public AssemblaWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 @@ -129,7 +129,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 421c642305..d49f06c27f 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java @@ -1,20 +1,19 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser URLs for on-premise Bitbucket Server installation. */ @@ -43,14 +42,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(); @@ -71,7 +71,8 @@ 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> { @NonNull public String getDisplayName() { @@ -79,8 +80,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public BitbucketServer newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 d43cad8861..d980140acc 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java @@ -1,20 +1,19 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser URLs */ @@ -43,14 +42,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(); @@ -80,11 +80,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public BitbucketWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 52c31f32a0..6492bb785e 100644 --- a/src/main/java/hudson/plugins/git/browser/CGit.java +++ b/src/main/java/hudson/plugins/git/browser/CGit.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -7,16 +9,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser URLs */ @@ -59,7 +58,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())); } /** @@ -75,9 +75,12 @@ 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()))); } } @@ -90,8 +93,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public CGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 e81322bc6b..f3b6429342 100644 --- a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -8,121 +10,115 @@ 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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 - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { - 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> { + + @NonNull + public String getDisplayName() { + return "FishEye"; + } + + @Override + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) + throws FormException { + 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 7e2c616ae8..1195ebdc7d 100644 --- a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -11,22 +13,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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 { @@ -43,8 +42,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())); } @@ -54,22 +57,27 @@ 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"); } @@ -82,23 +90,24 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) + throws FormException { 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() { diff --git a/src/main/java/hudson/plugins/git/browser/GitLab.java b/src/main/java/hudson/plugins/git/browser/GitLab.java index 3ffc881127..a3c5d1ad6e 100644 --- a/src/main/java/hudson/plugins/git/browser/GitLab.java +++ b/src/main/java/hudson/plugins/git/browser/GitLab.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -7,21 +9,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import javax.servlet.ServletException; - import org.kohsuke.stapler.QueryParameter; +import org.kohsuke.stapler.StaplerRequest; /** * Git Browser for GitLab @@ -143,8 +139,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitLab newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { return req.bindJSON(GitLab.class, jsonObject); } @@ -172,11 +169,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 4648f56ffd..7980e46470 100644 --- a/src/main/java/hudson/plugins/git/browser/GitList.java +++ b/src/main/java/hudson/plugins/git/browser/GitList.java @@ -1,22 +1,20 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser URLs */ @@ -45,8 +43,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); @@ -60,7 +60,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))); } @@ -92,8 +92,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitList newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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..66d63d350c 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> { @@ -70,18 +65,20 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Gitiles newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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)) { @@ -90,8 +87,7 @@ public FormValidation doCheckRepoUrl(@AncestorInPath Item project, @QueryParamet return new URLCheck() { protected FormValidation check() throws IOException, ServletException { String v = cleanUrl; - if (!v.endsWith("/")) - v += '/'; + 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 b9faa07be4..36f579d664 100644 --- a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java +++ b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java @@ -1,20 +1,19 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser for Gitorious */ @@ -34,9 +33,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 @@ -44,13 +43,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 @@ -74,11 +74,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitoriousWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 0e5f31008a..238854214f 100644 --- a/src/main/java/hudson/plugins/git/browser/GogsGit.java +++ b/src/main/java/hudson/plugins/git/browser/GogsGit.java @@ -1,22 +1,20 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * @author Norbert Lange (nolange79@gmail.com) */ @@ -53,7 +51,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; } @@ -87,7 +87,8 @@ 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())); } } @@ -100,8 +101,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GogsGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 53d879c13d..7fbb9cc40e 100644 --- a/src/main/java/hudson/plugins/git/browser/KilnGit.java +++ b/src/main/java/hudson/plugins/git/browser/KilnGit.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -7,17 +9,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * @author Chris Klaiber (cklaiber@gmail.com) */ @@ -58,7 +56,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; } @@ -98,7 +98,9 @@ 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()))); } } @@ -111,8 +113,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public KilnGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 fd18751715..00e4858ff2 100644 --- a/src/main/java/hudson/plugins/git/browser/Phabricator.java +++ b/src/main/java/hudson/plugins/git/browser/Phabricator.java @@ -1,20 +1,19 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser for Phabricator */ @@ -90,8 +89,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Phabricator newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 5820fac961..d334cceab2 100644 --- a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java +++ b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java @@ -1,24 +1,23 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Git Browser for Redmine. - * + * * @author mfriedenhagen */ public class RedmineWeb extends GitRepositoryBrowser { @@ -38,13 +37,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 @@ -68,7 +67,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 @@ -93,11 +92,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public RedmineWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 73356106d6..9c8840a27d 100644 --- a/src/main/java/hudson/plugins/git/browser/RhodeCode.java +++ b/src/main/java/hudson/plugins/git/browser/RhodeCode.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -7,16 +9,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * RhodeCode Browser URLs */ @@ -59,7 +58,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"); } /** @@ -95,8 +98,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public RhodeCode newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 b4fa048690..aacc5bdee8 100644 --- a/src/main/java/hudson/plugins/git/browser/Stash.java +++ b/src/main/java/hudson/plugins/git/browser/Stash.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -7,15 +9,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; -import java.net.URL; - /** * Stash Browser URLs */ @@ -60,9 +59,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())); } } @@ -80,14 +87,18 @@ 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> { @NonNull public String getDisplayName() { @@ -95,8 +106,9 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Stash newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 a76a8e51d3..d203f12f84 100644 --- a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.AbstractProject; @@ -8,23 +10,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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 @@ -39,13 +38,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)); } @@ -56,12 +57,10 @@ 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("/")) - return normalizeToEndWithSlash(getResultFromNamedRepository(changeSet)); + else if (!result.contains("/")) return normalizeToEndWithSlash(getResultFromNamedRepository(changeSet)); return getUrl(); } @@ -77,7 +76,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(); } @@ -86,16 +86,20 @@ 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"; + @NonNull public String getDisplayName() { return REPOSITORY_BROWSER_LABEL; } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) + throws FormException { try { req.getSubmittedForm(); } catch (ServletException e) { @@ -113,27 +117,27 @@ 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)) - return FormValidation.ok(); + if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) return FormValidation.ok(); if (value == null) // nothing entered yet - value = "origin"; + 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) + ""); - + return FormValidation.errorWithMarkup( + "There is no remote with the name " + Util.escape(value) + ""); + value = remote.getURIs().get(0).toString(); } - - if (!value.endsWith("/")) - value += '/'; + + if (!value.endsWith("/")) value += '/'; if (!URL_PATTERN.matcher(value).matches()) return FormValidation.errorWithMarkup("The URL should end like .../_git/foobar/"); @@ -145,7 +149,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 af62841ad1..dcd778be74 100644 --- a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java +++ b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java @@ -1,5 +1,7 @@ package hudson.plugins.git.browser; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -12,22 +14,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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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 { @@ -46,7 +45,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; } @@ -58,18 +57,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) { @@ -89,28 +100,28 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings( + value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public ViewGitWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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)) - return FormValidation.ok(); + if (initialChecksAndReturnOk(project, cleanUrl)) return FormValidation.ok(); if (!validateUrl(cleanUrl)) { return FormValidation.error(Messages.invalidUrl()); } return new URLCheck() { protected FormValidation check() throws IOException, ServletException { String v = cleanUrl; - if (!v.endsWith("/")) - v += '/'; + 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..930eb05407 100644 --- a/src/main/java/hudson/plugins/git/extensions/GitClientType.java +++ b/src/main/java/hudson/plugins/git/extensions/GitClientType.java @@ -1,8 +1,8 @@ package hudson.plugins.git.extensions; /** -* @author Nicolas De Loof -*/ + * @author Nicolas De Loof + */ public enum GitClientType { JGIT { @Override @@ -10,13 +10,15 @@ public GitClientType combine(GitClientType c) throws 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(); 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..e1852b296d 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,7 @@ public BuildChooserSetting(BuildChooser buildChooser) { } public BuildChooser getBuildChooser() { - if (buildChooser==null) - buildChooser = new DefaultBuildChooser(); + 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 7f28763c76..9162c8400d 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. @@ -41,7 +41,9 @@ public Integer getTimeout() { * {@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); } @@ -55,7 +57,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); } @@ -89,9 +93,7 @@ public int hashCode() { */ @Override public String toString() { - return "CheckoutOption{" + - "timeout=" + timeout + - '}'; + return "CheckoutOption{" + "timeout=" + timeout + '}'; } @Extension @@ -106,5 +108,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..12dfa45b3f 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,12 @@ private String[] normalize(String s) { } private List getIncludedPatterns() { - if (includedPatterns==null) - includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized()); + if (includedPatterns == null) includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized()); return includedPatterns; } private List getExcludedPatterns() { - if (excludedPatterns==null) - excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized()); + if (excludedPatterns == null) excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized()); return excludedPatterns; } @@ -93,11 +90,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 +133,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..e7505c5aaa 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,7 @@ 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 +53,48 @@ 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)) - return rev; + 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); + 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()) - ext.decorateMergeCommand(scm, build, git, listener, cmd); + 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); + 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 +102,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 +119,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 +176,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..a5ccf4012e 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; @@ -62,14 +64,15 @@ public String apply(@NonNull SparseCheckoutPath sparseCheckoutPath) { } } - public Descriptor getDescriptor() - { + 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..96b6a9c39b 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,13 @@ 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 798aba91d7..0b7801fe80 100644 --- a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java +++ b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java @@ -1,13 +1,12 @@ package hudson.plugins.git.opt; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.) * @@ -20,26 +19,22 @@ public class PreBuildMergeOptions implements Serializable { /** * Remote repository that contains the {@linkplain #mergeTarget ref}. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public RemoteConfig mergeRemote = null; /** * Remote ref to merge. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public String mergeTarget = null; /** * Merge strategy. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public String mergeStrategy = MergeCommand.Strategy.DEFAULT.toString(); - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public MergeCommand.GitPluginFastForwardMode fastForwardMode = MergeCommand.GitPluginFastForwardMode.FF; public RemoteConfig getMergeRemote() { @@ -61,9 +56,8 @@ public void setMergeTarget(String mergeTarget) { @Exported public MergeCommand.Strategy getMergeStrategy() { - for (MergeCommand.Strategy strategy: MergeCommand.Strategy.values()) - if (strategy.toString().equals(mergeStrategy)) - return strategy; + for (MergeCommand.Strategy strategy : MergeCommand.Strategy.values()) + if (strategy.toString().equals(mergeStrategy)) return strategy; return MergeCommand.Strategy.DEFAULT; } @@ -74,13 +68,12 @@ public void setMergeStrategy(MergeCommand.Strategy mergeStrategy) { @Exported public MergeCommand.GitPluginFastForwardMode getFastForwardMode() { for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values()) - if (ffMode == fastForwardMode) - return ffMode; + 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..e1e0e4db47 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,62 @@ public Collection getCandidateRevisions(boolean isPollCall, String bra .filter(IOException.class::isInstance) .map(IOException.class::cast) .iterator(); - if (ioeIter.hasNext()) - throw ioeIter.next(); - else - throw Throwables.propagate(e); + if (ioeIter.hasNext()) throw ioeIter.next(); + 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 +159,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 4a17cb71ae..72c44841e5 100644 --- a/src/main/java/hudson/plugins/git/util/Build.java +++ b/src/main/java/hudson/plugins/git/util/Build.java @@ -4,13 +4,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}. @@ -39,8 +38,7 @@ public class Build implements Serializable, Cloneable { * to the same value as {@link #revision}, as we want to be able to build two pull requests rooted at the same * commit in the base repository. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public Revision marked; /** @@ -51,8 +49,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. @@ -64,7 +62,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() { @@ -121,15 +119,12 @@ 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) - clone.revision = revision.clone(); - if (marked != null) - clone.marked = marked.clone(); + if (revision != null) clone.revision = revision.clone(); + if (marked != null) clone.marked = marked.clone(); return clone; } @@ -138,8 +133,8 @@ public boolean isFor(String sha1) { } public Object readResolve() throws IOException { - if (marked==null) // this field was introduced later than 'revision' - marked = 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..4a600c9c29 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,8 +238,10 @@ 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); } /** @@ -232,16 +249,15 @@ public Build prevBuildForChangelog(String branch, @Nullable BuildData data, huds * @return build chooser descriptor */ 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 +268,8 @@ public static DescriptorExtensionList all() */ public static List allApplicableTo(Item item) { List result = new ArrayList<>(); - for (BuildChooserDescriptor d: all()) { - if (d.isApplicable(item.getClass())) - result.add(d); + for (BuildChooserDescriptor d : all()) { + if (d.isApplicable(item.getClass())) result.add(d); } return result; } @@ -276,7 +291,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 ba4cb6d783..066da06715 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.model.AbstractBuild; @@ -10,6 +12,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; @@ -17,6 +21,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; @@ -25,11 +31,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. * @@ -48,29 +49,25 @@ public class BuildData implements Action, Serializable, Cloneable { * This map contains all the branches we've built in the past (including the build that this {@link BuildData} * is attached to) */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public Map buildsByBranchName = new HashMap<>(); /** * The last build that we did (among the values in {@link #buildsByBranchName}.) */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public Build lastBuild; /** * The name of the SCM as given by the user. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public String scmName; /** * The URLs that have been referenced. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", - justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") public Set remoteUrls = new HashSet<>(); /** @@ -79,8 +76,7 @@ public class BuildData implements Action, Serializable, Cloneable { @CheckForNull private Integer index; - public BuildData() { - } + public BuildData() {} public BuildData(String scmName) { this.scmName = scmName; @@ -88,7 +84,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()); } } @@ -104,8 +100,7 @@ public BuildData(String scmName, Collection remoteConfigs) { */ @Override public String getDisplayName() { - if (scmName != null && !scmName.isEmpty()) - return "Git Build Data:" + scmName; + if (scmName != null && !scmName.isEmpty()) return "Git Build Data:" + scmName; return "Git Build Data"; } @@ -116,7 +111,7 @@ public String getIconFileName() { @Override public String getUrlName() { - return index == null ? "git" : "git-"+index; + return index == null ? "git" : "git-" + index; } /** @@ -140,7 +135,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; @@ -149,7 +144,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()); @@ -159,8 +154,7 @@ public Object readResolve() { this.buildsByBranchName = newBuildsByBranchName; - if(this.remoteUrls == null) - this.remoteUrls = new HashSet<>(); + if (this.remoteUrls == null) this.remoteUrls = new HashSet<>(); return this; } @@ -172,7 +166,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) { @@ -186,11 +180,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"); @@ -202,11 +201,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"); @@ -239,11 +242,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); } } @@ -259,24 +262,21 @@ 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) - scmName = ""; + public String getScmName() { + if (scmName == null) scmName = ""; return scmName; } @@ -285,7 +285,7 @@ public void addRemoteUrl(String remoteUrl) { } @Exported - public Set getRemoteUrls() { + public Set getRemoteUrls() { return remoteUrls; } @@ -298,8 +298,7 @@ public BuildData clone() { BuildData clone; try { clone = (BuildData) super.clone(); - } - catch (CloneNotSupportedException e) { + } catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning BuildData", e); } @@ -330,8 +329,7 @@ public BuildData clone() { } } - for(String remoteUrl : getRemoteUrls()) - { + for (String remoteUrl : getRemoteUrls()) { clone.addRemoteUrl(remoteUrl); } @@ -345,10 +343,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 + "]"; } /** @@ -401,11 +399,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..897b0760c4 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; @@ -45,7 +46,7 @@ public CommitTimeComparator(Repository r) { } 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 +54,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..4e83b47a9c 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,26 @@ 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); + 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 +68,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 +99,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 +133,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 +180,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 +192,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 +211,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 +238,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 +258,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 +279,7 @@ 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..3a143c9ad0 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,8 @@ 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)) - return revision; + for (Revision revision : getAllBranchRevisions()) { + if (revision.getSha1().equals(sha1)) return revision; } return new Revision(sha1); } @@ -174,11 +177,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 +212,7 @@ 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) - return l; + if (l.size() <= 1) return l; try { return git.withRepository((Repository repo, VirtualChannel channel) -> { @@ -224,9 +227,7 @@ 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); @@ -259,8 +260,8 @@ public List filterTipBranches(final Collection revisions) th 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 +271,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 +287,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 +321,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 +331,22 @@ 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) - env.put("WORKSPACE", ws.getRemote()); + 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 +372,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 +388,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 aa08eb197c..14dfcaa14d 100644 --- a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java @@ -151,7 +151,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. * @@ -167,9 +168,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); @@ -323,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); @@ -394,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 { @@ -417,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(); @@ -484,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..."); @@ -497,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; } @@ -547,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; } @@ -588,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; + 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(); } - 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; - } - 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; } - )) { - listener.getLogger().format("Processed %d tags (query complete)%n", count); - return; + 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%n", count); } - } - listener.getLogger().format("Processed %d tags%n", count); - } - }, context, listener, true, true); + }, + context, + listener, + true, + true); } /** @@ -817,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()); @@ -860,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; @@ -870,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)) { @@ -882,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; @@ -894,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); @@ -902,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; @@ -914,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; @@ -945,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); @@ -966,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); } /** @@ -1050,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()); @@ -1088,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)) { @@ -1102,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) { @@ -1209,11 +1263,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()); @@ -1253,7 +1308,8 @@ protected static File getCacheDir(String cacheEntry, boolean createDirectory) { return null; } String cacheRootDir = SystemProperties.getString(AbstractGitSCMSource.class.getName() + ".cacheRootDir"); - File cacheDir = new File(cacheRootDir != null ? new File(cacheRootDir) : new File(jenkins.getRootDir(), "caches"), cacheEntry); + File cacheDir = new File( + cacheRootDir != null ? new File(cacheRootDir) : new File(jenkins.getRootDir(), "caches"), cacheEntry); if (!cacheDir.isDirectory()) { if (createDirectory) { boolean ok = cacheDir.mkdirs(); @@ -1286,12 +1342,13 @@ private StandardUsernameCredentials getCredentials(@CheckForNull Item context) { if (credentialsId == null) { return null; } - return CredentialsMatchers - .firstOrNull( - CredentialsProvider.lookupCredentialsInItem(StandardUsernameCredentials.class, context, - ACL.SYSTEM2, URIRequirementBuilder.fromUri(getRemote()).build()), - CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), - GitClient.CREDENTIALS_MATCHER)); + return CredentialsMatchers.firstOrNull( + CredentialsProvider.lookupCredentialsInItem( + StandardUsernameCredentials.class, + context, + ACL.SYSTEM2, + URIRequirementBuilder.fromUri(getRemote()).build()), + CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); } /** @@ -1326,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} @@ -1347,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); @@ -1373,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} @@ -1384,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) { @@ -1451,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()); } /** @@ -1470,7 +1526,6 @@ public int hashCode() { public String toString() { return hash; } - } public static class SpecificRevisionBuildChooser extends BuildChooser { @@ -1487,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); } @@ -1498,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; } - } /** @@ -1511,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; @@ -1630,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 7e146bc563..217a2f9e44 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.lookupCredentialsInItem( - StandardUsernameCredentials.class, - owner, - ACL.SYSTEM2, - URIRequirementBuilder.fromUri(remote).build() - ), + StandardUsernameCredentials.class, + owner, + ACL.SYSTEM2, + 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..52fd6279c2 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,7 @@ public static Set populateCandidatesFromRootBuild(AbstractBuild build, BuildData parentBuildData = scm.getBuildData(parentBuild); if (parentBuildData != null) { Build lastBuild = parentBuildData.lastBuild; - if (lastBuild != null) - return Collections.singleton(lastBuild.getMarked()); + 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 894ae2b7f9..94f8cbb2c0 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 @@ -170,7 +170,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 +203,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 +235,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 +277,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 +306,6 @@ public boolean isIgnoreOnPushNotifications() { return SCMTrait.find(traits, IgnoreOnPushNotificationTrait.class) != null; } - // For Stapler only @Restricted(DoNotUse.class) @DataBoundSetter @@ -332,13 +351,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); @@ -373,8 +397,8 @@ public String getRawRefSpecs() { 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 +419,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 +439,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 +458,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 +480,7 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item context, for (ListBoxModel.Option o : CredentialsProvider.listCredentialsInItem( StandardUsernameCredentials.class, context, - context instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) context) - : ACL.SYSTEM2, + context instanceof Queue.Task ? Tasks.getAuthenticationOf2((Queue.Task) context) : ACL.SYSTEM2, URIRequirementBuilder.fromUri(remote).build(), GitClient.CREDENTIALS_MATCHER)) { if (Objects.equals(value, o.value)) { @@ -475,7 +499,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,12 +534,14 @@ 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; } @@ -527,18 +553,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 +574,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 +592,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 +618,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 +633,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 +656,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 +676,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 +695,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 9862c34d92..0cd28ce494 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 - .lookupCredentialsInItem(StandardUsernameCredentials.class, owner, - owner instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) owner) - : ACL.SYSTEM2, URIRequirementBuilder.fromUri(remote).build()); + List urlCredentials = CredentialsProvider.lookupCredentialsInItem( + StandardUsernameCredentials.class, + owner, + owner instanceof Queue.Task + ? Tasks.getAuthenticationOf2((Queue.Task) owner) + : ACL.SYSTEM2, + 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 faf8c043fb..97cba663c9 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 */ @@ -271,12 +282,16 @@ private void assignSizeToInternalCache(String repoURL, long repoSize) { repoURL = convertToCanonicalURL(repoURL); Long oldSize = repositorySizeCache.put(repoURL, repoSize); if (oldSize == null) { - 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}); } else if (oldSize < repoSize) { - LOGGER.log(Level.FINE, "Replaced old repo size {0} with new size {1} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); + LOGGER.log(Level.FINE, "Replaced old repo size {0} with new size {1} for repo {2}", new Object[] { + oldSize, repoSize, repoURL + }); } else if (oldSize > repoSize) { /* Put back the larger old repo size and log a warning. This is not harmful but should be quite rare */ - LOGGER.log(Level.WARNING, "Ignoring new repo size {1} in favor of old size {0} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); + LOGGER.log(Level.WARNING, "Ignoring new repo size {1} in favor of old size {0} for repo {2}", new Object[] { + oldSize, repoSize, repoURL + }); repositorySizeCache.put(repoURL, oldSize); } } @@ -287,14 +302,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; @@ -349,10 +363,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); } } @@ -363,13 +377,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()); } @@ -402,7 +418,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 a0ee7e3161..2a0955794e 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..1c8157e02d 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) @@ -16,7 +15,7 @@ public class MatrixGitPublisher implements MatrixAggregatable { * For a matrix project, push should only happen once. */ 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/test/java/hudson/plugins/git/AbstractGitProject.java b/src/test/java/hudson/plugins/git/AbstractGitProject.java index 0800d8749a..aa9e1b1232 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 r = 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 = r.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 = r.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 = r.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 630693a25f..95f3ed1441 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitRepository.java +++ b/src/test/java/hudson/plugins/git/AbstractGitRepository.java @@ -1,25 +1,20 @@ package hudson.plugins.git; +import hudson.model.TaskListener; +import hudson.plugins.git.util.GitUtilsTest; +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 hudson.plugins.git.util.GitUtilsTest; -import org.eclipse.jgit.util.SystemReader; -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.eclipse.jgit.util.SystemReader; 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 @@ -44,7 +39,9 @@ public void createGitRepository() throws Exception { TaskListener listener = StreamTaskListener.fromStderr(); repo.init(); testGitDir = repo.getRoot(); - testGitClient = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()).in(testGitDir).getClient(); + testGitClient = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()) + .in(testGitDir) + .getClient(); } /** @@ -81,6 +78,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 bcb83147cb..cf3c0b3592 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,145 @@ 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) - scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); - if (excludedUsers!=null) - scm.getExtensions().add(new UserExclusion(excludedUsers)); - if (excludedRegions!=null || includedRegions!=null) - scm.getExtensions().add(new PathRestriction(includedRegions,excludedRegions)); + if (relativeTargetDir != null) scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); + if (excludedUsers != null) scm.getExtensions().add(new UserExclusion(excludedUsers)); + if (excludedRegions != null || includedRegions != null) + scm.getExtensions().add(new PathRestriction(includedRegions, excludedRegions)); scm.getExtensions().add(new SparseCheckoutPaths(sparseCheckoutPaths)); @@ -218,95 +278,109 @@ 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) { r.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) { r.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) { r.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); - } + 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 +405,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 5e198345db..adfc096d4e 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']]]", @@ -243,7 +245,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']", }; @@ -286,10 +293,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); } @@ -306,10 +315,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); } @@ -322,10 +333,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); } @@ -341,7 +354,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 408310628a..6824c8cc1a 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..647fe2fb1c 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,41 +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 +128,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 +158,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 +184,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 af3a8614a2..e58feae7ee 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 9570d87cef..f8cfd0caf4 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"); @@ -144,7 +151,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; gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java index d498e8b278..4a61dc17a4 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,53 @@ 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 005e0288a2..3d120c0667 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()); r.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 r.jenkins.setLabelString("master"); - r.jenkins.setNumExecutors(3); //In case this changes in the future as well. + r.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 = r.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 = r.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 = r.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 = r.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 = r.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 = r.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 = r.buildAndAssertSuccess(job); r.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 e0fd8fd508..1793249716 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.EnvVars; import hudson.FilePath; import hudson.Launcher; @@ -41,14 +50,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.jenkinsci.plugins.gitclient.UnsupportedCommand; -import org.jvnet.hudson.test.Issue; - import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -57,29 +58,26 @@ 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.jenkinsci.plugins.gitclient.UnsupportedCommand; 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 { @@ -102,32 +100,39 @@ public void testMatrixBuild() throws Exception { commitNewFile("a"); MatrixProject mp = r.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 TestGitPublisher( - 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 TestGitPublisher( + 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 = r.buildAndAssertSuccess(mp); @@ -136,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 @@ -151,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new TestGitPublisher( + 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"); @@ -176,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 */ @@ -195,45 +202,53 @@ 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() r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); MatrixProject mp = r.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 TestGitPublisher( - 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 TestGitPublisher( + 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 = r.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")); } @@ -243,19 +258,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new TestGitPublisher( + 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"); @@ -270,7 +285,6 @@ public void testMergeAndPush() throws Exception { String sha1 = getHeadRevision(build1, "integration"); assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); - } @Issue("JENKINS-12402") @@ -279,19 +293,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new TestGitPublisher( + 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"); @@ -299,7 +315,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"); @@ -320,12 +339,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 @@ -352,9 +371,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") @@ -363,19 +384,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new TestGitPublisher( + 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"); @@ -383,7 +406,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 @@ -408,9 +434,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"); @@ -436,13 +463,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") @@ -451,19 +483,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, true, false)); + project.getPublishersList() + .add(new TestGitPublisher( + 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"); @@ -471,7 +505,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 @@ -491,15 +528,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 @@ -518,49 +557,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 TestGitPublisher( - 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 TestGitPublisher( + 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"); @@ -571,18 +632,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); @@ -590,7 +651,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 @@ -615,10 +678,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"); @@ -637,16 +704,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); @@ -660,47 +733,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 TestGitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, + true, + false)); - project.getPublishersList().add(new TestGitPublisher( - 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 @@ -710,7 +787,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); @@ -718,10 +796,7 @@ public void testRebaseBeforePush() throws Exception { btp.setRebaseBeforePush(true); GitPublisher rebasedPublisher = new TestGitPublisher( - 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)); @@ -741,7 +816,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,12 +824,12 @@ public void testRebaseBeforePush() throws Exception { @Test public void testMergeAndPushWithCharacteristicEnvVar() throws Exception { // jgit doesn't work because of missing PerBuildTag - //GitTool tool = new JGitTool(Collections.emptyList()); - //r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); + // GitTool tool = new JGitTool(Collections.emptyList()); + // r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); 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 @@ -793,14 +867,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; @@ -808,7 +880,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()); @@ -834,7 +908,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"; @@ -850,12 +926,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); - } /** @@ -886,8 +963,8 @@ protected GitClient getGitClient( gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); return gitClient; } - } - + } + private boolean existsTag(String tag) throws InterruptedException { return existsTagInRepo(testGitClient, tag); } @@ -914,7 +991,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 == ';'; } } @@ -927,9 +1004,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. @@ -942,7 +1021,4 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen return true; } - - - } 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 2e2c9ac384..4715ac84d3 100644 --- a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java @@ -1,5 +1,14 @@ 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.assumeFalse; +import static org.junit.Assume.assumeTrue; + import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; @@ -33,16 +42,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.assumeFalse; -import static org.junit.Assume.assumeTrue; - import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.storage.file.UserConfigFile; import org.eclipse.jgit.util.FS; @@ -86,12 +85,14 @@ public static void gpgsignCheck() throws Exception { } UserConfigFile userConfig = new UserConfigFile(null, userGitConfig, xdgGitConfig, FS.DETECTED); userConfig.load(); - gpgsignEnabled = userConfig.getBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false) || - userConfig.getBoolean(ConfigConstants.CONFIG_TAG_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false); + gpgsignEnabled = userConfig.getBoolean( + ConfigConstants.CONFIG_COMMIT_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false) + || userConfig.getBoolean(ConfigConstants.CONFIG_TAG_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false); } @ClassRule public static Stopwatch stopwatch = new Stopwatch(); + @Rule public TestName testName = new TestName(); @@ -131,9 +132,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); r.configRoundtrip(p); r.assertEqualDataBoundBeans(scm, p.getScm()); @@ -162,9 +162,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 */ @@ -249,7 +248,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(); @@ -270,7 +270,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); @@ -287,16 +288,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()); r.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 @@ -308,7 +315,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 TestPreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); @@ -325,7 +333,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"); @@ -333,11 +343,15 @@ 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()); r.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()); } /** @@ -372,14 +386,15 @@ public void testMergeWithMatrixBuild() throws Exception { * without issue. */ assumeFalse("gpgsign enabled", gpgsignEnabled); - //Create a matrix project and a couple of axes + // Create a matrix project and a couple of axes MatrixProject project = r.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); @@ -396,7 +411,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"); @@ -404,11 +421,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()); r.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 @@ -492,19 +513,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()); r.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 7efada4462..bbf4a22e38 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; @@ -7,8 +22,6 @@ import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; -import org.htmlunit.html.HtmlPage; - import hudson.EnvVars; import hudson.FilePath; import hudson.Functions; @@ -34,26 +47,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 +56,42 @@ 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.htmlunit.html.HtmlPage; +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"; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.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()); r.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()); r.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()); r.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()); r.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()); r.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"; @@ -1219,21 +1311,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()); } /* @@ -1322,15 +1426,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()); @@ -1341,36 +1451,46 @@ public void testBasicExcludedUser() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.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()); r.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") @@ -1388,19 +1508,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()); r.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 @@ -1414,21 +1540,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 @@ -1436,28 +1570,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 @@ -1470,12 +1612,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) { @@ -1520,7 +1664,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); @@ -1546,15 +1692,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"); @@ -1563,9 +1711,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); @@ -1573,17 +1725,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()); } /* @@ -1607,9 +1766,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); @@ -1619,17 +1782,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: @@ -1653,7 +1819,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()); @@ -1674,9 +1840,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"); @@ -1691,32 +1858,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())); r.jenkins.rebuildDependencyGraph(); - FreeStyleBuild ub = r.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 - Thread.sleep(100); + for (int i = 0; + (d.getLastBuild() == null || d.getLastBuild().isBuilding()) && i < 100; + i++) // wait only up to 10 sec to avoid infinite loop + Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); - assertNotNull("downstream build didn't happen",db); + assertNotNull("downstream build didn't happen", db); db = r.waitForCompletion(db); r.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())); } } @@ -1727,9 +1893,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(); @@ -1756,10 +1923,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()); @@ -1772,23 +1937,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(); @@ -1800,7 +1972,7 @@ public void testEmailCommitter() throws Exception { r.assertBuildStatusSuccess(build); } - + @Issue("JENKINS-59868") @Test public void testNonExistentWorkingDirectoryPoll() throws Exception { @@ -1811,9 +1983,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); @@ -1829,10 +2002,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 @@ -1847,10 +2023,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"; @@ -1861,17 +2034,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()); r.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 { @@ -1887,10 +2066,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); r.assertBuildStatusSuccess(build); @@ -1926,14 +2102,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"); @@ -1944,10 +2124,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)); } @@ -1971,9 +2153,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 GitSCMSlowTest.TestPreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions() + .add(new GitSCMSlowTest.TestPreBuildMerge(new UserMergeOptions( + "origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); @@ -1988,7 +2173,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"); @@ -1996,11 +2183,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()); r.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") @@ -2012,9 +2203,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); @@ -2036,7 +2230,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 @@ -2047,10 +2244,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: @@ -2064,56 +2264,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()); r.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"); @@ -2134,8 +2347,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", ""); } } @@ -2145,7 +2359,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) r.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); + FreeStyleProject p = (FreeStyleProject) + r.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); @@ -2174,46 +2389,65 @@ public void testCheckoutReturnsLatestValues() throws Exception { WorkflowJob p = r.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 = r.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_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, "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; @@ -2222,7 +2456,7 @@ private String getLineStartsWith(String text, String startOfLine) { } return ""; } - + @Test public void testPleaseDontContinueAnyway() throws Exception { /* Wastes time waiting for the build to fail */ @@ -2233,7 +2467,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())); @@ -2256,22 +2490,24 @@ public void testCheckoutToSpecificBranch() throws Exception { p.setScm(oldGit); FreeStyleBuild b = r.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
      * 
@@ -2279,24 +2515,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
      * 
@@ -2304,17 +2540,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)); } /* @@ -2323,33 +2559,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)); } /* @@ -2358,15 +2594,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()); @@ -2408,7 +2645,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()); @@ -2441,7 +2680,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 @@ -2453,7 +2691,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"))); @@ -2464,17 +2703,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 @@ -2482,7 +2720,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); @@ -2492,7 +2730,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") @@ -2517,21 +2755,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(); r.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); @@ -2542,10 +2783,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; @@ -2575,37 +2817,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(); r.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 @@ -2616,7 +2860,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); @@ -2631,7 +2876,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(); r.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); @@ -2651,8 +2897,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); @@ -2661,9 +2913,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()); @@ -2671,15 +2928,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 @@ -2722,129 +2979,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 - - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + EnvVars env = new EnvVars(); + scm.buildEnvVars(build, env); // NPE here before fix applied - /* Verify mocks were called as expected */ - verify(buildData, times(1)).getLastBuiltRevision(); - verify(buildData, times(1)).hasBeenReferenced(anyString()); - verify(build, times(1)).getActions(BuildData.class); + 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); } @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 @@ -2917,7 +3174,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); @@ -2941,7 +3199,7 @@ public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); - Run run = r.buildAndAssertSuccess(p); + Run run = r.buildAndAssertSuccess(p); r.waitForMessage("Commit message: \"test commit\"", run); } @@ -2955,18 +3213,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)); } @@ -2982,14 +3246,16 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); - final String notificationPath = r.getURL().toExternalForm() - + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; + final String notificationPath = + r.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) && (r.jenkins.getQueue().isEmpty())) { @@ -3007,8 +3273,10 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws } private void setupJGit(GitSCM git) { - git.gitTool="jgit"; - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.emptyList())); + git.gitTool = "jgit"; + r.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 :). */ @@ -3033,7 +3301,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/GitStatusSimpleTest.java b/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java index 298490ea05..7eded3470a 100644 --- a/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java @@ -2,9 +2,9 @@ import static org.junit.Assert.*; -import org.eclipse.jgit.transport.URIish; import java.util.ArrayList; import java.util.List; +import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/hudson/plugins/git/GitStatusTest.java b/src/test/java/hudson/plugins/git/GitStatusTest.java index 74561ba0ce..2b19594e6d 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; @@ -17,26 +21,19 @@ import hudson.util.RunList; import java.io.File; 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.junit.After; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; - -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 { @@ -59,7 +56,8 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (r.jenkins != null) { - this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -99,7 +97,8 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); r.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); } }); } @@ -161,7 +160,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(); @@ -256,7 +256,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); } @@ -293,7 +294,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(); } @@ -301,25 +303,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); @@ -331,7 +337,8 @@ 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); @@ -343,7 +350,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 @@ -369,12 +377,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 @@ -397,7 +404,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); } @@ -427,9 +435,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 @@ -454,7 +460,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 { @@ -480,14 +486,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(); r.waitForMessage("aaa aaaccc ccc", build); @@ -514,7 +518,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 } /** @@ -533,7 +538,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); @@ -557,12 +563,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 @@ -586,7 +593,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"); @@ -613,7 +621,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 @@ -626,7 +637,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 @@ -636,7 +650,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 cf9ce2af1d..2a4f27ac67 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java @@ -1,5 +1,8 @@ package hudson.plugins.git; +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + import hudson.model.FreeStyleProject; import hudson.model.Run; import hudson.model.View; @@ -9,10 +12,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 +20,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 +44,8 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (r.jenkins != null) { - this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = + ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -88,30 +88,29 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTheoriesTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); r.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 +118,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,7 +140,8 @@ 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); diff --git a/src/test/java/hudson/plugins/git/GitTagActionTest.java b/src/test/java/hudson/plugins/git/GitTagActionTest.java index 2e70a2c44d..bf7379974a 100644 --- a/src/test/java/hudson/plugins/git/GitTagActionTest.java +++ b/src/test/java/hudson/plugins/git/GitTagActionTest.java @@ -1,5 +1,18 @@ 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.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.IOException; import java.io.StringWriter; @@ -14,32 +27,13 @@ import java.util.Map; import java.util.Random; import java.util.Set; - -import hudson.EnvVars; -import hudson.Extension; -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 org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.util.SystemReader; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; - +import javax.servlet.ServletException; 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 org.eclipse.jgit.lib.ObjectId; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; - +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -48,8 +42,6 @@ import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; -import javax.servlet.ServletException; - /** * Test git tag action. Low value test that was created as part of * another investigation. @@ -80,8 +72,7 @@ public class GitTagActionTest { @ClassRule public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - public GitTagActionTest() { - } + public GitTagActionTest() {} private static FreeStyleProject p; private static GitClient workspaceGitClient = null; @@ -222,7 +213,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 */ @@ -288,17 +281,16 @@ public TestTagWorkerThread(Map tagSet, String ignoredComment) { } @Override - protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) throws IOException, InterruptedException { + protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) + throws IOException, InterruptedException { GitClient gitClient = super.getGitClient(listener, environment, workspace); gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); return gitClient; } } - } - private static Set getMatchingTagNames() throws Exception { Set tags = workspaceGitClient.getTags(); Set matchingTagNames = new HashSet<>(); 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/Security2478Test.java b/src/test/java/hudson/plugins/git/Security2478Test.java index b7476342e1..dd1ea1cbd9 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 = r.jenkins.createProject(WorkflowJob.class, "pipeline"); - String script = "node {\n" + - " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + - "}"; + String script = "node {\n" + + " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" + + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + "}"; p.setDefinition(new CpsFlowDefinition(script, true)); WorkflowRun run = r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0)); - r.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); + r.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 = r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0)); - r.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); + r.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 82df452e5d..a32614d7c8 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 b21275fcef..6c51c98ac2 100644 --- a/src/test/java/hudson/plugins/git/TestGitRepo.java +++ b/src/test/java/hudson/plugins/git/TestGitRepo.java @@ -4,59 +4,58 @@ 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(); git.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); git.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); - } - + } + /** * Creates a commit in current repo. * @param fileName relative path to the file to be committed with default content @@ -81,7 +80,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); } @@ -96,7 +96,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); } @@ -112,8 +113,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 9bc582c005..ddb3446b32 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; @@ -39,15 +40,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")); } @@ -70,25 +72,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 @@ -96,7 +98,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)); } @@ -105,7 +108,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)); } @@ -114,7 +118,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 10d6198b78..f4d0553b68 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java @@ -1,9 +1,12 @@ package hudson.plugins.git.browser; -import org.htmlunit.html.HtmlPage; 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.htmlunit.html.HtmlPage; 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 60ebf1d205..991b6e9e59 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 r = new JenkinsRule(); + @Rule + public JenkinsRule r = 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) { - r.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) { + r.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 = r.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 = r.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 8df2bfaf84..86ac43942a 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); r.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); r.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 f51efc61d7..0bb7191099 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 d963bd4923..39d042e7e6 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 = r.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..02d2940b21 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,13 +16,10 @@ 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; @@ -45,7 +44,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 +56,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 bc6d7d0575..66c7ded44c 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java @@ -24,13 +24,17 @@ */ package hudson.plugins.git.extensions.impl; +import hudson.FilePath; +import hudson.Functions; +import hudson.model.Result; +import hudson.model.TaskListener; +import hudson.plugins.git.GitSCM; +import hudson.plugins.git.util.GitUtilsTest; +import hudson.util.LogTaskListener; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; - -import hudson.plugins.git.GitSCM; -import hudson.plugins.git.util.GitUtilsTest; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.util.SystemReader; @@ -48,16 +52,11 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -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(); @@ -95,16 +94,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(); @@ -138,5 +139,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 ebcb8858c5..f711f208b9 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,22 +81,31 @@ 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); localClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); localClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); 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)); @@ -118,7 +124,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); @@ -147,7 +153,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); @@ -172,7 +178,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); @@ -191,7 +197,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"; @@ -202,7 +208,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 9197f6bb8d..62935303e4 100644 --- a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java +++ b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java @@ -1,26 +1,25 @@ 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 hudson.plugins.git.ApiTokenPropertyConfiguration; +import java.util.Collection; +import java.util.Collections; +import jenkins.model.Jenkins; +import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; import org.htmlunit.WebResponse; import org.htmlunit.util.NameValuePair; -import hudson.plugins.git.ApiTokenPropertyConfiguration; -import jenkins.model.Jenkins; -import net.sf.json.JSONObject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; 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 = r.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 = r.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 = r.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..88456039c5 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,119 +10,117 @@ 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) - cmd.setAuthor(author); + if (author != null) cmd.setAuthor(author); if (committer != null) // cmd.setCommitter(new PersonIdent(committer,new Date())); cmd.setCommitter(committer); @@ -129,114 +129,115 @@ private void commit(String message, PersonIdent author, PersonIdent committer) { 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 fb47137281..2aadaf085b 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..52a0105399 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,36 @@ 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 e58b3b031a..6381da50d2 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 5e793eeb13..c2ec8b8824 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..ddfaaaf286 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 { @@ -209,5 +208,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 0a24cbaffa..a20a3d4bfb 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 r = 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 d7bea205aa..9a4d1a5095 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 40efa21490..18a8d794cc 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); r.getInstance().add(scmSourceOwner, "gitSourceOwner"); gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "", notifyCommitApiToken); - SCMHeadEvent event = - r.getInstance().getExtensionList(SCMEventListener.class).get(SCMEventListenerImpl.class) - .waitSCMHeadEvent(1, TimeUnit.SECONDS); + SCMHeadEvent event = r.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(r.jenkins.getSelfLabel().getName(), "echo Hello", "git"); - GitTool t = new GitTool("myGit", null, Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + HelloToolInstaller inst = + new HelloToolInstaller(r.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 70ee731934..26dfabfb63 100644 --- a/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java +++ b/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java @@ -24,12 +24,10 @@ package jenkins.plugins.git; -import org.htmlunit.WebResponse; -import org.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; @@ -39,6 +37,8 @@ import jenkins.scm.impl.mock.AbstractSampleDVCSRepoRule; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.RepositoryBuilder; +import org.htmlunit.WebResponse; +import org.htmlunit.util.NameValuePair; import org.jvnet.hudson.test.JenkinsRule; /** @@ -75,13 +75,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"); @@ -98,9 +101,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")) { @@ -111,7 +117,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() { @@ -126,7 +136,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); } @@ -134,30 +148,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 989b80f22e..6d2e4b4b39 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,17 +286,17 @@ 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 'config --local commit.gpgsign false'\n" + - " rungit 'config --local tag.gpgSign false'\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 'config --local commit.gpgsign false'\n" + + " rungit 'config --local tag.gpgSign false'\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 abe38698ad..613983b092 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()); r.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")); } @@ -138,14 +138,16 @@ public void testResolveGitToolWithJenkins() throws IOException, InterruptedExcep String credentialsId = null; TestToolInstaller inst = new TestToolInstaller(r.jenkins.getSelfLabel().getName(), "echo Hello", "updated/git"); - GitTool t = new GitTool("myGit", "default/git", Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + 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()); r.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")); } @@ -174,25 +176,37 @@ public void testResolutionGitToolOnAgent() throws Exception { agent.setLabelString("agent-windows"); TestToolInstaller inst = new TestToolInstaller(r.jenkins.getSelfLabel().getName(), "echo Hello", "myGit/git"); - GitTool toolOnMaster = new GitTool("myGit", "default/git", Collections.singletonList( - new InstallSourceProperty(Collections.singletonList(inst)))); + 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()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(toolOnMaster, toolOnAgent, JTool); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnMaster.getName(), toolOnMaster.getHome()))); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), + toolOnMaster.getName(), + toolOnMaster.getHome()))); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnAgent.getName(), toolOnAgent.getHome()))); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), + toolOnAgent.getName(), + toolOnAgent.getHome()))); - agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), JTool.getName(), null))); + agent.getNodeProperties() + .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.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 +228,11 @@ public void testSizeEstimationWithNoGitCache() throws Exception { List list = r.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 +280,8 @@ public void testSizeEstimationWithGitCache() throws Exception { List list = r.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 +291,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 +311,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 +324,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 +344,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 +358,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 +403,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 +424,11 @@ public void testSizeEstimationWithAPIForJGit() throws Exception { GitTool tool = new JGitTool(Collections.emptyList()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); - buildAProject(sampleRepo, false); List list = r.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 +449,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 +472,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 +493,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 +514,12 @@ public void testGitToolChooserWithCustomGitTool() throws Exception { GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); r.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 +534,8 @@ public void testGitToolChooserWithBothGitAndJGit() throws Exception { GitTool jgitTool = new JGitTool(Collections.emptyList()); r.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")); } @@ -525,7 +555,8 @@ public void testGitToolChooserWithAllTools() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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 +576,8 @@ public void testGitToolChooserWithJGitApache() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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 +595,8 @@ public void testGitToolChooserWithJGitApacheAndGit() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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 +618,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 +642,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 +668,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")); } @@ -656,7 +694,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 +736,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 +811,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 = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( @@ -789,7 +829,8 @@ 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 = r.buildAndAssertSuccess(p); if (!noCredentials) { r.waitForMessage("using credential github", b); @@ -800,11 +841,8 @@ private void buildAProject(GitSampleRepoRule sampleRepo, boolean noCredentials) /* 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 = r.jenkins.createProject(WorkflowJob.class, "intentionally-failing-job-without-remote-config"); - p.setDefinition(new CpsFlowDefinition("node {\n" - + " checkout(\n" - + " [$class: 'GitSCM']\n" - + " )\n" - + "}", true)); + p.setDefinition( + new CpsFlowDefinition("node {\n" + " checkout(\n" + " [$class: 'GitSCM']\n" + " )\n" + "}", true)); WorkflowRun b = r.buildAndAssertStatus(hudson.model.Result.FAILURE, p); r.waitForMessage("Couldn't find any revision to build", b); } @@ -815,6 +853,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 46654be9d5..48b4ad0cc1 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,11 +106,7 @@ 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&", @@ -122,17 +118,26 @@ private boolean isTimeAvailable() { "%interior-single-quote%_786'@**", }; 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 three 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)]}, - {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)] + }, + { + userNames[random.nextInt(userNames.length)], + passwords[random.nextInt(passwords.length)], + gitTools[random.nextInt(gitTools.length)] + }, }; public GitUsernamePasswordBindingTest(String username, String password, GitTool gitToolInstance) { @@ -143,20 +148,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); } @@ -174,8 +187,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); @@ -184,14 +198,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 { @@ -200,16 +214,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")); @@ -232,7 +246,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" @@ -244,7 +259,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 { @@ -252,9 +267,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)); @@ -269,7 +288,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()))); } @@ -278,8 +297,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); @@ -289,10 +309,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); @@ -303,18 +329,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 Exception { 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..d845e9783f 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; @@ -32,8 +32,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 +43,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 +61,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 69f7ee8e48..4a0313107b 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 a052738ed1..0d77eae914 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 r = 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 acfeae8833..673d7a9759 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,58 +95,59 @@ 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 = { - // Assembla now requires login to access the space - // " 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 + // Assembla now requires login to access the space + // " 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 11caef6f5a..e4c0a18653 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 r = new JenkinsRule(); + @Rule + public final JenkinsRule r = 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(r.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()).in(repoDir.getRoot()).getClient(); + repo = Git.with(r.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 418640988b..3f9f5da2a2 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,16 @@ 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 { + 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 = r.createFreeStyleProject(); @@ -55,5 +56,4 @@ private static Builder createEnvEchoBuilder(String key, String envVarName) { } return new Shell(String.format("echo \"%s='${%s}'\"", key, envVarName)); } - } From a803d346dc7275879d8c9b4e86b588b3187d01e1 Mon Sep 17 00:00:00 2001 From: JoeyAGawron Date: Tue, 16 Apr 2024 22:15:30 -0400 Subject: [PATCH 21/30] Pushing documentation image --- images/git-extension-for-first-build.png | Bin 0 -> 9742 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 images/git-extension-for-first-build.png diff --git a/images/git-extension-for-first-build.png b/images/git-extension-for-first-build.png new file mode 100644 index 0000000000000000000000000000000000000000..7c38342c55ee03d83626168ca7cbe6f980dcc645 GIT binary patch literal 9742 zcmbt)2{_d4_ct<tO6#O^rQ_ zb;vp~Mz*mJ@7Gg|-|u?g_xiur>$=QxUuVvJ?sGo(IiGW8{)TC*voi58(a_MaYTUej zhlYj@3%vfy$N)Sp)MM_`&b6$ZP$Oj=UzVTOv1XtpAF; zg)6^svFX-QV!F>-vxzw1=M9|D`3NBm|`gO+caC zwveckkTA(*2K-851V zR@kAvr@EI??kqy;5kJBY|HpcmV;HjKsa&Wok|CScF^uQW)6EaG5f7P|@=yDp&^Vw4 z&&JTe<-JcCL&uzZc^0(;^FZ;Lf|aqJku+~*gfNZ zn@T?^e0VY~?dZVR36sj@IE$pM@9+1F8pr~+&|o;}f=Cwo^sMl%YyrglVaBWaaXA1p3&SnhB=`CyUL@{Q5qp zzvi->0yjxrltP0z5yMX&nd@T$mrB zkUs~t$q!G8SX5k9__@7B`0P5`U>EfC+V)!9&}4$eWJRT~8U-#d!f2N#PA8R*%q^Yb zKV4ZFi1+Tr&t_^>p23c6Ey~64i~kC_cvgAiXPmZp2giNEkhROJ80GEHlqs1m{MLG{ zTlO!UEx$TBXoqsN^3$hP{6_;P{MVOuYfA&tH!gL3`kSRYvnQu_@;l-5W+QqHA@n<9 z5RqPp7S#AmGfpEi!MHfh9kJ1E2k6r|s^ms=GPVVc=8{n<>76c%ELca)v{P5a5mhnA zO$hz%HqCb{^t9KH`ZkNzy8aaBw%UBPYS)@HUbE5TRxUGabljl%+ql$5`N`h*ozjKM zJ8|j1gJs{#lPwQscHCTX1;PX$>Mp$Mo zyqo3;xECr{`>Q4@C6YG!nbLAc`nG>w;MT&rHgpI#;@&9cIyVHG6R|isUDk>C>cZ1B zhYzGwTy0yc+40=ss`X2%9FGY++-v9*ml>4eKPBtBu{BS9$jJZkP5+C1k$U%+Rn%NVH@YlR{q5Jso@;JN`K{vFb`of!TV@EE$(a?C%_BDz zwflzqHvO0NDC<4>nd`(72R-%A?1TMiyjJ3(Qz*a9yO8Enx#@++mlA)fMay-$*;%Q2>bg~uTvu_X zyhC_jmw9I3u?Rmu-(Rzqg+HoV1~4V1?WiRG2Rc|p3*u7n9haF z+w0NFh^Y&v*W5}Vi;S@W;RUv>0fJ$l(6&WKZ7Y399_@;&4alg7HxZrLx^`%T9NaoA zQ=;tt=Zk{$HXFl%@^|1}_JXKT0m^Nhkx3=TR>($|#$0Z38(HrP$62wki*F*%)J(yxg$-F~@b8c4(XQbL4u`nf3)`<-K$zRL$`42=t;Dy^qGSY^kH`ysYvqtzg7OE%uA@luF% ztNzi2UZ%Sn3M~xKNJC(zYxz9tBY!7!p^IQ&FXtuN>*-&Z%!#<_@tyOz1s^))LHC&7 zXeQLmJ$jy|7pBXu!F-76>o+9dHe8WKJ4xDoz#(fh_Bf{pH~1s!0*ml~h1;uJ0^$l5 z8A#5w$^lAMLwf3&X*>92!q&^bmBgTW){=ZMVgY(ehWF_C_j$g9a zw(XHV_vmqSx$*qbcCM8(naD*JxKGH^Wo2I7nz3g&RkgT59qvW%JjqbAUd`1wOyM|2 zG`UkJnnPqLXV@z^j`UHw;-iy;_|F!N&EDhjP9K=HMvm+}v)b&Fje{ENonLl?gz|UR z9%)@gDEK?JLS=K>AKt?GruEADv-+h_G&#?___tKs<9V_#fTIMD`qqOI)?^M(pUDxW zagw~dWFs|c)s~XAWo89x(Mm2YpYF0-qsjX~!^B9Yw~5wvx|Fs3IEX?nW7$qLC!o;j zN!B09#dgZm?KuP~@v=L~-_?dB13ozLC7I@p+w1GXy|>jKJ-n)<+Mh`ec6Jyp+sG%r zl^sm7&buJaWL4o>AslchLxAXSex4cYfccw(8F~>iWAdSz$D@Z=h0tdHGt2mPYCvVE zYT7_P!6l|>Bb&>xA|}78NR%82QH09oUFsIlS}myPsIrLkuU^;d9UX9TTOs9f#J8I5 zur0f(xG8i?9^ut3C6A(58-4B~yeW*>yiI1=l@Y;BkJb;nw8dVVwVNZJ)V|IX1Efr1 zmPsF|Gr4(r`WVys4fN*R;b88&u^m5?l-&B2T%hTRJX+ekqfCch8H(-(h4l=1-E|YfKC(Ls+)(0*Tii< zcwMT7!R))qvFPEanM#7&Rrp2$6JKJU@A@&#>U!P53mq4X9OYibr23@XBD4h5oTPNi zdMhIQ#(WT`~`|Phcx1EdOocs=XHhzz%y@w!Gql~qr<)%>J+`- zoU22;o@9cBdU0V2CKGG0Y z_3RJH`@>L$z{lhLLH|ikWA7ZIpXA`U2VMLxh8l*v4V(HeatgTx7^nyH1AY51hDsZ8 z1)BKZT(Q|Hi-W1Z_l-M#1&{_Yfg= zA@E`DA*uxAe{{Tmbt7~Osha+OJpaFS!@ZG~-jR`C!rCblF^VhY^@!p&IgHr7t#`cK z++QU}3ez#s0>Np?S0+naT!{D|lL-ms3*-6j{QRlpIqb?GECGOO)JM)EgSOYX(1bM8 z*|gA*!p+g67_@lkI?=T?36)sY%7XPIY_~=8kj+0Di#=u5=X z2jA}aZY`Xz$k4QC?sm0>wJFH*{)X%>Zc9?@VnH^MlMY?3zRGL$p8>Ly71hhZqV>5W zo<*y(s@!=R2T5? zj^=glhZxEqpc{;;NaK zTJ2CRHZ$y%_FZc28k){Rkfhy)$3(#*^Gfq|jjp5t^4xi4bW8A3vK_iLS$+#lu3l|( z&$*lD@vC~ZX2dYPhX*xW>ayE?dg9G}@r3-2ZHi!pNPbnDR+3k=ULER34zkMk*FE3$ zNyCcHbWC|I&;uwbIGKXn_%&r*@3X`_SE%eIGvr>Z z{7*>Qhc~eiQ$u5a5;|Nyz-PUspGvaV)?cibSNNWl>+ZJRK z4RZ=;($f+1!sF$KW_p|$)Z@J!MB_(7cT__LKBxK)%dZuBSRnjcP0B3Lm18UiwNcAtuin`;X%r39Q34!)f{1#VASe}f=ww#oBSf*wQ; z;kI4v+g?t>$~s%M7YObfoREkt%D8lOkJ} zMpt}Z*dZvzfuoTLLGn@*l|hjzPu0DsvfFC`2`r^oW~qM}l&t;MW|3Ka`N#>T=8?58 zCzU2J2_03z1E8+HGG|YEv~LZJ4XA{&pAO|ws|z?0aKHnu$5Z=BgE3xp zw+yxhO_swBs@vVy%-Qq6rZjYuKsiYmm+N4nI_uRD_IOPns6E?3+paviGSXrg!+b-8 znrfe&_+7CIxgHl&=|H?HQXlHCV}U5POfwTkzao+@59ZyJY65Xlcr}J+N3jsLshL=PfDY9W&exe8KgEn4tOy($h)#yvuMXFQgj}Xj+(-Fo$JahLiDx#R zuwwgmj(lg%qVF5g299<$lj%`ev?aeZE8-`sRCoUq#l|l;anH26?ShkZ0PibgmDLii z9x~Kho8PHapuB$?8oGOyn=xtiDIZ$;zvj&&`JPOCTCL!9kl#GLk18Se_^>OP6obr{ z1t}-vm$qz`Si?=zWqe(fKk6xj?}sA{B0z^t`bXY6%L>RZ3OtS&KkrG$5lgjKT8|H8 zpJICF2mb3b-nv;}N${^}qVF$PJZBHgM`a(f5ahk^wA4y`T^*#la-GD?iq#c+aDG1~ zwDeCPzeB3(Zg7pNxh|IZ0fS94z2bye1}zoaj2vK?5v*;g>nhXos6KUF>=L{Dyr~f^ z#>Miv1y>S${~QucbcM3)ak4Cv#>LBDxJj>*}yNGPwt9;v?!NDq@ z)0DDY7ORfMFLh5CQT3ylSeAczMg{m%u5z0~K9$VkCrfk$$}&NdRa2Z8X^EqJF;w44 zT&FwCCLo~riQ{Q;+6a0OedsW+V~{gjYf3;TEGHt>nwOg|qLQjy?5spVXejB-*OTGK zm}k|Wr#c!Ut{^acfe!sg_pXe+Vz`28QLDASPLLzVK z6J5BiEzI_8xqx;ll}pVd>^t8hbFI0&n^~}ho^sD-XbAhYj2#RQ+wppC8#ximCzG$! z`1Ov6C{Wv`Pa5;zSKLQeUB{7b@-g?q@Csi;bN(0nYht2cjC8>zkTf*~a9^Pf*1b79 zG#;>;L(tT??+J$bf4%kh@qO1fYSx90-(yX0suV}eZrCb&>u2LUO$;^dacIZtWARR} z@5}FFBRrF_dqcRU##jg4W*sAcT2$ohc|;D+8={|{MOVbbd!Em&dEZn$qfjWWV@(=! zeb#XKG4*x_eEfy7bpoL!F=0rm45RsvsN&cV?w^1*U>G;}FKy{eZ}*h;EA-2gLe|>?rTx%;6qyXKAA|5Jv#J9(gG=Q^H*;W6ulee_ z!(mQWl0Pr&-LJQm3>}`Sppd!V4lcJDMsqPUaF=xHkN8>&spXlTxU)%Qv_P_Yd5KH6 zI7+WeVz$q**cB(^*?FgZ`mRH0veK9glUfZbe;~Is3e)Lhm3_3=7}01w;EzhB7$wi9 zjH0@pM-=H?F7zq>O~oy*9f|jzxsmGu6gQ`{*Gj{`Q5x7C-)d-r#POmM=L82!nOur( z6_vQlXV>2#oi`m%KA92cr5>F##QSjinyJ@8b$#3*>9Gk))B!*8h#sk!>uo@uL0NC&I#-l8_Rm3D5 z9H8wgMvH~fXNhZ^3}P=L2_@bRR^6p~5axFN;ob^h`zg`+e%WFHQ~3rT(~<83wwU5N z2N%`^s}7WpfxK;zpz&tZU~(-=Q%x?5|BQ1M*+6q}IK|ogC%aN_f4|hVE3U!c?+}>V zkIA_U{<*tJXJ9yZ)N_){Zisc-85`e#(hHV2w>UDrG?j3koVZuChD6cF8Iii7b(R4t zCVqN#gB2)Z_B6vcnm6QYdH9|I&XsQ)t|U~3%W;OU6PHOI_IjFMUq?pb=GTCFK>;Qd zaBo*rH>hlDeMCXq`c!gGuuv(fr?(^|iFU6KvrnV3xb~Mra_?8KD}Lva<5=!~!@Mpn zL)t)fHw`Kxp<1NQ))h?#8%2a!zEA?o<8K(8EAzNjtq7`hrO=Y7vjs=Dy&i6{BjIW| zB}geNeKB_MMj_|TC;<5RZElnz>%Q@MZd{xD<^;Jw+97#9g)^SCX5!YH^pqDu!gOpKefy{uy4 ze9*Yk7ff!(MNx{jpFsOpjwCqhpeU{4{l6wIcTbhLIPbiFq{s%hUhT=82R&AFYc4=& zhzR`2IS@~JhK<#pEn_S> z6%qg2fw{pzL$`2D@8(C68&sxBN$yE7T_mc0AkjIUgz)NI@wvyZs%*6xM?`58y04&9 zQL$!`J& zVP@vL)>ooyR0ie4)vmxfcIh^mmYK0RBUJcgT*Im zmXzpcJXPQiH`VB~O@uPPE59FL`5pFa7t%$4MI z{QNeY_wtzLT)H6Tapio2W=hQ!S#&Cim+#fV`hT&b1eubc?tF--7>eqA5R6*DD6Jfk zvHo&qu7W6B2@l<}z`r)U7Yck!;clyszUN=6zQ?by7ub_kuM)t79{jtSL><9Z+cOQ{ zUXJaKAC3!e1xav+&UspR6A+=DKgQhy`BgDv)bn{ZZ%)FzT|#BMWR8>Y%S{J z;Ed6M3E04HhYUoT`(m3(#G;+j5-7`o`*lQ#q7F>pW6oFq{ouUi0*ivVfPBq_Hr5k& zt);k@*>?)&Fxbd{>99C$LZz-9Pa(5)Za^9>4JW_T54?(q=IAY&XbmD`FGu8kr=bDm z@BS8`c%QPsw8Q)O?_uTt9rC)7|s}Ud1V1pFQWSLX%?(=&x6MOuj z!p1J~nC*sR%>RC2Cr?Nb)Mvr2EIh0~g?_$IDm&f*?aPk_o9K&nTGf`4vUL-e_E=KK z7@Za~)*sy@EwQpyT`f;3BiclcO$0&jiU|=5ODCz33=5-w5)3PC z&SlSq$LI;+xc=_riu)-`S9IaPSZsGR$0wiFs9i@L^U;Lg<@n?LJilZ1SNDz)23exN ze>jAh8C%HeEO1ht%JA$D13tY4bB&ro!uJR$gqN8;esFE9%X`mmns6-OBCK>Sm1Ejl zhwswm+W=?lU6(!3f(0`D@r4K5XPKqR9-kO$SJ)A<3(=MI49wnMG<12Q5SZ&^j{4vp zfN1HHgkw*}TNAt_^FH%&?_E|1O*kDr;5}gSNNX6UM+Gq7xxHrLhpyt}k$szK>1WuV zw!WpGl#A`>*w=z21MO>`Z>#-fs&i<8!_mdcf~YIRBa&iZ!i{5tbyaQc9@I_}xCGKs zwr#p?&*R*tnl)dIQ_bKw1++4k-d#;Ow7(Zkcondjzs5tpeWSvy&iy_ci^w^-1CH?l z9Ai_Hm``$i&bH64GuWU0OUrj$`fp{av9Ykk)4fom?#L2KYolWWv*`?Q1H5Wz_-Q42 zmN;VQ#@jD&zyvTL1hV-f)Wa*iuI5wSYyN)|a=|Osyv)xxw)j5^0fUC&Lw5)7sSY;} zn-P^1+>ryexzs!lL0Zwa>J0aFPX1Fq3A~cN27Qj1dJ!SQBH56vi%LJ zL3C=b9v?sjD^nB0_=H20BshPh%@Q(zLR*T|4RO9 zlMRE7RtQdKSf*946#k;vvv0BSC_JTc3roxi;&rYT>u2NYq4S3D!w$DC1TN0+6(~YF*PH%=bYr};RaY|3ev{c;P^Q^Fj0||omVIdEhdV1f z{aP@R2l@M5l3CIH*X^;`SJ?Q=2v;k#B${s#nc~cTVEn}negw=tSPa9ZsgaA<4nvw% zXsSG-A`2@7fn91eK(bPAM#gbqY?0w~nRTyq0Z@db0g4js*OUXpm;WK4f&P0_f`}vX zh*57pMCcyy1%n$Vjk;;0Q5aI;h4>|NYB-;A34t+#h3EILN1X(x5cuf$bIo3={bQhQ uL2+8 Date: Wed, 1 May 2024 11:36:33 -0600 Subject: [PATCH 22/30] Undo spotless changes - not ready for spotless --- pom.xml | 130 +- .../git/ApiTokenPropertyConfiguration.java | 30 +- .../java/hudson/plugins/git/BranchSpec.java | 51 +- .../plugins/git/ChangelogToBranchOptions.java | 10 +- .../plugins/git/GitBranchSpecifierColumn.java | 16 +- .../plugins/git/GitBranchTokenMacro.java | 21 +- .../plugins/git/GitChangeLogParser.java | 29 +- .../java/hudson/plugins/git/GitChangeSet.java | 107 +- .../hudson/plugins/git/GitChangeSetList.java | 9 +- .../java/hudson/plugins/git/GitPublisher.java | 233 +-- .../git/GitRevisionBuildParameters.java | 63 +- .../plugins/git/GitRevisionTokenMacro.java | 19 +- src/main/java/hudson/plugins/git/GitSCM.java | 697 ++++----- .../git/GitSCMBackwardCompatibility.java | 89 +- .../java/hudson/plugins/git/GitStatus.java | 178 +-- .../plugins/git/GitStatusCrumbExclusion.java | 3 +- .../java/hudson/plugins/git/GitTagAction.java | 42 +- .../hudson/plugins/git/ObjectIdConverter.java | 19 +- .../plugins/git/RemoteConfigConverter.java | 109 +- .../plugins/git/RevisionParameterAction.java | 63 +- .../plugins/git/SubmoduleCombinator.java | 34 +- .../hudson/plugins/git/SubmoduleConfig.java | 20 +- .../hudson/plugins/git/UserMergeOptions.java | 42 +- .../hudson/plugins/git/UserRemoteConfig.java | 102 +- .../plugins/git/browser/AssemblaWeb.java | 31 +- .../plugins/git/browser/BitbucketServer.java | 22 +- .../plugins/git/browser/BitbucketWeb.java | 20 +- .../java/hudson/plugins/git/browser/CGit.java | 24 +- .../browser/FisheyeGitRepositoryBrowser.java | 208 +-- .../git/browser/GitBlitRepositoryBrowser.java | 57 +- .../hudson/plugins/git/browser/GitLab.java | 24 +- .../hudson/plugins/git/browser/GitList.java | 23 +- .../git/browser/GitRepositoryBrowser.java | 47 +- .../hudson/plugins/git/browser/GitWeb.java | 49 +- .../hudson/plugins/git/browser/GithubWeb.java | 32 +- .../hudson/plugins/git/browser/Gitiles.java | 24 +- .../plugins/git/browser/GitoriousWeb.java | 24 +- .../hudson/plugins/git/browser/GogsGit.java | 22 +- .../hudson/plugins/git/browser/KilnGit.java | 23 +- .../plugins/git/browser/Phabricator.java | 14 +- .../plugins/git/browser/RedmineWeb.java | 27 +- .../hudson/plugins/git/browser/RhodeCode.java | 20 +- .../hudson/plugins/git/browser/Stash.java | 36 +- .../browser/TFS2013GitRepositoryBrowser.java | 67 +- .../plugins/git/browser/ViewGitWeb.java | 57 +- .../git/browser/casc/GitLabConfigurator.java | 4 +- .../git/extensions/FakeGitSCMExtension.java | 3 +- .../GitClientConflictException.java | 3 +- .../plugins/git/extensions/GitClientType.java | 10 +- .../git/extensions/GitSCMExtension.java | 148 +- .../extensions/GitSCMExtensionDescriptor.java | 2 +- .../extensions/impl/AuthorInChangelog.java | 3 +- .../extensions/impl/BuildChooserSetting.java | 6 +- .../impl/BuildSingleRevisionOnly.java | 3 +- .../extensions/impl/ChangelogToBranch.java | 5 +- .../git/extensions/impl/CheckoutOption.java | 17 +- .../extensions/impl/CleanBeforeCheckout.java | 11 +- .../git/extensions/impl/CleanCheckout.java | 11 +- .../git/extensions/impl/CloneOption.java | 32 +- .../extensions/impl/DisableRemotePoll.java | 3 +- .../git/extensions/impl/GitLFSPull.java | 11 +- .../extensions/impl/IgnoreNotifyCommit.java | 3 +- .../git/extensions/impl/LocalBranch.java | 10 +- .../git/extensions/impl/MessageExclusion.java | 97 +- .../git/extensions/impl/PathRestriction.java | 35 +- .../git/extensions/impl/PerBuildTag.java | 11 +- .../git/extensions/impl/PreBuildMerge.java | 67 +- .../git/extensions/impl/PruneStaleBranch.java | 8 +- .../git/extensions/impl/PruneStaleTag.java | 16 +- .../impl/RelativeTargetDirectory.java | 7 +- .../extensions/impl/SparseCheckoutPath.java | 19 +- .../extensions/impl/SparseCheckoutPaths.java | 31 +- .../git/extensions/impl/SubmoduleOption.java | 49 +- .../git/extensions/impl/UserExclusion.java | 17 +- .../git/extensions/impl/UserIdentity.java | 24 +- .../git/extensions/impl/WipeWorkspace.java | 6 +- .../plugins/git/opt/PreBuildMergeOptions.java | 25 +- .../git/util/AncestryBuildChooser.java | 72 +- .../java/hudson/plugins/git/util/Build.java | 29 +- .../hudson/plugins/git/util/BuildChooser.java | 64 +- .../plugins/git/util/BuildChooserContext.java | 10 +- .../git/util/BuildChooserDescriptor.java | 4 +- .../hudson/plugins/git/util/BuildData.java | 104 +- .../git/util/CommitTimeComparator.java | 15 +- .../plugins/git/util/DefaultBuildChooser.java | 92 +- .../hudson/plugins/git/util/GitUtils.java | 126 +- .../plugins/git/util/InverseBuildChooser.java | 22 +- .../plugins/git/AbstractGitSCMSource.java | 937 ++++++------ .../jenkins/plugins/git/GitBranchSCMHead.java | 7 +- .../plugins/git/GitBranchSCMRevision.java | 3 + .../plugins/git/GitCredentialBindings.java | 34 +- .../plugins/git/GitHooksConfiguration.java | 34 +- .../plugins/git/GitRemoteHeadRefAction.java | 11 +- .../jenkins/plugins/git/GitSCMBuilder.java | 18 +- .../java/jenkins/plugins/git/GitSCMFile.java | 12 +- .../jenkins/plugins/git/GitSCMFileSystem.java | 86 +- .../jenkins/plugins/git/GitSCMMatrixUtil.java | 8 +- .../jenkins/plugins/git/GitSCMSource.java | 141 +- .../plugins/git/GitSCMSourceContext.java | 18 +- .../plugins/git/GitSCMSourceDefaults.java | 12 +- .../plugins/git/GitSCMSourceRequest.java | 4 +- .../jenkins/plugins/git/GitSCMTelescope.java | 89 +- .../java/jenkins/plugins/git/GitStep.java | 20 +- .../jenkins/plugins/git/GitTagSCMHead.java | 1 + .../jenkins/plugins/git/GitToolChooser.java | 114 +- .../git/GitUsernamePasswordBinding.java | 131 +- .../plugins/git/MatrixGitPublisher.java | 3 +- .../plugins/git/MergeWithGitSCMExtension.java | 21 +- .../git/traits/BranchDiscoveryTrait.java | 5 +- .../git/traits/CleanAfterCheckoutTrait.java | 3 +- .../git/traits/CleanBeforeCheckoutTrait.java | 3 +- .../git/traits/DiscoverOtherRefsTrait.java | 15 +- .../git/traits/GitBrowserSCMSourceTrait.java | 3 +- .../git/traits/GitSCMExtensionTrait.java | 2 +- .../GitSCMExtensionTraitDescriptor.java | 48 +- .../git/traits/GitToolSCMSourceTrait.java | 9 +- .../traits/IgnoreOnPushNotificationTrait.java | 5 +- .../plugins/git/traits/LocalBranchTrait.java | 2 +- .../git/traits/PruneStaleTagTrait.java | 5 +- .../git/traits/RefSpecsSCMSourceTrait.java | 4 +- .../git/traits/RemoteNameSCMSourceTrait.java | 14 +- .../plugins/git/traits/TagDiscoveryTrait.java | 8 +- .../plugins/git/AbstractGitProject.java | 200 +-- .../plugins/git/AbstractGitRepository.java | 23 +- .../plugins/git/AbstractGitTestCase.java | 305 ++-- .../hudson/plugins/git/BranchSpecTest.java | 88 +- .../git/ChangelogToBranchOptionsTest.java | 3 +- .../git/CheckoutStepSnippetizerTest.java | 186 ++- .../git/CliGitSCMTriggerLocalPollTest.java | 10 +- .../git/CliGitSCMTriggerRemotePollTest.java | 7 +- .../git/CredentialsUserRemoteConfigTest.java | 48 +- .../git/GitBranchSpecifierColumnTest.java | 12 +- .../plugins/git/GitChangeLogParserTest.java | 29 +- .../plugins/git/GitChangeSetBadArgsTest.java | 18 +- .../plugins/git/GitChangeSetBasicTest.java | 142 +- .../plugins/git/GitChangeSetEmptyTest.java | 7 +- .../plugins/git/GitChangeSetEuroTest.java | 3 +- .../plugins/git/GitChangeSetListTest.java | 14 +- .../git/GitChangeSetPluginHistoryTest.java | 32 +- .../plugins/git/GitChangeSetSimpleTest.java | 101 +- .../hudson/plugins/git/GitChangeSetTest.java | 97 +- .../git/GitChangeSetTimestampTest.java | 5 +- .../plugins/git/GitChangeSetTruncateTest.java | 76 +- .../hudson/plugins/git/GitChangeSetUtil.java | 118 +- .../java/hudson/plugins/git/GitHooksTest.java | 124 +- .../hudson/plugins/git/GitPublisherTest.java | 520 +++---- .../git/GitRevisionTokenMacroTest.java | 18 +- .../hudson/plugins/git/GitSCMBrowserTest.java | 11 +- .../hudson/plugins/git/GitSCMSlowTest.java | 99 +- .../java/hudson/plugins/git/GitSCMTest.java | 1346 +++++++---------- .../hudson/plugins/git/GitSCMUnitTest.java | 92 +- .../git/GitStatusCrumbExclusionTest.java | 14 +- .../plugins/git/GitStatusSimpleTest.java | 2 +- .../hudson/plugins/git/GitStatusTest.java | 107 +- .../plugins/git/GitStatusTheoriesTest.java | 47 +- .../hudson/plugins/git/GitTagActionTest.java | 54 +- .../git/JGitSCMTriggerLocalPollTest.java | 14 +- .../git/JGitSCMTriggerRemotePollTest.java | 12 +- .../RevisionParameterActionRemoteUrlTest.java | 14 +- .../git/RevisionParameterActionTest.java | 28 +- .../hudson/plugins/git/Security2478Test.java | 38 +- .../plugins/git/SubmoduleCombinatorTest.java | 9 +- .../plugins/git/SubmoduleConfigTest.java | 7 +- .../java/hudson/plugins/git/TestGitRepo.java | 82 +- .../plugins/git/UserMergeOptionsTest.java | 43 +- .../git/UserRemoteConfigRefSpecTest.java | 46 +- .../plugins/git/UserRemoteConfigTest.java | 50 +- .../browser/AssemblaWebDoCheckURLTest.java | 47 +- .../plugins/git/browser/AssemblaWebTest.java | 4 +- .../git/browser/BitbucketServerTest.java | 33 +- .../plugins/git/browser/BitbucketWebTest.java | 33 +- .../hudson/plugins/git/browser/CGitTest.java | 4 +- .../FisheyeGitRepositoryBrowserTest.java | 6 +- .../browser/GitBlitRepositoryBrowserTest.java | 14 +- .../git/browser/GitChangeSetSample.java | 16 +- .../plugins/git/browser/GitLabTest.java | 36 +- .../git/browser/GitLabWorkflowTest.java | 21 +- .../plugins/git/browser/GitListTest.java | 35 +- .../git/browser/GitRepositoryBrowserTest.java | 15 +- .../plugins/git/browser/GitWebTest.java | 34 +- .../plugins/git/browser/GithubWebTest.java | 118 +- .../plugins/git/browser/GitilesTest.java | 9 +- .../plugins/git/browser/GitoriousWebTest.java | 45 +- .../plugins/git/browser/GogsGitTest.java | 36 +- .../plugins/git/browser/KilnGitTest.java | 38 +- .../plugins/git/browser/PhabricatorTest.java | 10 +- .../plugins/git/browser/RedmineWebTest.java | 47 +- .../plugins/git/browser/RhodeCodeTest.java | 40 +- .../hudson/plugins/git/browser/StashTest.java | 9 +- .../TFS2013GitRepositoryBrowserTest.java | 28 +- .../TFS2013GitRepositoryBrowserXSSTest.java | 12 +- .../plugins/git/browser/ViewGitWebTest.java | 42 +- .../browser/casc/GitLabConfiguratorTest.java | 18 +- .../git/extensions/GitSCMExtensionTest.java | 116 +- .../impl/AuthorInChangelogTest.java | 11 +- .../impl/BuildSingleRevisionOnlyTest.java | 21 +- .../impl/ChangelogToBranchTest.java | 11 +- .../extensions/impl/CheckoutOptionTest.java | 6 +- .../impl/CheckoutOptionWorkflowTest.java | 16 +- .../extensions/impl/CleanCheckoutTest.java | 6 +- .../extensions/impl/CloneOptionDepthTest.java | 5 +- .../impl/CloneOptionHonorRefSpecTest.java | 41 +- .../impl/CloneOptionNoTagsTest.java | 30 +- .../CloneOptionShallowDefaultTagsTest.java | 16 +- .../git/extensions/impl/CloneOptionTest.java | 5 +- .../git/extensions/impl/EnforceGitClient.java | 11 +- .../git/extensions/impl/GitLFSPullTest.java | 4 +- .../impl/IgnoreNotifyCommitTest.java | 4 +- .../git/extensions/impl/LocalBranchTest.java | 10 +- .../git/extensions/impl/LogHandler.java | 3 +- .../extensions/impl/MessageExclusionTest.java | 66 +- .../extensions/impl/PathRestrictionTest.java | 91 +- .../extensions/impl/PreBuildMergeTest.java | 52 +- .../extensions/impl/PruneStaleBranchTest.java | 4 +- .../impl/PruneStaleTagPipelineTest.java | 40 +- .../extensions/impl/PruneStaleTagTest.java | 50 +- .../impl/SparseCheckoutPathTest.java | 4 +- .../impl/SparseCheckoutPathsTest.java | 17 +- .../impl/SubmoduleOptionDepthTest.java | 5 +- .../extensions/impl/SubmoduleOptionTest.java | 88 +- .../extensions/impl/UserExclusionTest.java | 63 +- .../git/extensions/impl/UserIdentityTest.java | 18 +- .../extensions/impl/WipeWorkspaceTest.java | 10 +- .../git/opt/PreBuildMergeOptionsTest.java | 22 +- .../ApiTokenPropertyConfigurationTest.java | 85 +- .../git/util/AncestryBuildChooserTest.java | 133 +- .../git/util/BuildDataLoggingTest.java | 14 +- .../plugins/git/util/BuildDataTest.java | 41 +- .../hudson/plugins/git/util/BuildTest.java | 6 +- .../git/util/CandidateRevisionsTest.java | 22 +- .../git/util/CommitTimeComparatorTest.java | 27 +- .../git/util/DefaultBuildChooserTest.java | 43 +- .../git/util/GitUtilsJenkinsRuleTest.java | 6 +- .../hudson/plugins/git/util/GitUtilsTest.java | 22 +- .../plugins/git/AbstractGitSCMSourceTest.java | 328 ++-- .../git/AbstractGitSCMSourceTrivialTest.java | 10 +- .../git/BrowsersJCasCCompatibilityTest.java | 304 ++-- .../jenkins/plugins/git/CliGitCommand.java | 33 +- .../plugins/git/GitBranchSCMHeadTest.java | 24 +- .../git/GitHooksConfigurationTest.java | 15 +- .../git/GitJCasCCompatibilityTest.java | 7 +- .../git/GitRemoteHeadRefActionTest.java | 4 +- .../plugins/git/GitSCMBuilderTest.java | 722 +++++---- .../plugins/git/GitSCMFileSystemTest.java | 128 +- .../git/GitSCMJCasCCompatibilityTest.java | 11 +- .../plugins/git/GitSCMSourceDefaultsTest.java | 4 +- .../jenkins/plugins/git/GitSCMSourceTest.java | 290 ++-- .../plugins/git/GitSCMSourceTraitsTest.java | 228 +-- .../plugins/git/GitSCMTelescopeTest.java | 58 +- .../plugins/git/GitSampleRepoRule.java | 73 +- .../java/jenkins/plugins/git/GitStepTest.java | 105 +- .../plugins/git/GitToolChooserTest.java | 220 ++- .../git/GitToolJCasCCompatibilityTest.java | 38 +- .../git/GitUsernamePasswordBindingTest.java | 149 +- ...braryWithLegacyJCasCCompatibilityTest.java | 280 ++-- ...braryWithModernJCasCCompatibilityTest.java | 237 +-- .../git/MergeWithGitSCMExtensionTest.java | 35 +- .../jenkins/plugins/git/ModernScmTest.java | 11 +- .../java/jenkins/plugins/git/RandomOrder.java | 4 +- .../traits/DiscoverOtherRefsTraitTest.java | 5 +- .../git/traits/GitSCMExtensionTraitTest.java | 15 +- .../traits/MultibranchProjectTraitsTest.java | 126 +- .../git/traits/PruneStaleBranchTraitTest.java | 9 +- .../plugins/gitclient/TestCliGitAPIImpl.java | 1 + .../plugins/gitclient/TestJGitAPIImpl.java | 6 +- .../AbstractGitTagMessageExtensionTest.java | 30 +- .../GitTagMessageExtensionTest.java | 14 +- 267 files changed, 7280 insertions(+), 8572 deletions(-) diff --git a/pom.xml b/pom.xml index 5452f78b81..30de966abe 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,20 +95,9 @@ - - - io.jenkins - configuration-as-code - true - - - org.jenkins-ci.plugins - credentials - - org.jenkins-ci.plugins - credentials-binding + structs org.jenkins-ci.plugins @@ -116,24 +105,11 @@ org.jenkins-ci.plugins - mailer - - - org.jenkins-ci.plugins - matrix-project - true - - - - org.jenkins-ci.plugins - parameterized-trigger - true + credentials org.jenkins-ci.plugins - promoted-builds - 3.11 - true + ssh-credentials org.jenkins-ci.plugins @@ -144,17 +120,8 @@ script-security - org.jenkins-ci.plugins - ssh-credentials - - - org.jenkins-ci.plugins - structs - - - org.jenkins-ci.plugins - token-macro - true + org.jenkins-ci.plugins.workflow + workflow-step-api org.jenkins-ci.plugins.workflow @@ -162,16 +129,23 @@ org.jenkins-ci.plugins.workflow - workflow-step-api + workflow-cps + tests + test - io.jenkins.configuration-as-code - test-harness - test + org.jenkins-ci.plugins + matrix-project + true - io.jenkins.plugins - pipeline-groovy-lib + org.jenkins-ci.plugins + mailer + + + + org.jenkins-ci.plugins + junit test @@ -179,27 +153,43 @@ junit test + + org.mockito + mockito-core + test + nl.jqno.equalsverifier equalsverifier 3.16.1 test + - org.jenkins-ci.main - jenkins-test-harness - test + org.jenkins-ci.plugins + credentials-binding + org.jenkins-ci.plugins - git-tag-message - 1.7.1 - test + parameterized-trigger + true - org.jenkins-ci.plugins - junit + token-macro + true + + + org.jenkins-ci.plugins + promoted-builds + 3.11 + true + + + org.jenkins-ci.plugins.workflow + workflow-step-api + tests test @@ -210,13 +200,12 @@ org.jenkins-ci.plugins.workflow - workflow-basic-steps + workflow-job test org.jenkins-ci.plugins.workflow - workflow-cps - tests + workflow-basic-steps test @@ -226,23 +215,34 @@ org.jenkins-ci.plugins.workflow - workflow-job + workflow-multibranch test - org.jenkins-ci.plugins.workflow - workflow-multibranch + io.jenkins.plugins + pipeline-groovy-lib test - org.jenkins-ci.plugins.workflow - workflow-step-api - tests + org.jenkins-ci.plugins + git-tag-message + 1.7.1 test + - org.mockito - mockito-core + io.jenkins + configuration-as-code + true + + + io.jenkins.configuration-as-code + test-harness + test + + + org.jenkins-ci.main + jenkins-test-harness test diff --git a/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java b/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java index 4540174e03..346b121d6e 100644 --- a/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java +++ b/src/main/java/hudson/plugins/git/ApiTokenPropertyConfiguration.java @@ -5,6 +5,18 @@ 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; @@ -17,17 +29,7 @@ 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) @@ -73,8 +75,7 @@ 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) { @@ -171,8 +172,7 @@ 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 12442298af..e083a75bc0 100644 --- a/src/main/java/hudson/plugins/git/BranchSpec.java +++ b/src/main/java/hudson/plugins/git/BranchSpec.java @@ -1,10 +1,11 @@ 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; @@ -13,10 +14,11 @@ 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. * @@ -41,9 +43,12 @@ public String getName() { } public void setName(String name) { - if (name == null) throw new IllegalArgumentException(); - else if (name.length() == 0) this.name = "**"; - else this.name = name.trim(); + if(name == null) + throw new IllegalArgumentException(); + else if(name.length() == 0) + this.name = "**"; + else + this.name = name.trim(); } @DataBoundConstructor @@ -92,8 +97,7 @@ 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(); } /** @@ -109,14 +113,15 @@ public List filterMatching(Collection branches) { public List filterMatching(Collection branches, EnvVars env) { List items = new ArrayList<>(); - - for (String b : branches) { - if (matches(b, env)) items.add(b); + + 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); @@ -124,11 +129,12 @@ 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)) items.add(b); + + for(Branch b : branches) { + if(matches(b.getName(), env)) + items.add(b); } - + return items; } @@ -166,6 +172,7 @@ 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("/")) { @@ -183,12 +190,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? @@ -197,11 +204,13 @@ 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 @@ -213,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 1f6b317d50..00ccb4db0b 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 hudson.Extension; -import hudson.model.AbstractDescribableImpl; -import hudson.model.Descriptor; import java.io.Serializable; import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; +import hudson.Extension; +import hudson.model.AbstractDescribableImpl; +import hudson.model.Descriptor; + /** * 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 91d727bd70..dd8c63119b 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,5 +53,7 @@ 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 ae24a32d73..82952f8081 100644 --- a/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java +++ b/src/main/java/hudson/plugins/git/GitBranchTokenMacro.java @@ -29,16 +29,17 @@ 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. @@ -58,26 +59,24 @@ 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(); @@ -88,7 +87,7 @@ 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 47be7d92cb..3f9ab90905 100644 --- a/src/main/java/hudson/plugins/git/GitChangeLogParser.java +++ b/src/main/java/hudson/plugins/git/GitChangeLogParser.java @@ -1,13 +1,19 @@ 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; @@ -18,9 +24,6 @@ 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 @@ -65,13 +68,11 @@ 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); } } @@ -80,8 +81,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())); @@ -102,8 +103,8 @@ private List parse(Iterator changelog) { lines = new ArrayList<>(); } - if (lines != null && lines.size() < THRESHOLD) - lines.add(line); // TODO: if we ignored some lines, tell the user so. + 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"; @@ -57,7 +60,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()); @@ -81,7 +84,6 @@ 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; @@ -168,7 +170,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; } } @@ -178,7 +180,8 @@ private void parseCommit(List lines) { StringBuilder message = new StringBuilder(); for (String line : lines) { - if (line.length() < 1) continue; + if( line.length() < 1) + continue; if (line.startsWith("commit ")) { String[] split = line.split(" "); if (split.length > 1) this.id = split[1]; @@ -190,7 +193,8 @@ private void parseCommit(List lines) { 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)); @@ -213,11 +217,8 @@ 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)); } @@ -239,7 +240,8 @@ 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)); } } @@ -253,16 +255,16 @@ 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(" ")) { @@ -283,7 +285,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 @@ -326,7 +328,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) { } } @@ -348,7 +350,8 @@ public void setParent(ChangeLogSet parent) { super.setParent(parent); } - public @CheckForNull String getParentCommit() { + public @CheckForNull + String getParentCommit() { return parentCommit; } @@ -431,11 +434,8 @@ 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 +456,7 @@ public User findOrCreateUser( 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,7 +469,8 @@ public User findOrCreateUser( } if (user != null && setUserDetails) { user.setFullName(csAuthor); - if (hasMailerPlugin()) setMail(user, csAuthorEmail); + if (hasMailerPlugin()) + setMail(user, csAuthorEmail); user.save(); } } catch (AuthenticationException authException) { @@ -577,13 +578,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()); } /** @@ -621,7 +622,7 @@ 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()); @@ -635,7 +636,7 @@ public String getBranch() { return null; } - @ExportedBean(defaultVisibility = 999) + @ExportedBean(defaultVisibility=999) public static class Path implements AffectedFile { private String src; @@ -660,7 +661,7 @@ public String getDst() { return dst; } - @Exported(name = "file") + @Exported(name="file") public String getPath() { return path; } @@ -672,12 +673,12 @@ public GitChangeSet getChangeSet() { @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 9911bce0d3..d013724c1b 100644 --- a/src/main/java/hudson/plugins/git/GitChangeSetList.java +++ b/src/main/java/hudson/plugins/git/GitChangeSetList.java @@ -3,10 +3,11 @@ 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. @@ -17,9 +18,10 @@ 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) log.setParent(this); + for (GitChangeSet log : logs) + log.setParent(this); } public boolean isEmptySet() { @@ -38,4 +40,5 @@ public List getLogs() { 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 1972f5b4b1..bbb8332dff 100644 --- a/src/main/java/hudson/plugins/git/GitPublisher.java +++ b/src/main/java/hudson/plugins/git/GitPublisher.java @@ -21,11 +21,6 @@ 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; @@ -33,6 +28,12 @@ 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; @@ -45,21 +46,20 @@ 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( 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,22 +125,23 @@ public List getNotesToPush() { return notesToPush; } - + + 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; @@ -155,9 +156,10 @@ protected GitClient getGitClient( throws IOException, InterruptedException { return gitSCM.createClient(listener, environment, build, build.getWorkspace(), cmd); } - + @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, @@ -180,16 +182,15 @@ public boolean perform(AbstractBuild build, Launcher launcher, final 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 = getGitClient(gitSCM, listener, environment, build, cmd); + final GitClient git = getGitClient(gitSCM, listener, environment, build, cmd); URIish remoteURI; @@ -200,7 +201,8 @@ public boolean perform(AbstractBuild build, Launcher launcher, final 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)) git.deleteTag(buildnumber); + if (git.tagExists(buildnumber)) + git.deleteTag(buildnumber); // And add the success / fail state into the tag. buildnumber += "-" + buildResult.toString(); @@ -219,19 +221,14 @@ public boolean perform(AbstractBuild build, Launcher launcher, final 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")); @@ -241,16 +238,18 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build if (isPushTags()) { for (final TagToPush t : tagsToPush) { - if (t.getTagName() == null) throw new AbortException("No tag to push defined"); + if (t.getTagName() == null) + throw new AbortException("No tag to push defined"); - if (t.getTargetRepoName() == null) throw new AbortException("No target repo to push to defined"); + 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) @@ -262,21 +261,21 @@ public boolean perform(AbstractBuild build, Launcher launcher, final 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); @@ -287,18 +286,20 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build } } } - + if (isPushBranches()) { for (final BranchToPush b : branchesToPush) { - if (b.getBranchName() == null) throw new AbortException("No branch to push defined"); + if (b.getBranchName() == null) + throw new AbortException("No branch to push defined"); - if (b.getTargetRepoName() == null) throw new AbortException("No branch repo to push to defined"); + 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) @@ -310,24 +311,17 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build 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)); @@ -335,10 +329,11 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build } } } - + if (isPushNotes()) { for (final NoteToPush b : notesToPush) { - if (b.getnoteMsg() == null) throw new AbortException("No note to push defined"); + if (b.getnoteMsg() == null) + throw new AbortException("No note to push defined"); b.setEmptyTargetRepoToOrigin(); String noteMsgTmp = environment.expand(b.getnoteMsg()); @@ -346,9 +341,9 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build 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) { @@ -359,24 +354,23 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build // 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; } } @@ -388,7 +382,8 @@ public boolean perform(AbstractBuild build, Launcher launcher, final Build */ protected Object readResolve() { // Default unspecified to v0 - if (configVersion == null) this.configVersion = 0L; + if(configVersion == null) + this.configVersion = 0L; if (this.configVersion < 1L) { if (tagsToPush == null) { @@ -398,8 +393,8 @@ protected Object readResolve() { return this; } - - @Extension(ordinal = -1) + + @Extension(ordinal=-1) public static class DescriptorImpl extends BuildStepDescriptor { public String getDisplayName() { return "Git Publisher"; @@ -420,8 +415,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) { @@ -431,35 +426,40 @@ 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) return FormValidation.ok(); + if (remote.length() == 0 && isMerge) + return FormValidation.ok(); - FormValidation validation = checkFieldNotEmpty(remote, Messages.GitPublisher_Check_RemoteName()); - if (validation.kind != FormValidation.Kind.OK) return validation; + 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 + "'"); + return FormValidation + .error("No remote repository configured with name '" + + remote + "'"); return FormValidation.ok(); } - + public boolean isApplicable(Class jobType) { return true; } @@ -476,15 +476,15 @@ private FormValidation checkFieldNotEmpty(String value, String field) { } } - public abstract static class PushConfig extends AbstractDescribableImpl implements Serializable { + public static abstract 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; } @@ -492,10 +492,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"; } } } @@ -555,8 +555,7 @@ 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; @@ -572,6 +571,7 @@ public String getDisplayName() { } } } + public static final class NoteToPush extends PushConfig { @@ -582,24 +582,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 @@ -610,4 +612,5 @@ public String getDisplayName() { } } } + } diff --git a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java index 318c505725..29bab615a3 100644 --- a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java +++ b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java @@ -41,50 +41,51 @@ */ 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 a946d0a3ab..895e096948 100644 --- a/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java +++ b/src/main/java/hudson/plugins/git/GitRevisionTokenMacro.java @@ -29,22 +29,23 @@ 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) { @@ -52,23 +53,21 @@ 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 57b9bb4e90..8e95b481f7 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -1,29 +1,26 @@ 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; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; +import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import com.google.common.collect.Iterables; + import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; -import hudson.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; @@ -32,14 +29,13 @@ import hudson.plugins.git.extensions.impl.ChangelogToBranch; import hudson.plugins.git.extensions.impl.CloneOption; import hudson.plugins.git.extensions.impl.FirstBuildChangelog; -import hudson.plugins.git.extensions.impl.LocalBranch; import hudson.plugins.git.extensions.impl.PathRestriction; -import hudson.plugins.git.extensions.impl.PreBuildMerge; +import hudson.plugins.git.extensions.impl.LocalBranch; import hudson.plugins.git.extensions.impl.RelativeTargetDirectory; -import hudson.plugins.git.extensions.impl.ScmName; +import hudson.plugins.git.extensions.impl.PreBuildMerge; import hudson.plugins.git.opt.PreBuildMergeOptions; -import hudson.plugins.git.util.*; import hudson.plugins.git.util.Build; +import hudson.plugins.git.util.*; import hudson.remoting.Channel; import hudson.scm.AbstractScmTagAction; import hudson.scm.ChangeLogParser; @@ -54,7 +50,30 @@ import hudson.util.DescribableList; import hudson.util.FormValidation; import hudson.util.ListBoxModel; -import hudson.util.LogTaskListener; +import jenkins.model.Jenkins; +import jenkins.plugins.git.GitHooksConfiguration; +import jenkins.plugins.git.GitSCMMatrixUtil; +import jenkins.plugins.git.GitToolChooser; +import jenkins.util.SystemProperties; +import net.sf.json.JSONObject; + +import org.eclipse.jgit.errors.MissingObjectException; +import org.eclipse.jgit.lib.Config; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.transport.RefSpec; +import org.eclipse.jgit.transport.RemoteConfig; +import org.eclipse.jgit.transport.URIish; +import org.jenkinsci.plugins.gitclient.*; +import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted; +import org.jenkinsci.Symbol; +import org.kohsuke.stapler.DataBoundConstructor; +import org.kohsuke.stapler.DataBoundSetter; +import org.kohsuke.stapler.StaplerRequest; +import org.kohsuke.stapler.export.Exported; + +import javax.servlet.ServletException; + import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; @@ -76,33 +95,22 @@ 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. @@ -116,7 +124,6 @@ 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); @@ -130,21 +137,17 @@ 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 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"; @@ -157,8 +160,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 @@ -167,7 +170,8 @@ 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<>(); @@ -185,9 +189,7 @@ public GitSCM(String repositoryUrl) { this( createRepoList(repositoryUrl, null), Collections.singletonList(new BranchSpec("")), - null, - null, - Collections.emptyList()); + null, null, Collections.emptyList()); } @Deprecated @@ -226,7 +228,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. } @@ -289,6 +291,7 @@ public Object readResolve() throws IOException { } } + if (configVersion < 1 && branches != null) { // Migrate the branch specs from // single * wildcard, to ** wildcard. @@ -301,7 +304,7 @@ 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) @@ -326,11 +329,12 @@ public Object readResolve() throws IOException { } } - if (extensions == null) extensions = new DescribableList<>(Saveable.NOOP); + 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 { @@ -357,33 +361,36 @@ 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) { @@ -453,14 +460,14 @@ 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)); @@ -483,8 +490,7 @@ 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 @@ -502,8 +508,7 @@ 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); @@ -523,7 +528,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])); @@ -551,8 +556,7 @@ 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<>(); } @@ -629,16 +633,17 @@ 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); @@ -662,9 +667,7 @@ 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; } @@ -683,25 +686,17 @@ boolean requiresWorkspaceForPolling(EnvVars environment) { } @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 Jenkins ought to build ? listener.getLogger().println("Using strategy: " + getBuildChooser().getDisplayName()); @@ -718,17 +713,13 @@ private PollingResult compareRemoteRevisionWithImpl( 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); @@ -739,12 +730,12 @@ private PollingResult compareRemoteRevisionWithImpl( 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()) { @@ -757,9 +748,7 @@ private PollingResult compareRemoteRevisionWithImpl( } } 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(); } } @@ -772,13 +761,10 @@ private PollingResult compareRemoteRevisionWithImpl( // 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()); + if (matcher.matches()) name = remote + head.substring(matcher.group(1).length()); else name = remote + "/" + head; if (!branchSpec.matches(name, environment)) continue; @@ -787,15 +773,11 @@ private PollingResult compareRemoteRevisionWithImpl( 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; } } @@ -805,11 +787,9 @@ private PollingResult compareRemoteRevisionWithImpl( } 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()) { @@ -831,14 +811,8 @@ private PollingResult compareRemoteRevisionWithImpl( 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)) { @@ -865,15 +839,13 @@ private PollingResult compareRemoteRevisionWithImpl( * @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); } /** @@ -890,38 +862,23 @@ public GitClient createClient( * @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 */ @@ -943,20 +900,13 @@ private GitClient createClient( 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; } @@ -966,7 +916,7 @@ private GitClient createClient( GitClient c = git.getClient(); for (GitSCMExtension ext : extensions) { - c = ext.decorate(this, c); + c = ext.decorate(this,c); } for (UserRemoteConfig uc : getUserRemoteConfigs()) { @@ -978,15 +928,13 @@ private GitClient createClient( 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); } } } @@ -996,8 +944,9 @@ private GitClient createClient( 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 { @@ -1027,9 +976,10 @@ 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()) { @@ -1047,7 +997,7 @@ private void fetchFrom( } 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); } } } @@ -1060,7 +1010,9 @@ 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) str.add(rs.toString()); + 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); @@ -1087,7 +1039,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(); @@ -1099,12 +1051,10 @@ 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) { @@ -1113,13 +1063,11 @@ public GitTool getGitTool(Node builtOn, EnvVars env, TaskListener listener) { this.environment = environment; } - public T actOnBuild(@NonNull ContextCallable, T> callable) - throws IOException, InterruptedException { + 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 { + public T actOnProject(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException { return callable.invoke(project, FilePath.localChannel); } @@ -1136,15 +1084,13 @@ 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() { + 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()); + public T actOnProject(@NonNull ContextCallable, T> callable) throws IOException, InterruptedException { + return callable.invoke(project,Channel.current()); } public Run getBuild() { @@ -1168,13 +1114,11 @@ 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); @@ -1185,7 +1129,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 @@ -1194,38 +1138,35 @@ 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); @@ -1241,12 +1182,9 @@ 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()); } } } @@ -1260,25 +1198,25 @@ 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) log.println("Fetching changes from the remote Git repository"); - else log.println(MessageFormat.format("Fetching changes from {0} remote Git repositories", repos.size())); + if (repos.size() == 1) + log.println("Fetching changes from the remote Git repository"); + 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); } @@ -1296,7 +1234,7 @@ private void retrieveChanges(Run build, GitClient git, TaskListener listener) 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; } @@ -1336,13 +1274,7 @@ 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()) { @@ -1350,10 +1282,9 @@ public void checkout( } if (VERBOSE) - listener.getLogger() - .println("Using checkout strategy: " + getBuildChooser().getDisplayName()); + 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) { @@ -1364,12 +1295,8 @@ public void checkout( 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) { @@ -1383,14 +1310,14 @@ public void checkout( // 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 @@ -1401,7 +1328,7 @@ public void checkout( } 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); @@ -1411,25 +1338,22 @@ public void checkout( 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); @@ -1458,31 +1382,24 @@ public void checkout( } 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); } } /* 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."); } } } @@ -1555,14 +1472,7 @@ 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()); @@ -1575,8 +1485,7 @@ private void computeChangeLog( 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; @@ -1586,7 +1495,7 @@ private void computeChangeLog( if (!exclusion) { FirstBuildChangelog firstBuildChangelog = getExtensions().get(FirstBuildChangelog.class); - if (firstBuildChangelog != null && firstBuildChangelog.isMakeChangelog()) { + if (firstBuildChangelog!=null&&firstBuildChangelog.isMakeChangelog()) { changelog.to(out).max(1).execute(); executed = true; listener.getLogger().println("First time build. Latest changes added to changelog."); @@ -1617,30 +1526,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); @@ -1664,21 +1573,20 @@ public void buildEnvironment(Run build, java.util.Map env) /* 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++; } } @@ -1689,10 +1597,11 @@ 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; @@ -1701,8 +1610,7 @@ 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) { @@ -1716,8 +1624,7 @@ 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) { @@ -1732,16 +1639,10 @@ 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); } @@ -1750,14 +1651,13 @@ public ChangeLogParser createChangeLogParser() { @Symbol({"scmGit", "gitSCM"}) // Cannot use "git" because there is already a `git` pipeline step public static final class DescriptorImpl extends SCMDescriptor { - @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "Do not risk compatibility") + @SuppressFBWarnings(value="UUF_UNUSED_FIELD", justification="Do not risk compatibility") private String gitExe; - private String globalConfigName; 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; @@ -1794,9 +1694,7 @@ public boolean isShowEntireCommitSummaryInChanges() { return showEntireCommitSummaryInChanges; } - public boolean isHideCredentials() { - return hideCredentials; - } + public boolean isHideCredentials() { return hideCredentials; } public void setHideCredentials(boolean hideCredentials) { this.hideCredentials = hideCredentials; @@ -1810,8 +1708,7 @@ public String getDisplayName() { return "Git"; } - @Override - public boolean isApplicable(Job project) { + @Override public boolean isApplicable(Job project) { return true; } @@ -1820,11 +1717,7 @@ 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; } /** @@ -1832,9 +1725,7 @@ 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); } @@ -1905,29 +1796,19 @@ 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 @@ -1938,8 +1819,9 @@ public String getOldGitExe() { return null; } - 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(); @@ -1962,8 +1844,7 @@ public static List createRepositoryConfigurations( } 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 { @@ -1974,8 +1855,9 @@ public static List createRepositoryConfigurations( 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; @@ -1991,8 +1873,7 @@ public static PreBuildMergeOptions createMergeOptions( } } 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()); @@ -2003,7 +1884,8 @@ public static PreBuildMergeOptions createMergeOptions( 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; @@ -2016,7 +1898,8 @@ public FormValidation doGitRemoteNameCheck(StaplerRequest req) throws IOExceptio String[] names = req.getParameterValues("repo.name"); if (urls != null && names != null) for (String name : GitUtils.fixupNames(names, urls)) - if (name.equals(mergeRemoteName)) return FormValidation.ok(); + if (name.equals(mergeRemoteName)) + return FormValidation.ok(); return FormValidation.error("No remote repository configured with name '" + mergeRemoteName + "'"); } @@ -2032,26 +1915,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; @@ -2068,8 +1951,7 @@ 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(); @@ -2095,8 +1977,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; } } @@ -2124,11 +2006,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) return new BuildData(scmName, getUserRemoteConfigs()); + if (base==null) + return new BuildData(scmName, getUserRemoteConfigs()); else { - BuildData buildData = base.clone(); - buildData.setScmName(scmName); - return buildData; + BuildData buildData = base.clone(); + buildData.setScmName(scmName); + return buildData; } } @@ -2193,9 +2076,7 @@ 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; @@ -2203,7 +2084,7 @@ protected FilePath workingDirectory( 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; } @@ -2216,52 +2097,48 @@ protected FilePath workingDirectory( * @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) break; + 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. } } @@ -2276,7 +2153,8 @@ 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. @@ -2287,7 +2165,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); @@ -2298,12 +2176,11 @@ 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)); @@ -2316,11 +2193,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 240f23a336..89ba40779c 100644 --- a/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java +++ b/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java @@ -11,9 +11,11 @@ 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; /** @@ -30,7 +32,6 @@ public abstract class GitSCMBackwardCompatibility extends SCM implements Seriali // when writing back @Deprecated transient String source; - @Deprecated transient String branch; @@ -73,6 +74,7 @@ public abstract class GitSCMBackwardCompatibility extends SCM implements Seriali @Deprecated private transient Boolean skipTag; + /** * @deprecated * Moved to {@link SubmoduleOption} @@ -199,12 +201,13 @@ 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() { @@ -213,8 +216,7 @@ 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; } @@ -222,17 +224,15 @@ 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,75 @@ 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) getExtensions().add(ext); + 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 +354,38 @@ 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 +395,7 @@ public UserMergeOptions getUserMergeOptions() { */ @Deprecated public boolean getClean() { - return getExtensions().get(CleanCheckout.class) != null; + return getExtensions().get(CleanCheckout.class)!=null; } /** @@ -405,7 +405,7 @@ public boolean getClean() { */ @Deprecated public boolean getWipeOutWorkspace() { - return getExtensions().get(WipeWorkspace.class) != null; + return getExtensions().get(WipeWorkspace.class)!=null; } /** @@ -416,7 +416,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 +427,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 +437,7 @@ public String getReference() { */ @Deprecated public boolean getRemotePoll() { - return getExtensions().get(DisableRemotePoll.class) == null; + return getExtensions().get(DisableRemotePoll.class)==null; } /** @@ -450,7 +450,7 @@ public boolean getRemotePoll() { */ @Deprecated public boolean getAuthorOrCommitter() { - return getExtensions().get(AuthorInChangelog.class) != null; + return getExtensions().get(AuthorInChangelog.class)!=null; } /** @@ -460,7 +460,7 @@ public boolean getAuthorOrCommitter() { */ @Deprecated public boolean isIgnoreNotifyCommit() { - return getExtensions().get(IgnoreNotifyCommit.class) != null; + return getExtensions().get(IgnoreNotifyCommit.class)!=null; } /** @@ -471,7 +471,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,8 +482,9 @@ 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 13070b0b11..29e3b824cb 100644 --- a/src/main/java/hudson/plugins/git/GitStatus.java +++ b/src/main/java/hudson/plugins/git/GitStatus.java @@ -1,8 +1,5 @@ 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; @@ -22,12 +19,16 @@ 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.model.ParameterizedJobMixIn; 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.*; @@ -61,9 +62,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,18 +114,13 @@ 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"); @@ -132,19 +128,15 @@ public HttpResponse doNotifyCommit( } 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); @@ -162,11 +154,8 @@ public HttpResponse doNotifyCommit( 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])); } } @@ -215,14 +204,14 @@ public HttpResponse doNotifyCommit( * @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; } @@ -239,7 +228,8 @@ 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. @@ -259,7 +249,8 @@ 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) { + } } /** @@ -267,7 +258,7 @@ public void writeBody(PrintWriter w) {} * * @since 1.4.1 */ - public abstract static class Listener implements ExtensionPoint { + public static abstract class Listener implements ExtensionPoint { /** * @deprecated implement {@link #onNotifyCommit(org.eclipse.jgit.transport.URIish, String, List, String...)} @@ -307,8 +298,7 @@ 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); } @@ -327,14 +317,15 @@ public List onNotifyCommit( * @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); } + + } /** @@ -350,14 +341,11 @@ 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(); @@ -367,7 +355,8 @@ public List onNotifyCommit( // 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"); @@ -378,8 +367,7 @@ public List onNotifyCommit( if (scmTriggerItem == null) { continue; } - SCMS: - for (SCM scm : scmTriggerItem.getSCMs()) { + SCMS: for (SCM scm : scmTriggerItem.getSCMs()) { if (!(scm instanceof GitSCM)) { continue; } @@ -387,7 +375,8 @@ public List onNotifyCommit( 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)) { @@ -397,34 +386,28 @@ public List onNotifyCommit( } } - 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; @@ -432,12 +415,7 @@ public List onNotifyCommit( 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; @@ -448,22 +426,19 @@ public List onNotifyCommit( } if (!branchFound) continue; urlFound = true; - if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob - && ((ParameterizedJobMixIn.ParameterizedJob) project).isDisabled())) { - // JENKINS-30178 Add default parameters defined in the job + if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob && ((ParameterizedJobMixIn.ParameterizedJob) project).isDisabled())) { + //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); @@ -475,14 +450,10 @@ public List onNotifyCommit( * 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 @@ -490,26 +461,23 @@ public List onNotifyCommit( * 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; @@ -521,12 +489,12 @@ public List onNotifyCommit( * 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 { @@ -536,7 +504,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); @@ -665,8 +633,7 @@ 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]"); @@ -674,8 +641,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()); @@ -698,10 +665,8 @@ 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. @@ -719,10 +684,8 @@ 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; } @@ -749,6 +712,5 @@ 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 429ef02329..72ac266b44 100644 --- a/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java +++ b/src/main/java/hudson/plugins/git/GitStatusCrumbExclusion.java @@ -2,11 +2,12 @@ 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 425a13959c..cc31924127 100644 --- a/src/main/java/hudson/plugins/git/GitTagAction.java +++ b/src/main/java/hudson/plugins/git/GitTagAction.java @@ -8,10 +8,6 @@ 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; @@ -21,6 +17,11 @@ 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 */ @@ -64,7 +65,8 @@ public boolean isTagged() { @Override public String getIconFileName() { - if (!isTagged() && !getACL().hasPermission(getPermission())) return null; + if (!isTagged() && !getACL().hasPermission(getPermission())) + return null; return "save.gif"; } @@ -74,12 +76,16 @@ public String getDisplayName() { for (List v : tags.values()) { if (!v.isEmpty()) { nonNullTag += v.size(); - if (nonNullTag > 1) break; + if (nonNullTag > 1) + break; } } - if (nonNullTag == 0) return "No Tags"; - if (nonNullTag == 1) return "One tag"; - else return "Multiple tags"; + if (nonNullTag == 0) + return "No Tags"; + if (nonNullTag == 1) + return "One tag"; + else + return "Multiple tags"; } /** @@ -95,7 +101,8 @@ public List getTagInfo() { List data = new ArrayList<>(); for (Map.Entry> e : tags.entrySet()) { String module = e.getKey(); - for (String tag : e.getValue()) data.add(new TagInfo(module, tag)); + for (String tag : e.getValue()) + data.add(new TagInfo(module, tag)); } return data; } @@ -181,14 +188,16 @@ void scheduleTagCreation(Map newTags, String comment) throws IOE public 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; } protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) throws IOException, InterruptedException { - return Git.with(listener, environment).in(workspace).getClient(); + return Git.with(listener, environment) + .in(workspace) + .getClient(); } @Override @@ -199,8 +208,9 @@ protected void perform(final TaskListener listener) throws Exception { 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(); @@ -209,7 +219,8 @@ protected void perform(final TaskListener listener) throws Exception { 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 @@ -219,6 +230,7 @@ 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 36d3deb898..3b61acdd5c 100644 --- a/src/main/java/hudson/plugins/git/ObjectIdConverter.java +++ b/src/main/java/hudson/plugins/git/ObjectIdConverter.java @@ -30,38 +30,43 @@ public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return ObjectId.class == type; } - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + 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)) return legacyUnmarshal(reader, context); + 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 774773f7e0..cf95e3eebb 100644 --- a/src/main/java/hudson/plugins/git/RemoteConfigConverter.java +++ b/src/main/java/hudson/plugins/git/RemoteConfigConverter.java @@ -12,6 +12,9 @@ import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.eclipse.jgit.lib.Config; +import org.eclipse.jgit.transport.RemoteConfig; + import java.io.*; import java.net.URISyntaxException; import java.util.ArrayList; @@ -19,8 +22,6 @@ 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,7 +32,8 @@ 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,16 +67,23 @@ public RemoteConfigProxy() { } public String getString(String section, String subsection, String name) { - if (KEY_UPLOADPACK.equals(name)) return uploadpack; - if (KEY_RECEIVEPACK.equals(name)) return receivepack; - if (KEY_TAGOPT.equals(name)) return tagopt; + if (KEY_UPLOADPACK.equals(name)) + return uploadpack; + if (KEY_RECEIVEPACK.equals(name)) + return receivepack; + 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)) return uris; - if (KEY_FETCH.equals(name)) return fetch; - if (KEY_PUSH.equals(name)) return push; + public String[] getStringList(String section, String subsection, + String name) { + if (KEY_URL.equals(name)) + return uris; + if (KEY_FETCH.equals(name)) + return fetch; + if (KEY_PUSH.equals(name)) + return push; return super.getStringList(section, subsection, name); } @@ -84,32 +93,36 @@ private void fromMap(Map> map) { Collection values = entry.getValue(); 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; + } } } - @SuppressFBWarnings(value = "SE_PREVENT_EXT_OBJ_OVERWRITE", justification = "Used during version upgrade") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + @SuppressFBWarnings(value="SE_PREVENT_EXT_OBJ_OVERWRITE", justification="Used during version upgrade") + public void readExternal(ObjectInput in) throws IOException, + ClassNotFoundException { name = in.readUTF(); final int items = in.readInt(); Map> map = new HashMap<>(); @@ -140,13 +153,14 @@ 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; } @@ -154,29 +168,32 @@ public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { return RemoteConfig.class == type; } - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + 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() { public Object readFromStream() { @@ -197,7 +214,8 @@ public void defaultReadObject() { throw new UnsupportedOperationException(); } - public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { + public void registerValidation(ObjectInputValidation validation, + int priority) throws NotActiveException { throw new NotActiveException(); } @@ -207,7 +225,8 @@ public void close() { }; try { @SuppressWarnings("deprecation") - CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback); + CustomObjectInputStream objectInput = CustomObjectInputStream + .getInstance(context, callback); proxy.readExternal(objectInput); objectInput.popCallback(); return proxy.toRemote(); @@ -216,8 +235,10 @@ public void close() { } } - public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) { - if (isLegacyNode(reader, context)) return legacyUnmarshal(reader, context); + 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 2fde7756e1..7af792adec 100644 --- a/src/main/java/hudson/plugins/git/RevisionParameterAction.java +++ b/src/main/java/hudson/plugins/git/RevisionParameterAction.java @@ -29,27 +29,29 @@ import hudson.model.Queue; import hudson.model.Queue.QueueAction; import hudson.model.queue.FoldableAction; -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; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + + /** * Used as a build parameter to specify the revision to be built. * * @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; @@ -72,17 +74,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 { @@ -90,15 +92,16 @@ 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; } @@ -152,30 +155,32 @@ 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} - */ + */ 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) return false; + if(otherActions.size() != 0) + return false; } else { - for (RevisionParameterAction action : otherActions) { - if (this.commit.equals(action.commit)) return false; + 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 @@ -188,8 +193,8 @@ public boolean shouldSchedule(List actions) { */ 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 ca8760ca59..58481a0a34 100644 --- a/src/main/java/hudson/plugins/git/SubmoduleCombinator.java +++ b/src/main/java/hudson/plugins/git/SubmoduleCombinator.java @@ -1,48 +1,50 @@ 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 org.jenkinsci.plugins.gitclient.GitClient; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * 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 93758a0dcb..ae830cda1a 100644 --- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java +++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java @@ -1,10 +1,12 @@ package hudson.plugins.git; -import java.util.Collection; -import java.util.Collections; import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted; import org.kohsuke.stapler.DataBoundConstructor; + +import java.util.Collection; +import java.util.Collections; + /** * Deprecated data class used in a submodule configuration experiment. * Deprecated as inaccessible in git plugin 4.6.0. Class retained for @@ -16,30 +18,34 @@ 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 3f3fe7d1c3..e4ff9915a2 100644 --- a/src/main/java/hudson/plugins/git/UserMergeOptions.java +++ b/src/main/java/hudson/plugins/git/UserMergeOptions.java @@ -5,15 +5,16 @@ 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; /** @@ -21,7 +22,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; @@ -45,10 +46,7 @@ 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; @@ -66,11 +64,7 @@ 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()); } /** @@ -107,20 +101,21 @@ public String getRef() { } public MergeCommand.Strategy getMergeStrategy() { - for (MergeCommand.Strategy strategy : MergeCommand.Strategy.values()) - if (strategy.toString().equals(mergeStrategy)) return strategy; + 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)) return ffMode; + if (ffMode.equals(fastForwardMode)) + return ffMode; return MergeCommand.GitPluginFastForwardMode.FF; } @@ -131,11 +126,12 @@ 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 @@ -177,5 +173,7 @@ 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 90b3ccd128..6f1dd6e33b 100644 --- a/src/main/java/hudson/plugins/git/UserRemoteConfig.java +++ b/src/main/java/hudson/plugins/git/UserRemoteConfig.java @@ -1,8 +1,5 @@ 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; @@ -15,7 +12,6 @@ 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; @@ -24,23 +20,28 @@ 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 @@ -90,15 +91,16 @@ public String toString() { return getRefspec() + " => " + getUrl() + " (" + getName() + ")"; } - private static final Pattern SCP_LIKE = Pattern.compile("(.*):(.*)"); + private final static 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) { @@ -121,10 +123,11 @@ public ListBoxModel doFillCredentialsIdItems( .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(); } @@ -145,12 +148,12 @@ public FormValidation doCheckCredentialsId( { return FormValidation.ok(); } - for (ListBoxModel.Option o : CredentialsProvider.listCredentialsInItem( - StandardUsernameCredentials.class, - project, - project instanceof Queue.Task ? Tasks.getAuthenticationOf2((Queue.Task) project) : ACL.SYSTEM2, - GitURIRequirementsBuilder.fromUri(url).build(), - GitClient.CREDENTIALS_MATCHER)) { + for (ListBoxModel.Option o : CredentialsProvider + .listCredentialsInItem(StandardUsernameCredentials.class, project, project instanceof Queue.Task + ? Tasks.getAuthenticationOf2((Queue.Task) project) + : ACL.SYSTEM2, + 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 @@ -164,21 +167,20 @@ public FormValidation doCheckCredentialsId( } @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) return FormValidation.error(Messages.UserRemoteConfig_CheckUrl_UrlIsNull()); + if (url == null) + return FormValidation.error(Messages.UserRemoteConfig_CheckUrl_UrlIsNull()); if (url.indexOf('$') >= 0) // set by variable, can't validate @@ -224,18 +226,18 @@ public FormValidation doCheckUrl( * @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(); } @@ -245,7 +247,7 @@ public FormValidation doCheckRefspec( 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) { @@ -255,17 +257,11 @@ public FormValidation doCheckRefspec( return FormValidation.ok(); } - private static StandardCredentials lookupCredentials( - @CheckForNull Item project, String credentialId, String uri) { - return (credentialId == null) - ? null - : CredentialsMatchers.firstOrNull( - CredentialsProvider.lookupCredentialsInItem( - StandardCredentials.class, - project, - ACL.SYSTEM2, - 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.lookupCredentialsInItem(StandardCredentials.class, project, ACL.SYSTEM2, + 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 7f1025086c..243df70372 100644 --- a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java +++ b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -13,18 +11,21 @@ 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 org.kohsuke.stapler.interceptor.RequirePOST; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import javax.servlet.ServletException; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; /** * AssemblaWeb Git Browser URLs @@ -95,20 +96,19 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public AssemblaWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 @@ -129,8 +129,7 @@ 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 d49f06c27f..421c642305 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java @@ -1,19 +1,20 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser URLs for on-premise Bitbucket Server installation. */ @@ -42,15 +43,14 @@ 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(); @@ -71,8 +71,7 @@ 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> { @NonNull public String getDisplayName() { @@ -80,9 +79,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public BitbucketServer newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 d980140acc..d43cad8861 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java @@ -1,19 +1,20 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser URLs */ @@ -42,15 +43,14 @@ 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(); @@ -80,11 +80,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public BitbucketWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 6492bb785e..52c31f32a0 100644 --- a/src/main/java/hudson/plugins/git/browser/CGit.java +++ b/src/main/java/hudson/plugins/git/browser/CGit.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -9,13 +7,16 @@ 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser URLs */ @@ -58,8 +59,7 @@ 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())); } /** @@ -75,12 +75,9 @@ 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()))); } } @@ -93,9 +90,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public CGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 f3b6429342..e81322bc6b 100644 --- a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -10,115 +8,121 @@ 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 org.kohsuke.stapler.interceptor.RequirePOST; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import javax.servlet.ServletException; +import java.io.IOException; +import java.net.URL; +import java.util.regex.Pattern; 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 - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) - throws FormException { - 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> { + + @NonNull + public String getDisplayName() { + return "FishEye"; + } + + @Override + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public FisheyeGitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { + 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 1195ebdc7d..7e2c616ae8 100644 --- a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -13,19 +11,22 @@ 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 org.kohsuke.stapler.interceptor.RequirePOST; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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; public class GitBlitRepositoryBrowser extends GitRepositoryBrowser { @@ -42,12 +43,8 @@ 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())); } @@ -57,27 +54,22 @@ 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"); } @@ -90,24 +82,23 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) - throws FormException { + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public GitBlitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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() { diff --git a/src/main/java/hudson/plugins/git/browser/GitLab.java b/src/main/java/hudson/plugins/git/browser/GitLab.java index a3c5d1ad6e..3ffc881127 100644 --- a/src/main/java/hudson/plugins/git/browser/GitLab.java +++ b/src/main/java/hudson/plugins/git/browser/GitLab.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -9,16 +7,22 @@ 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.QueryParameter; import org.kohsuke.stapler.StaplerRequest; +import java.io.IOException; +import java.net.URL; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import javax.servlet.ServletException; + +import org.kohsuke.stapler.QueryParameter; + /** * Git Browser for GitLab */ @@ -139,9 +143,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitLab newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { return req.bindJSON(GitLab.class, jsonObject); } @@ -169,10 +172,11 @@ 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 7980e46470..4648f56ffd 100644 --- a/src/main/java/hudson/plugins/git/browser/GitList.java +++ b/src/main/java/hudson/plugins/git/browser/GitList.java @@ -1,20 +1,22 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser URLs */ @@ -43,10 +45,8 @@ 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); @@ -60,7 +60,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))); } @@ -92,9 +92,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitList newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 66d63d350c..814d8ce19d 100644 --- a/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java @@ -1,6 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.EnvVars; import hudson.model.Item; import hudson.model.Job; @@ -8,6 +7,10 @@ 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; @@ -21,8 +24,8 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; -import org.kohsuke.stapler.Stapler; -import org.kohsuke.stapler.StaplerRequest; + +import edu.umd.cs.findbugs.annotations.CheckForNull; public abstract class GitRepositoryBrowser extends RepositoryBrowser { @@ -30,7 +33,8 @@ public abstract class GitRepositoryBrowser extends RepositoryBrowser> { @@ -65,20 +70,18 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Gitiles newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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)) { @@ -87,7 +90,8 @@ public FormValidation doCheckRepoUrl( return new URLCheck() { protected FormValidation check() throws IOException, ServletException { String v = cleanUrl; - if (!v.endsWith("/")) v += '/'; + 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 36f579d664..b9faa07be4 100644 --- a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java +++ b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java @@ -1,19 +1,20 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser for Gitorious */ @@ -33,9 +34,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,14 +44,13 @@ 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 @@ -74,11 +74,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GitoriousWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 238854214f..0e5f31008a 100644 --- a/src/main/java/hudson/plugins/git/browser/GogsGit.java +++ b/src/main/java/hudson/plugins/git/browser/GogsGit.java @@ -1,20 +1,22 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * @author Norbert Lange (nolange79@gmail.com) */ @@ -51,9 +53,7 @@ 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; } @@ -87,8 +87,7 @@ 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())); } } @@ -101,9 +100,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public GogsGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 7fbb9cc40e..53d879c13d 100644 --- a/src/main/java/hudson/plugins/git/browser/KilnGit.java +++ b/src/main/java/hudson/plugins/git/browser/KilnGit.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -9,13 +7,17 @@ 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * @author Chris Klaiber (cklaiber@gmail.com) */ @@ -56,9 +58,7 @@ 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; } @@ -98,9 +98,7 @@ 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()))); } } @@ -113,9 +111,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public KilnGit newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 00e4858ff2..fd18751715 100644 --- a/src/main/java/hudson/plugins/git/browser/Phabricator.java +++ b/src/main/java/hudson/plugins/git/browser/Phabricator.java @@ -1,19 +1,20 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser for Phabricator */ @@ -89,9 +90,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Phabricator newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 d334cceab2..5820fac961 100644 --- a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java +++ b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java @@ -1,23 +1,24 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Git Browser for Redmine. - * + * * @author mfriedenhagen */ public class RedmineWeb extends GitRepositoryBrowser { @@ -37,13 +38,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 +68,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 @@ -92,11 +93,11 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public RedmineWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 9c8840a27d..73356106d6 100644 --- a/src/main/java/hudson/plugins/git/browser/RhodeCode.java +++ b/src/main/java/hudson/plugins/git/browser/RhodeCode.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -9,13 +7,16 @@ 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * RhodeCode Browser URLs */ @@ -58,11 +59,7 @@ 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"); } /** @@ -98,9 +95,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public RhodeCode newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 aacc5bdee8..b4fa048690 100644 --- a/src/main/java/hudson/plugins/git/browser/Stash.java +++ b/src/main/java/hudson/plugins/git/browser/Stash.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.Descriptor; import hudson.plugins.git.GitChangeSet; @@ -9,12 +7,15 @@ 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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URL; + /** * Stash Browser URLs */ @@ -59,17 +60,9 @@ 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())); } } @@ -87,18 +80,14 @@ 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> { @NonNull public String getDisplayName() { @@ -106,9 +95,8 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public Stash newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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 d203f12f84..a76a8e51d3 100644 --- a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.AbstractProject; @@ -10,20 +8,23 @@ 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 org.kohsuke.stapler.interceptor.RequirePOST; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import javax.servlet.ServletException; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.regex.Pattern; /** * Browser for Git repositories on Microsoft Team Foundation Server (TFS) 2013 and higher versions using the @@ -38,15 +39,13 @@ 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)); } @@ -57,10 +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("/")) return normalizeToEndWithSlash(getResultFromNamedRepository(changeSet)); + + else if (!result.contains("/")) + return normalizeToEndWithSlash(getResultFromNamedRepository(changeSet)); return getUrl(); } @@ -76,8 +77,7 @@ 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(); } @@ -86,20 +86,16 @@ 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"; @NonNull public String getDisplayName() { return REPOSITORY_BROWSER_LABEL; } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") - public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) - throws FormException { + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") + public TFS2013GitRepositoryBrowser newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { try { req.getSubmittedForm(); } catch (ServletException e) { @@ -117,27 +113,27 @@ 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)) return FormValidation.ok(); + if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) + return FormValidation.ok(); if (value == null) // nothing entered yet - value = "origin"; + 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) + ""); - + return FormValidation.errorWithMarkup("There is no remote with the name " + Util.escape(value) + ""); + value = remote.getURIs().get(0).toString(); } - - if (!value.endsWith("/")) value += '/'; + + if (!value.endsWith("/")) + value += '/'; if (!URL_PATTERN.matcher(value).matches()) return FormValidation.errorWithMarkup("The URL should end like .../_git/foobar/"); @@ -149,8 +145,7 @@ 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 dcd778be74..af62841ad1 100644 --- a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java +++ b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; @@ -14,19 +12,22 @@ 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 org.kohsuke.stapler.interceptor.RequirePOST; + +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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; public class ViewGitWeb extends GitRepositoryBrowser { @@ -45,7 +46,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,30 +58,18 @@ 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) { @@ -100,28 +89,28 @@ public String getDisplayName() { } @Override - @SuppressFBWarnings( - value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", - justification = "Inherited javadoc commits that req is non-null") + @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", + justification = "Inherited javadoc commits that req is non-null") public ViewGitWeb newInstance(StaplerRequest req, @NonNull JSONObject jsonObject) throws FormException { 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)) return FormValidation.ok(); + if (initialChecksAndReturnOk(project, cleanUrl)) + return FormValidation.ok(); if (!validateUrl(cleanUrl)) { return FormValidation.error(Messages.invalidUrl()); } return new URLCheck() { protected FormValidation check() throws IOException, ServletException { String v = cleanUrl; - if (!v.endsWith("/")) v += '/'; + 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 3360035aa3..caa113847e 100644 --- a/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java +++ b/src/main/java/hudson/plugins/git/browser/casc/GitLabConfigurator.java @@ -10,9 +10,10 @@ 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 { @@ -57,4 +58,5 @@ 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 6d5f7f2d28..64986d9d1e 100644 --- a/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java +++ b/src/main/java/hudson/plugins/git/extensions/FakeGitSCMExtension.java @@ -15,4 +15,5 @@ * @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 2dfa2a180b..e1818caa37 100644 --- a/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java +++ b/src/main/java/hudson/plugins/git/extensions/GitClientConflictException.java @@ -3,4 +3,5 @@ /** * @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 930eb05407..6a8b07dcaf 100644 --- a/src/main/java/hudson/plugins/git/extensions/GitClientType.java +++ b/src/main/java/hudson/plugins/git/extensions/GitClientType.java @@ -1,8 +1,8 @@ package hudson.plugins.git.extensions; /** - * @author Nicolas De Loof - */ +* @author Nicolas De Loof +*/ public enum GitClientType { JGIT { @Override @@ -10,15 +10,13 @@ public GitClientType combine(GitClientType c) throws 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(); 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 e29b38f057..98180eee62 100644 --- a/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java +++ b/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java @@ -25,6 +25,7 @@ import java.io.File; import java.io.IOException; import java.util.Map; + import org.jenkinsci.plugins.gitclient.*; /** @@ -61,13 +62,9 @@ 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; } @@ -84,9 +81,7 @@ public Boolean isRevExcluded( * @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); } @@ -94,18 +89,8 @@ public FilePath getWorkingDirectory( } @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; @@ -150,30 +135,17 @@ public FilePath getWorkingDirectory( * @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; @@ -190,24 +162,15 @@ public Revision decorateRevisionToBuild( * @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); } } @@ -228,24 +191,15 @@ 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); } } @@ -260,7 +214,8 @@ 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. @@ -281,7 +236,9 @@ 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. @@ -294,27 +251,15 @@ 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); } } @@ -331,8 +276,8 @@ public void decorateCloneCommand( * @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. @@ -345,8 +290,7 @@ 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); } @@ -362,27 +306,15 @@ public void decorateFetchCommand( * @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); } } @@ -398,27 +330,15 @@ public void decorateMergeCommand( * @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); } } @@ -428,7 +348,7 @@ public void decorateCheckoutCommand( * @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 33791e9252..c3b7cfb4a0 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 0e834eaef6..0b8d1b49a6 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/AuthorInChangelog.java @@ -15,7 +15,8 @@ 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 e1852b296d..cd7b59b26e 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,10 @@ import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserDescriptor; import hudson.plugins.git.util.DefaultBuildChooser; -import java.util.List; import org.kohsuke.stapler.DataBoundConstructor; +import java.util.List; + /** * Holds {@link BuildChooser}. * @@ -24,7 +25,8 @@ public BuildChooserSetting(BuildChooser buildChooser) { } public BuildChooser getBuildChooser() { - if (buildChooser == null) buildChooser = new DefaultBuildChooser(); + 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 06d13c4ed7..c83608b9a6 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnly.java @@ -13,7 +13,8 @@ */ 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 eb50570a6f..06d7fc96af 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/ChangelogToBranch.java @@ -1,11 +1,12 @@ 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 9162c8400d..7f28763c76 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/CheckoutOption.java @@ -1,6 +1,5 @@ package hudson.plugins.git.extensions.impl; -import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.BuildListener; @@ -13,11 +12,12 @@ 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. @@ -41,9 +41,7 @@ public Integer getTimeout() { * {@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); } @@ -57,9 +55,7 @@ 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); } @@ -93,7 +89,9 @@ public int hashCode() { */ @Override public String toString() { - return "CheckoutOption{" + "timeout=" + timeout + '}'; + return "CheckoutOption{" + + "timeout=" + timeout + + '}'; } @Extension @@ -108,4 +106,5 @@ 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 32d6a449fa..beac934486 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckout.java @@ -8,6 +8,7 @@ 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; @@ -23,7 +24,8 @@ public class CleanBeforeCheckout extends GitSCMExtension { private boolean deleteUntrackedNestedRepositories; @DataBoundConstructor - public CleanBeforeCheckout() {} + public CleanBeforeCheckout() { + } public boolean isDeleteUntrackedNestedRepositories() { return deleteUntrackedNestedRepositories; @@ -39,8 +41,7 @@ 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 @@ -77,7 +78,9 @@ 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 01517cba82..aad2315994 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/CleanCheckout.java @@ -9,6 +9,7 @@ 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; @@ -23,7 +24,8 @@ public class CleanCheckout extends GitSCMExtension { private boolean deleteUntrackedNestedRepositories; @DataBoundConstructor - public CleanCheckout() {} + public CleanCheckout() { + } public boolean isDeleteUntrackedNestedRepositories() { return deleteUntrackedNestedRepositories; @@ -38,8 +40,7 @@ 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 @@ -76,7 +77,9 @@ 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 fd77710445..0ff34dbe41 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/CloneOption.java @@ -1,7 +1,5 @@ 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; @@ -21,14 +19,16 @@ 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,9 +131,7 @@ 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; @@ -170,7 +168,7 @@ public void decorateCloneCommand( 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)); @@ -193,8 +191,7 @@ 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; @@ -228,6 +225,7 @@ public GitClientType getRequiredClient() { return GitClientType.GITCLI; } + /** * {@inheritDoc} */ @@ -263,13 +261,14 @@ 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 @@ -283,4 +282,5 @@ 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 a0ddae0857..a90c3d74c4 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/DisableRemotePoll.java @@ -13,7 +13,8 @@ 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 9f49b804b6..e122d14179 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/GitLFSPull.java @@ -1,6 +1,5 @@ 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,11 +10,12 @@ 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,15 +24,14 @@ */ 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 969d0b0934..edcbd1f5f7 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommit.java @@ -12,7 +12,8 @@ */ 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 919e10d7fa..b099db234e 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.Symbol; import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted; +import org.jenkinsci.Symbol; 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,10 +65,8 @@ 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 1819464ccf..e725086c66 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/MessageExclusion.java @@ -11,76 +11,67 @@ import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; import hudson.plugins.git.util.BuildData; import hudson.util.FormValidation; -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; +import java.io.IOException; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + /** * {@link GitSCMExtension} that ignores commits with specific messages. * * @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 12dfa45b3f..8ca160ca5a 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java @@ -9,13 +9,14 @@ 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. @@ -29,7 +30,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() { @@ -66,12 +67,14 @@ private String[] normalize(String s) { } private List getIncludedPatterns() { - if (includedPatterns == null) includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized()); + if (includedPatterns==null) + includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized()); return includedPatterns; } private List getExcludedPatterns() { - if (excludedPatterns == null) excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized()); + if (excludedPatterns==null) + excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized()); return excludedPatterns; } @@ -90,14 +93,11 @@ 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,15 +133,14 @@ public Boolean isRevExcluded( } 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 ff22dc34cd..fc57243a00 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/PerBuildTag.java @@ -7,11 +7,12 @@ import hudson.plugins.git.GitSCM; 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.GitClient; +import org.jenkinsci.Symbol; import org.kohsuke.stapler.DataBoundConstructor; +import java.io.IOException; + /** * Tags every build. * @@ -19,11 +20,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 e7505c5aaa..859c7dce14 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/PreBuildMerge.java @@ -1,16 +1,11 @@ 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; @@ -19,9 +14,6 @@ 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; @@ -29,6 +21,15 @@ 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. @@ -43,7 +44,7 @@ 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; } @@ -53,48 +54,41 @@ 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)) return rev; + 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); + 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()) ext.decorateMergeCommand(scm, build, git, listener, cmd); + 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); + 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 @@ -102,14 +96,14 @@ public Revision decorateRevisionToBuild( 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 @@ -119,22 +113,19 @@ public Revision decorateRevisionToBuild( 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()); } @@ -176,7 +167,9 @@ 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 b087d56add..fccec00ddb 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 e46f77319c..70815d5dbe 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/PruneStaleTag.java @@ -32,13 +32,14 @@ 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.Map.Entry; import java.util.Objects; -import net.sf.json.JSONObject; +import java.util.Map.Entry; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; @@ -85,9 +86,11 @@ 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; @@ -113,8 +116,7 @@ public void decorateFetchCommand( 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 e6d10e5fe5..2f93739a34 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,10 @@ import hudson.plugins.git.Messages; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; -import java.io.IOException; import org.kohsuke.stapler.DataBoundConstructor; +import java.io.IOException; + /** * Instead of checking out to the top of the workspace, check out somewhere else. * @@ -33,9 +34,7 @@ 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 a5ccf4012e..c07399ca21 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java @@ -6,21 +6,19 @@ 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; @@ -64,15 +62,14 @@ public String apply(@NonNull SparseCheckoutPath sparseCheckoutPath) { } } - public Descriptor getDescriptor() { + 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 e7170961af..0a8796f1d7 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPaths.java @@ -1,7 +1,6 @@ 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; @@ -9,16 +8,18 @@ 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; @@ -34,18 +35,14 @@ 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)); } @@ -70,11 +67,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()); } @@ -86,12 +83,14 @@ 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 7b34bf28fa..94ecfe6878 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/SubmoduleOption.java @@ -1,6 +1,5 @@ package hudson.plugins.git.extensions.impl; -import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; @@ -12,13 +11,14 @@ 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,12 +45,10 @@ 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; @@ -60,13 +58,7 @@ 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; @@ -179,8 +171,7 @@ 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 { @@ -258,16 +249,7 @@ 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); } /** @@ -275,16 +257,17 @@ 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 2b77a835ca..d4c36965cf 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/UserExclusion.java @@ -3,18 +3,19 @@ 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. @@ -55,17 +56,13 @@ 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 96b6a9c39b..cbad3a0988 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/UserIdentity.java @@ -1,7 +1,5 @@ package hudson.plugins.git.extensions.impl; -import static hudson.Util.fixEmptyAndTrim; - import hudson.Extension; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; @@ -13,6 +11,8 @@ 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,7 +67,8 @@ 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); } /** @@ -83,7 +84,10 @@ public int hashCode() { */ @Override public String toString() { - return "UserIdentity{" + "name='" + name + '\'' + ", email='" + email + '\'' + '}'; + return "UserIdentity{" + + "name='" + name + '\'' + + ", email='" + email + '\'' + + '}'; } /** @@ -94,13 +98,13 @@ 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 aac7d0ae55..45c9c415ac 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 0b7801fe80..798aba91d7 100644 --- a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java +++ b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java @@ -1,12 +1,13 @@ package hudson.plugins.git.opt; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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.) * @@ -19,22 +20,26 @@ public class PreBuildMergeOptions implements Serializable { /** * Remote repository that contains the {@linkplain #mergeTarget ref}. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public RemoteConfig mergeRemote = null; /** * Remote ref to merge. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public String mergeTarget = null; /** * Merge strategy. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public String mergeStrategy = MergeCommand.Strategy.DEFAULT.toString(); - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public MergeCommand.GitPluginFastForwardMode fastForwardMode = MergeCommand.GitPluginFastForwardMode.FF; public RemoteConfig getMergeRemote() { @@ -56,8 +61,9 @@ public void setMergeTarget(String mergeTarget) { @Exported public MergeCommand.Strategy getMergeStrategy() { - for (MergeCommand.Strategy strategy : MergeCommand.Strategy.values()) - if (strategy.toString().equals(mergeStrategy)) return strategy; + for (MergeCommand.Strategy strategy: MergeCommand.Strategy.values()) + if (strategy.toString().equals(mergeStrategy)) + return strategy; return MergeCommand.Strategy.DEFAULT; } @@ -68,12 +74,13 @@ public void setMergeStrategy(MergeCommand.Strategy mergeStrategy) { @Exported public MergeCommand.GitPluginFastForwardMode getFastForwardMode() { for (MergeCommand.GitPluginFastForwardMode ffMode : MergeCommand.GitPluginFastForwardMode.values()) - if (ffMode == fastForwardMode) return ffMode; + 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 e1e0e4db47..e3af18e6e0 100644 --- a/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java @@ -1,62 +1,59 @@ 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)) { @@ -96,62 +93,63 @@ public Collection getCandidateRevisions( .filter(IOException.class::isInstance) .map(IOException.class::cast) .iterator(); - if (ioeIter.hasNext()) throw ioeIter.next(); - else throw Throwables.propagate(e); + if (ioeIter.hasNext()) + throw ioeIter.next(); + 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 @@ -159,6 +157,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 72c44841e5..4a17cb71ae 100644 --- a/src/main/java/hudson/plugins/git/util/Build.java +++ b/src/main/java/hudson/plugins/git/util/Build.java @@ -4,13 +4,14 @@ import hudson.model.Result; import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; -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; +import java.io.IOException; +import java.io.Serializable; +import java.util.Objects; + /** * Remembers which build built which {@link Revision}. * @@ -38,7 +39,8 @@ public class Build implements Serializable, Cloneable { * to the same value as {@link #revision}, as we want to be able to build two pull requests rooted at the same * commit in the base repository. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public Revision marked; /** @@ -49,8 +51,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. @@ -62,7 +64,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() { @@ -119,12 +121,15 @@ 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) clone.revision = revision.clone(); - if (marked != null) clone.marked = marked.clone(); + if (revision != null) + clone.revision = revision.clone(); + if (marked != null) + clone.marked = marked.clone(); return clone; } @@ -133,8 +138,8 @@ public boolean isFor(String sha1) { } public Object readResolve() throws IOException { - if (marked == null) // this field was introduced later than 'revision' - marked = 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 4a600c9c29..d574f3d775 100644 --- a/src/main/java/hudson/plugins/git/util/BuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/BuildChooser.java @@ -7,18 +7,19 @@ 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 @@ -78,14 +79,10 @@ 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; @@ -121,18 +118,13 @@ public Collection getCandidateRevisions( * @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)} @@ -151,13 +143,8 @@ public Collection getCandidateRevisions( * @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"); } @@ -204,9 +191,7 @@ 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); @@ -238,10 +223,8 @@ public Build prevBuildForChangelog( * @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); } /** @@ -249,15 +232,16 @@ public Build prevBuildForChangelog( * @return build chooser descriptor */ 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); } /** @@ -268,8 +252,9 @@ public static DescriptorExtensionList all( */ public static List allApplicableTo(Item item) { List result = new ArrayList<>(); - for (BuildChooserDescriptor d : all()) { - if (d.isApplicable(item.getClass())) result.add(d); + for (BuildChooserDescriptor d: all()) { + if (d.isApplicable(item.getClass())) + result.add(d); } return result; } @@ -291,8 +276,7 @@ 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 e8ee6ab929..43dc6ae574 100644 --- a/src/main/java/hudson/plugins/git/util/BuildChooserContext.java +++ b/src/main/java/hudson/plugins/git/util/BuildChooserContext.java @@ -5,6 +5,7 @@ import hudson.model.Run; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; + import java.io.IOException; import java.io.Serializable; @@ -18,15 +19,14 @@ * @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 f96f4403d6..ad52c1e7e5 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 hudson.model.Item; import jenkins.model.Jenkins; +import hudson.model.Item; /** * @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 066da06715..ba4cb6d783 100644 --- a/src/main/java/hudson/plugins/git/util/BuildData.java +++ b/src/main/java/hudson/plugins/git/util/BuildData.java @@ -1,7 +1,5 @@ package hudson.plugins.git.util; -import static hudson.Util.fixNull; - import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.model.AbstractBuild; @@ -12,8 +10,6 @@ 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; @@ -21,8 +17,6 @@ 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; @@ -31,6 +25,11 @@ 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. * @@ -49,25 +48,29 @@ public class BuildData implements Action, Serializable, Cloneable { * This map contains all the branches we've built in the past (including the build that this {@link BuildData} * is attached to) */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public Map buildsByBranchName = new HashMap<>(); /** * The last build that we did (among the values in {@link #buildsByBranchName}.) */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public Build lastBuild; /** * The name of the SCM as given by the user. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public String scmName; /** * The URLs that have been referenced. */ - @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility") + @SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", + justification = "Preserve API compatibility") public Set remoteUrls = new HashSet<>(); /** @@ -76,7 +79,8 @@ public class BuildData implements Action, Serializable, Cloneable { @CheckForNull private Integer index; - public BuildData() {} + public BuildData() { + } public BuildData(String scmName) { this.scmName = scmName; @@ -84,7 +88,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()); } } @@ -100,7 +104,8 @@ public BuildData(String scmName, Collection remoteConfigs) { */ @Override public String getDisplayName() { - if (scmName != null && !scmName.isEmpty()) return "Git Build Data:" + scmName; + if (scmName != null && !scmName.isEmpty()) + return "Git Build Data:" + scmName; return "Git Build Data"; } @@ -111,7 +116,7 @@ public String getIconFileName() { @Override public String getUrlName() { - return index == null ? "git" : "git-" + index; + return index == null ? "git" : "git-"+index; } /** @@ -135,7 +140,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; @@ -144,7 +149,7 @@ public Integer getIndex() { } public Object readResolve() { - Map newBuildsByBranchName = new HashMap<>(); + Map newBuildsByBranchName = new HashMap<>(); for (Map.Entry buildByBranchName : buildsByBranchName.entrySet()) { String branchName = fixNull(buildByBranchName.getKey()); @@ -154,7 +159,8 @@ public Object readResolve() { this.buildsByBranchName = newBuildsByBranchName; - if (this.remoteUrls == null) this.remoteUrls = new HashSet<>(); + if(this.remoteUrls == null) + this.remoteUrls = new HashSet<>(); return this; } @@ -166,7 +172,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) { @@ -180,16 +186,11 @@ 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"); @@ -201,15 +202,11 @@ 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"); @@ -242,11 +239,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); } } @@ -262,21 +259,24 @@ 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) scmName = ""; + public String getScmName() + { + if (scmName == null) + scmName = ""; return scmName; } @@ -285,7 +285,7 @@ public void addRemoteUrl(String remoteUrl) { } @Exported - public Set getRemoteUrls() { + public Set getRemoteUrls() { return remoteUrls; } @@ -298,7 +298,8 @@ public BuildData clone() { BuildData clone; try { clone = (BuildData) super.clone(); - } catch (CloneNotSupportedException e) { + } + catch (CloneNotSupportedException e) { throw new RuntimeException("Error cloning BuildData", e); } @@ -329,7 +330,8 @@ public BuildData clone() { } } - for (String remoteUrl : getRemoteUrls()) { + for(String remoteUrl : getRemoteUrls()) + { clone.addRemoteUrl(remoteUrl); } @@ -343,10 +345,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+"]"; } /** @@ -399,11 +401,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 897b0760c4..a9d8740818 100644 --- a/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java +++ b/src/main/java/hudson/plugins/git/util/CommitTimeComparator.java @@ -25,19 +25,18 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.plugins.git.Revision; -import java.io.IOException; -import java.util.Comparator; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevWalk; +import java.io.IOException; +import java.util.Comparator; + /** * 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; @@ -46,7 +45,7 @@ public CommitTimeComparator(Repository r) { } public int compare(Revision lhs, Revision rhs) { - return compare(time(lhs), time(rhs)); + return compare(time(lhs),time(rhs)); } private int time(Revision r) { @@ -54,7 +53,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 4e83b47a9c..226946c575 100644 --- a/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java @@ -1,28 +1,30 @@ package hudson.plugins.git.util; -import static java.util.Collections.emptyList; - -import hudson.EnvVars; import hudson.Extension; +import hudson.EnvVars; 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. @@ -39,26 +41,16 @@ 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); + 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 @@ -68,7 +60,7 @@ public Collection getCandidateRevisions( 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 @@ -99,29 +91,24 @@ public Collection getCandidateRevisions( 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)); } } @@ -133,13 +120,11 @@ public Collection getCandidateRevisions( 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); @@ -180,9 +165,7 @@ private Collection getHeadRevision( * @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(); @@ -192,11 +175,11 @@ private List getAdvancedCandidateRevisions( // 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()) { @@ -211,14 +194,14 @@ private List getAdvancedCandidateRevisions( 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(); } } } @@ -238,15 +221,15 @@ private List getAdvancedCandidateRevisions( // 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; } } } @@ -258,12 +241,8 @@ private List getAdvancedCandidateRevisions( // 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 @@ -279,7 +258,8 @@ private List getAdvancedCandidateRevisions( * 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 3a143c9ad0..1142142f63 100644 --- a/src/main/java/hudson/plugins/git/util/GitUtils.java +++ b/src/main/java/hudson/plugins/git/util/GitUtils.java @@ -1,8 +1,6 @@ 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; @@ -16,13 +14,6 @@ import hudson.plugins.git.Revision; import hudson.remoting.VirtualChannel; import hudson.slaves.NodeProperty; -import java.io.IOException; -import java.io.OutputStream; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import jenkins.model.Jenkins; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; @@ -31,12 +22,21 @@ import org.eclipse.jgit.revwalk.RevWalk; import org.jenkinsci.plugins.gitclient.GitClient; -public class GitUtils implements Serializable { +import java.io.IOException; +import java.io.OutputStream; +import java.io.Serializable; +import java.text.MessageFormat; +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; - @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "known non-serializable field") +public class GitUtils implements Serializable { + + @SuppressFBWarnings(value="SE_BAD_FIELD", justification="known non-serializable field") @NonNull GitClient git; - @NonNull TaskListener listener; @@ -56,16 +56,13 @@ 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(); @@ -152,11 +149,10 @@ 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; } } @@ -165,8 +161,9 @@ public Revision getRevisionContainingBranch(String branchName) } public Revision getRevisionForSHA1(ObjectId sha1) throws GitException, IOException, InterruptedException { - for (Revision revision : getAllBranchRevisions()) { - if (revision.getSha1().equals(sha1)) return revision; + for(Revision revision : getAllBranchRevisions()) { + if(revision.getSha1().equals(sha1)) + return revision; } return new Revision(sha1); } @@ -177,12 +174,11 @@ 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(); @@ -212,7 +208,8 @@ 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) return l; + if (l.size() <= 1) + return l; try { return git.withRepository((Repository repo, VirtualChannel channel) -> { @@ -227,7 +224,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); @@ -260,8 +259,8 @@ public List filterTipBranches(final Collection revisions) th 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()); }); @@ -271,10 +270,11 @@ 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,19 +287,18 @@ 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) { @@ -321,7 +320,7 @@ public static EnvVars getPollEnvironment( env = p.getEnvironment(workspaceToNode(ws), listener); } - p.getScm().buildEnvironment(b, env); + p.getScm().buildEnvironment(b,env); } else { env = p.getEnvironment(workspaceToNode(ws), listener); } @@ -331,22 +330,23 @@ public static EnvVars getPollEnvironment( 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) env.put("WORKSPACE", ws.getRemote()); + 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,14 +372,13 @@ 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); + } } } } @@ -388,16 +387,16 @@ public static String[] fixupNames(String[] names, String[] urls) { String[] returnNames = new String[urls.length]; Set usedNames = new HashSet<>(); - for (int i = 0; i < urls.length; i++) { + for(int i=0; iexcept for those which match the * configured branch specifiers. @@ -32,17 +33,13 @@ 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); @@ -107,4 +104,5 @@ 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 14dfcaa14d..aa08eb197c 100644 --- a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java @@ -151,8 +151,7 @@ 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. * @@ -168,8 +167,9 @@ 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); @@ -323,42 +323,41 @@ 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); @@ -395,7 +394,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 { @@ -418,64 +417,61 @@ 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(); @@ -488,7 +484,7 @@ protected void retrieve( 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..."); @@ -501,39 +497,37 @@ protected void retrieve( 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; } @@ -553,39 +547,37 @@ public void record( 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; } @@ -596,262 +588,228 @@ public void record( 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(); + 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; } - 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()); - } + 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; + } + 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; } - return null; + break; } + } + listener.getLogger().format("Processed %d refs%n", count); - 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; + } + + 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(); } - 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.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); } - 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; + }, 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"); + } } - break; } - } - listener.getLogger().format("Processed %d refs%n", count); + )) { + listener.getLogger().format("Processed %d branches (query complete)%n", count); + return; } + } + listener.getLogger().format("Processed %d branches%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); - } - }, - 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); + 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 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; + 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"); + } + } } - } - listener.getLogger().format("Processed %d tags%n", count); + )) { + listener.getLogger().format("Processed %d tags (query complete)%n", count); + return; } - }, - context, - listener, - true, - true); + } + listener.getLogger().format("Processed %d tags%n", count); + } + }, context, listener, true, true); } /** @@ -859,9 +817,7 @@ public void record( */ @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()); @@ -904,7 +860,9 @@ protected SCMRevision retrieve( 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; @@ -912,11 +870,11 @@ protected SCMRevision retrieve( 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)) { @@ -924,7 +882,7 @@ protected SCMRevision retrieve( // 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; @@ -936,8 +894,7 @@ protected SCMRevision retrieve( 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); @@ -945,7 +902,7 @@ protected SCMRevision retrieve( 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; @@ -957,11 +914,10 @@ protected SCMRevision retrieve( 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; @@ -989,18 +945,17 @@ protected SCMRevision retrieve( 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); @@ -1011,91 +966,83 @@ protected SCMRevision retrieve( 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); } /** @@ -1103,8 +1050,7 @@ public SCMRevision run(GitClient client, String remoteName) */ @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()); @@ -1142,7 +1088,9 @@ 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)) { @@ -1154,10 +1102,8 @@ 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) { @@ -1263,12 +1209,11 @@ 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()); @@ -1308,8 +1253,7 @@ protected static File getCacheDir(String cacheEntry, boolean createDirectory) { return null; } String cacheRootDir = SystemProperties.getString(AbstractGitSCMSource.class.getName() + ".cacheRootDir"); - File cacheDir = new File( - cacheRootDir != null ? new File(cacheRootDir) : new File(jenkins.getRootDir(), "caches"), cacheEntry); + File cacheDir = new File(cacheRootDir != null ? new File(cacheRootDir) : new File(jenkins.getRootDir(), "caches"), cacheEntry); if (!cacheDir.isDirectory()) { if (createDirectory) { boolean ok = cacheDir.mkdirs(); @@ -1342,13 +1286,12 @@ private StandardUsernameCredentials getCredentials(@CheckForNull Item context) { if (credentialsId == null) { return null; } - return CredentialsMatchers.firstOrNull( - CredentialsProvider.lookupCredentialsInItem( - StandardUsernameCredentials.class, - context, - ACL.SYSTEM2, - URIRequirementBuilder.fromUri(getRemote()).build()), - CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); + return CredentialsMatchers + .firstOrNull( + CredentialsProvider.lookupCredentialsInItem(StandardUsernameCredentials.class, context, + ACL.SYSTEM2, URIRequirementBuilder.fromUri(getRemote()).build()), + CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), + GitClient.CREDENTIALS_MATCHER)); } /** @@ -1383,7 +1326,8 @@ 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} @@ -1403,7 +1347,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); @@ -1429,10 +1373,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} @@ -1440,34 +1384,33 @@ 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("|"); - } - quotedBranches.append(quotedBranch); + 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("|"); } - return quotedBranches.toString(); + quotedBranches.append(quotedBranch); + } + return quotedBranches.toString(); } /*package*/ static String getCacheEntry(String remote) { @@ -1508,7 +1451,8 @@ 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()); } /** @@ -1526,6 +1470,7 @@ public int hashCode() { public String toString() { return hash; } + } public static class SpecificRevisionBuildChooser extends BuildChooser { @@ -1542,13 +1487,9 @@ 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); } @@ -1557,12 +1498,12 @@ public Collection getCandidateRevisions( * {@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; } + } /** @@ -1570,13 +1511,11 @@ public Build prevBuildForChangelog( * * @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; @@ -1691,8 +1630,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 6c9d21fbfc..14ba4feab2 100644 --- a/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java +++ b/src/main/java/jenkins/plugins/git/GitBranchSCMHead.java @@ -55,8 +55,7 @@ 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); @@ -68,8 +67,7 @@ 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); @@ -81,5 +79,6 @@ public SCMRevision migrate( } return null; } + } } diff --git a/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java b/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java index b2a7721ff2..486296f02e 100644 --- a/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java +++ b/src/main/java/jenkins/plugins/git/GitBranchSCMRevision.java @@ -24,9 +24,12 @@ */ 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 0deee361ba..063c9241a7 100644 --- a/src/main/java/jenkins/plugins/git/GitCredentialBindings.java +++ b/src/main/java/jenkins/plugins/git/GitCredentialBindings.java @@ -11,10 +11,11 @@ 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 { @@ -24,10 +25,7 @@ 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 @@ -35,9 +33,7 @@ void setCredentialPairBindings( * @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 @@ -47,14 +43,14 @@ void setGitEnvironmentVariables( * @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(); } @@ -65,20 +61,18 @@ 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 9b4fdb47b3..e170e4225e 100644 --- a/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java +++ b/src/main/java/jenkins/plugins/git/GitHooksConfiguration.java @@ -29,8 +29,6 @@ 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; @@ -40,9 +38,12 @@ import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; -@Extension -@Symbol("gitHooks") -@Restricted(NoExternalUse.class) +import java.io.IOException; +import java.util.logging.Logger; + + + +@Extension @Symbol("gitHooks") @Restricted(NoExternalUse.class) public class GitHooksConfiguration extends GlobalConfiguration implements PersistentDescriptor { public static final String DISABLED_WIN = "NUL:"; @@ -56,8 +57,7 @@ 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,8 +80,7 @@ public void setAllowedOnAgents(final boolean allowedOnAgents) { save(); } - @Override - @NonNull + @Override @NonNull public GlobalConfigurationCategory getCategory() { return GlobalConfigurationCategory.get(GlobalConfigurationCategory.Security.class); } @@ -91,20 +90,18 @@ 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); } } @@ -127,8 +124,7 @@ 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 7d956a2256..4bf85259c0 100644 --- a/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java +++ b/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java @@ -14,7 +14,6 @@ public class GitRemoteHeadRefAction extends InvisibleAction implements Serializa @NonNull private final String remote; - @NonNull private final String name; @@ -44,7 +43,8 @@ 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,6 +54,11 @@ 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 bcee71e84f..fbfa2f8d47 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMBuilder.java +++ b/src/main/java/jenkins/plugins/git/GitSCMBuilder.java @@ -115,11 +115,8 @@ 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; @@ -515,8 +512,7 @@ public GitSCM build() { return new GitSCM( asRemoteConfigs(), Collections.singletonList(new BranchSpec(head().getName())), - browser(), - gitTool(), + browser(), gitTool(), extensions); } @@ -551,7 +547,10 @@ 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 + ); } /** @@ -600,4 +599,5 @@ 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 3c27bd80a0..9b468d89ac 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMFile.java +++ b/src/main/java/jenkins/plugins/git/GitSCMFile.java @@ -47,13 +47,11 @@ * * @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 217a2f9e44..7e146bc563 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java +++ b/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java @@ -107,18 +107,15 @@ 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 @@ -185,8 +182,7 @@ 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(); } @@ -263,16 +259,14 @@ 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 } @@ -300,8 +294,9 @@ 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); @@ -335,8 +330,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; @@ -374,12 +369,16 @@ public SCMFileSystem build( if (credentialsId != null) { StandardCredentials credential = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentialsInItem( - StandardUsernameCredentials.class, - owner, - ACL.SYSTEM2, - URIRequirementBuilder.fromUri(remote).build()), + StandardUsernameCredentials.class, + owner, + ACL.SYSTEM2, + 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); } @@ -388,8 +387,7 @@ public SCMFileSystem build( 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); @@ -403,21 +401,12 @@ public SCMFileSystem build( 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(); } @@ -448,8 +437,7 @@ 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()); @@ -460,15 +448,9 @@ 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 52fd6279c2..7e80773b2e 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java +++ b/src/main/java/jenkins/plugins/git/GitSCMMatrixUtil.java @@ -5,11 +5,12 @@ import hudson.plugins.git.Revision; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; -import java.util.Collections; -import java.util.Set; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; +import java.util.Collections; +import java.util.Set; + /** * Utility methods for integrating with Matrix Project plugin. */ @@ -22,7 +23,8 @@ public static Set populateCandidatesFromRootBuild(AbstractBuild build, BuildData parentBuildData = scm.getBuildData(parentBuild); if (parentBuildData != null) { Build lastBuild = parentBuildData.lastBuild; - if (lastBuild != null) return Collections.singleton(lastBuild.getMarked()); + 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 94f8cbb2c0..894ae2b7f9 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 @@ -170,15 +170,7 @@ 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; @@ -203,13 +195,7 @@ public GitSCMSource( @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); } @@ -235,19 +221,13 @@ 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()); } } } @@ -277,7 +257,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<>(); @@ -306,6 +286,7 @@ public boolean isIgnoreOnPushNotifications() { return SCMTrait.find(traits, IgnoreOnPushNotificationTrait.class) != null; } + // For Stapler only @Restricted(DoNotUse.class) @DataBoundSetter @@ -351,18 +332,13 @@ 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); @@ -397,8 +373,8 @@ public String getRawRefSpecs() { 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; @@ -419,9 +395,7 @@ 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 @@ -439,18 +413,17 @@ 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(), @@ -458,10 +431,11 @@ public ListBoxModel doFillCredentialsIdItems( .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(); } @@ -480,7 +454,9 @@ public FormValidation doCheckCredentialsId( for (ListBoxModel.Option o : CredentialsProvider.listCredentialsInItem( StandardUsernameCredentials.class, context, - context instanceof Queue.Task ? Tasks.getAuthenticationOf2((Queue.Task) context) : ACL.SYSTEM2, + context instanceof Queue.Task + ? Tasks.getAuthenticationOf2((Queue.Task) context) + : ACL.SYSTEM2, URIRequirementBuilder.fromUri(remote).build(), GitClient.CREDENTIALS_MATCHER)) { if (Objects.equals(value, o.value)) { @@ -499,7 +475,7 @@ public FormValidation doCheckCredentialsId( @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 @@ -534,14 +510,12 @@ 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; } @@ -553,19 +527,18 @@ 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. @@ -574,8 +547,8 @@ public List onNotifyCommit( 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; @@ -592,8 +565,9 @@ 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; } @@ -618,9 +592,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(); } @@ -633,13 +607,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(); @@ -656,8 +630,9 @@ 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; } @@ -676,8 +651,7 @@ 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()); } @@ -695,8 +669,7 @@ 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 dbff593332..494d027d2f 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceContext.java @@ -39,6 +39,7 @@ 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; @@ -345,13 +346,14 @@ 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; } @@ -404,7 +406,8 @@ 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 @@ -420,8 +423,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 { @@ -439,7 +442,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; @@ -448,4 +451,5 @@ 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 4050728aaa..3d03df8ffb 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceDefaults.java @@ -96,16 +96,17 @@ 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); @@ -121,7 +122,8 @@ public void decorateCloneCommand( @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 ff6d4ea6e7..5262567c19 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSourceRequest.java @@ -61,8 +61,7 @@ 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(); @@ -89,6 +88,7 @@ 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 0cd28ce494..9862c34d92 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,9 +153,8 @@ && 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()); } /** @@ -165,9 +164,8 @@ 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(); @@ -191,24 +189,21 @@ 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.lookupCredentialsInItem( - StandardUsernameCredentials.class, - owner, - owner instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) owner) - : ACL.SYSTEM2, - URIRequirementBuilder.fromUri(remote).build()); + List urlCredentials = CredentialsProvider + .lookupCredentialsInItem(StandardUsernameCredentials.class, owner, + owner instanceof Queue.Task + ? Tasks.getAuthenticationOf2((Queue.Task) owner) + : ACL.SYSTEM2, 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; } @@ -218,13 +213,14 @@ && supports(remote) 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); } @@ -256,11 +252,8 @@ && supports(remote) * @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; /** @@ -274,9 +267,8 @@ protected abstract SCMFileSystem build( * @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. @@ -290,8 +282,9 @@ public abstract long getTimestamp( * @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; /** @@ -304,9 +297,8 @@ public abstract SCMRevision getRevision( * @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 { @@ -325,8 +317,9 @@ public long getTimestamp( * @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()); @@ -344,8 +337,8 @@ public SCMRevision getRevision( * @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)); } @@ -360,10 +353,9 @@ public final Iterable getRevisions( * @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; /** @@ -375,7 +367,8 @@ public abstract Iterable getRevisions( * @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 8fb8fd9145..67cf84c371 100644 --- a/src/main/java/jenkins/plugins/git/GitStep.java +++ b/src/main/java/jenkins/plugins/git/GitStep.java @@ -82,12 +82,7 @@ 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 @@ -96,15 +91,16 @@ 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); } @@ -117,5 +113,7 @@ 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 5232fc9664..07512cd636 100644 --- a/src/main/java/jenkins/plugins/git/GitTagSCMHead.java +++ b/src/main/java/jenkins/plugins/git/GitTagSCMHead.java @@ -58,4 +58,5 @@ 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 97cba663c9..faf8c043fb 100644 --- a/src/main/java/jenkins/plugins/git/GitToolChooser.java +++ b/src/main/java/jenkins/plugins/git/GitToolChooser.java @@ -9,6 +9,13 @@ 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.*; @@ -18,12 +25,6 @@ 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; @@ -42,7 +43,6 @@ 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,15 +61,8 @@ 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; @@ -97,7 +90,9 @@ public GitToolChooser( 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; } @@ -105,38 +100,29 @@ 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}); } } } @@ -191,15 +177,16 @@ 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"; @@ -209,7 +196,7 @@ String convertToCanonicalURL(String remoteURL) { 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); @@ -235,23 +222,25 @@ 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 */ @@ -282,16 +271,12 @@ private void assignSizeToInternalCache(String repoURL, long repoSize) { repoURL = convertToCanonicalURL(repoURL); Long oldSize = repositorySizeCache.put(repoURL, repoSize); if (oldSize == null) { - 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}); } else if (oldSize < repoSize) { - LOGGER.log(Level.FINE, "Replaced old repo size {0} with new size {1} for repo {2}", new Object[] { - oldSize, repoSize, repoURL - }); + LOGGER.log(Level.FINE, "Replaced old repo size {0} with new size {1} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); } else if (oldSize > repoSize) { /* Put back the larger old repo size and log a warning. This is not harmful but should be quite rare */ - LOGGER.log(Level.WARNING, "Ignoring new repo size {1} in favor of old size {0} for repo {2}", new Object[] { - oldSize, repoSize, repoURL - }); + LOGGER.log(Level.WARNING, "Ignoring new repo size {1} in favor of old size {0} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); repositorySizeCache.put(repoURL, oldSize); } } @@ -302,13 +287,14 @@ 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; @@ -363,10 +349,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); } } @@ -377,15 +363,13 @@ 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()); } @@ -418,7 +402,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 abstract static class RepositorySizeAPI implements ExtensionPoint { + public static abstract 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 2a0955794e..a0ee7e3161 100644 --- a/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java +++ b/src/main/java/jenkins/plugins/git/GitUsernamePasswordBinding.java @@ -3,22 +3,18 @@ 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; @@ -28,23 +24,29 @@ import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.stapler.DataBoundConstructor; -import org.kohsuke.stapler.interceptor.RequirePOST; -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; +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; 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; } @@ -58,32 +60,30 @@ 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,31 +96,24 @@ 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"); @@ -128,8 +121,8 @@ public void setGitEnvironmentVariables( } @Override - public GitClient getGitClientInstance(String gitToolExe, FilePath repository, EnvVars env, TaskListener listener) - throws IOException, InterruptedException { + public GitClient getGitClientInstance(String gitToolExe, FilePath repository, + EnvVars env, TaskListener listener) throws IOException, InterruptedException { Git gitInstance = Git.with(listener, env).using(gitToolExe); return gitInstance.getClient(); } @@ -140,7 +133,8 @@ protected static final class GenerateGitScript extends AbstractOnDiskBinding 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 1c8157e02d..4e23b0033d 100644 --- a/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java +++ b/src/main/java/jenkins/plugins/git/MatrixGitPublisher.java @@ -7,6 +7,7 @@ import hudson.matrix.MatrixBuild; import hudson.model.BuildListener; import hudson.plugins.git.GitPublisher; + import java.io.IOException; @Extension(optional = true) @@ -15,7 +16,7 @@ public class MatrixGitPublisher implements MatrixAggregatable { * For a matrix project, push should only happen once. */ 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 a88a438a07..3ba64b4eec 100644 --- a/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java +++ b/src/main/java/jenkins/plugins/git/MergeWithGitSCMExtension.java @@ -56,7 +56,6 @@ public class MergeWithGitSCMExtension extends GitSCMExtension { @NonNull private final String baseName; - @CheckForNull private final String baseHash; @@ -75,9 +74,8 @@ 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); } @@ -91,25 +89,24 @@ 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 f5a817c02e..3dbb845dd5 100644 --- a/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/BranchDiscoveryTrait.java @@ -56,14 +56,15 @@ 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 1cf2c48d08..50e6dc7771 100644 --- a/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/CleanAfterCheckoutTrait.java @@ -25,13 +25,14 @@ 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 a22648ecad..78d20e800e 100644 --- a/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/CleanBeforeCheckoutTrait.java @@ -25,13 +25,14 @@ 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 8c08c7bb3a..d512eac7e7 100644 --- a/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/DiscoverOtherRefsTrait.java @@ -23,8 +23,6 @@ */ 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; @@ -42,6 +40,8 @@ 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,8 +67,7 @@ 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() { @@ -88,8 +87,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; } } @@ -112,7 +111,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 4d3e06b6ed..02dd07afbd 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/GitBrowserSCMSourceTrait.java @@ -111,8 +111,7 @@ 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 0a54a4a24c..69f85f081f 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 6002b17c17..f4f2243be7 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java +++ b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java @@ -25,7 +25,6 @@ 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; @@ -38,6 +37,7 @@ 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,23 +79,21 @@ 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; @@ -121,11 +119,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; @@ -150,8 +148,8 @@ GitSCMExtensionTraitDescriptor.class, getClass(), "convertToTrait", GitSCMExtens + "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; @@ -213,17 +211,19 @@ 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 747e382933..c10764d131 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,8 +130,7 @@ public Class getContextClass() { */ @Override public boolean isApplicableToBuilder(@NonNull Class builderClass) { - return super.isApplicableToBuilder(builderClass) - && getSCMDescriptor().showGitToolOptions(); + return super.isApplicableToBuilder(builderClass) && getSCMDescriptor().showGitToolOptions(); } /** @@ -139,8 +138,7 @@ 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(); } /** @@ -169,5 +167,6 @@ 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 00e09a41d0..bbf82e0d60 100644 --- a/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/IgnoreOnPushNotificationTrait.java @@ -46,7 +46,8 @@ public class IgnoreOnPushNotificationTrait extends SCMSourceTrait { * Stapler constructor. */ @DataBoundConstructor - public IgnoreOnPushNotificationTrait() {} + public IgnoreOnPushNotificationTrait() { + } /** * {@inheritDoc} @@ -80,6 +81,7 @@ public String getDisplayName() { return "Ignore on push notifications"; } + /** * {@inheritDoc} */ @@ -111,5 +113,6 @@ 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 f73f713a45..d46866a519 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 ba82311429..0f1f9aced6 100644 --- a/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/PruneStaleTagTrait.java @@ -25,11 +25,12 @@ 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 60abe47754..1f461f8ef9 100644 --- a/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/RefSpecsSCMSourceTrait.java @@ -178,6 +178,7 @@ public Class getScmClass() { public Class getContextClass() { return GitSCMSourceContext.class; } + } /** @@ -243,7 +244,8 @@ 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 42750e0e55..e37fc7bc94 100644 --- a/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/RemoteNameSCMSourceTrait.java @@ -68,7 +68,9 @@ 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 + )); } /** @@ -187,8 +189,8 @@ public String getDisplayName() { } /** - * - * /** + + /** * {@inheritDoc} */ @Override @@ -225,9 +227,8 @@ 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); @@ -236,5 +237,6 @@ 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 55eeda476f..9c9be145a9 100644 --- a/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/TagDiscoveryTrait.java @@ -55,14 +55,15 @@ 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()); } @@ -119,8 +120,7 @@ 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/test/java/hudson/plugins/git/AbstractGitProject.java b/src/test/java/hudson/plugins/git/AbstractGitProject.java index aa9e1b1232..0800d8749a 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitProject.java +++ b/src/test/java/hudson/plugins/git/AbstractGitProject.java @@ -23,8 +23,6 @@ */ package hudson.plugins.git; -import static org.junit.Assert.assertTrue; - import hudson.EnvVars; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; @@ -43,15 +41,22 @@ 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; @@ -66,13 +71,14 @@ public class AbstractGitProject extends AbstractGitRepository { public JenkinsRule r = 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 = r.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; @@ -86,120 +92,65 @@ 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 = r.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)); @@ -229,15 +180,14 @@ protected FreeStyleProject setupProject( * @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 = r.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()); } @@ -255,14 +205,10 @@ protected FreeStyleProject setupProject( return project; } - 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()); + assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); } if (expectedResult != null) { r.assertBuildStatus(expectedResult, build); @@ -270,18 +216,10 @@ protected FreeStyleBuild 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()); + assertTrue(build.getWorkspace().child(parentDir).child(expectedNewlyCommittedFile).exists()); } if (expectedResult != null) { r.assertBuildStatus(expectedResult, build); @@ -289,14 +227,10 @@ protected FreeStyleBuild 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()); + assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); } if (expectedResult != null) { r.assertBuildStatus(expectedResult, build); @@ -304,13 +238,12 @@ protected MatrixBuild build( return build; } - 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() { @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); @@ -329,6 +262,9 @@ 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 95f3ed1441..630693a25f 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitRepository.java +++ b/src/test/java/hudson/plugins/git/AbstractGitRepository.java @@ -1,21 +1,26 @@ package hudson.plugins.git; -import hudson.model.TaskListener; -import hudson.plugins.git.util.GitUtilsTest; -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 jenkins.plugins.git.GitSampleRepoRule; + +import hudson.plugins.git.util.GitUtilsTest; import org.eclipse.jgit.util.SystemReader; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; 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; + /** * Temporary git repository for use with tests. Tests which need a git * repository but do not need a running Jenkins instance should extend this @@ -39,9 +44,7 @@ public void createGitRepository() throws Exception { TaskListener listener = StreamTaskListener.fromStderr(); repo.init(); testGitDir = repo.getRoot(); - testGitClient = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()) - .in(testGitDir) - .getClient(); + testGitClient = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()).in(testGitDir).getClient(); } /** @@ -78,6 +81,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 cf3c0b3592..bcb83147cb 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java +++ b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java @@ -1,26 +1,25 @@ 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.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.DisableRemotePoll; import hudson.plugins.git.extensions.impl.PathRestriction; import hudson.plugins.git.extensions.impl.RelativeTargetDirectory; import hudson.plugins.git.extensions.impl.SparseCheckoutPath; @@ -32,12 +31,13 @@ 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,9 +46,12 @@ 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; /** @@ -93,15 +96,14 @@ 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); } @@ -121,145 +123,83 @@ 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) scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); - if (excludedUsers != null) scm.getExtensions().add(new UserExclusion(excludedUsers)); - if (excludedRegions != null || includedRegions != null) - scm.getExtensions().add(new PathRestriction(includedRegions, excludedRegions)); + if (relativeTargetDir!=null) + scm.getExtensions().add(new RelativeTargetDirectory(relativeTargetDir)); + if (excludedUsers!=null) + scm.getExtensions().add(new UserExclusion(excludedUsers)); + if (excludedRegions!=null || includedRegions!=null) + scm.getExtensions().add(new PathRestriction(includedRegions,excludedRegions)); scm.getExtensions().add(new SparseCheckoutPaths(sparseCheckoutPaths)); @@ -278,109 +218,95 @@ protected FreeStyleProject setupProject( * @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) { r.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) { r.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) { r.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); + 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 { @@ -405,8 +331,7 @@ 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 eaeb0eb8cc..58d42e83e4 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,44 +16,45 @@ 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<>(); @@ -73,6 +74,7 @@ public void testMatchEnv() { assertTrue(l.matches("master", env)); assertFalse(l.matches("dev", env)); + BranchSpec est = new BranchSpec("${origin}/*/${dev}"); assertFalse(est.matches("origintestdev", env)); @@ -115,55 +117,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 cfdc6d84ff..4ebe2d6d8e 100644 --- a/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java +++ b/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java @@ -23,11 +23,10 @@ */ 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 2e38defdf2..e854d10232 100644 --- a/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java +++ b/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java @@ -56,8 +56,7 @@ 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); @@ -65,11 +64,9 @@ 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: '**']], "; @@ -80,46 +77,43 @@ 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 @@ -129,19 +123,15 @@ 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 @@ -150,16 +140,15 @@ 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 @@ -169,8 +158,14 @@ 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 @@ -183,12 +178,17 @@ 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,12 +201,17 @@ 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 @@ -219,12 +224,17 @@ 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 @@ -235,8 +245,14 @@ 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 @@ -247,8 +263,14 @@ 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 @@ -258,7 +280,13 @@ 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 8bdc836738..38c00e23bf 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java @@ -3,15 +3,19 @@ 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 9565f21d72..43b2db913f 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java @@ -12,12 +12,15 @@ 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 adfc096d4e..5e198345db 100644 --- a/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java @@ -1,9 +1,5 @@ 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; @@ -24,6 +20,10 @@ 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,8 +99,7 @@ private WorkflowJob createProject(boolean useCredential) throws Exception { + randomPipelineCheckoutExtras() + classEpilogue() + " )" - + "}", - true)); + + "}", true)); return p; } @@ -113,10 +112,9 @@ 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']]]", @@ -245,12 +243,7 @@ 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']", }; @@ -293,12 +286,10 @@ 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); } @@ -315,12 +306,10 @@ 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); } @@ -333,12 +322,10 @@ 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); } @@ -354,8 +341,7 @@ 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 833d9b5efb..1113899fd4 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 static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; -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 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; /** * @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 68f6b96cd1..7686f02bd7 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,17 +26,13 @@ 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); @@ -45,10 +41,7 @@ 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 6824c8cc1a..408310628a 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java @@ -1,11 +1,13 @@ package hudson.plugins.git; -import static org.junit.Assert.*; +import java.util.ArrayList; import hudson.model.User; -import java.util.ArrayList; -import org.junit.Rule; + import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Rule; + import org.jvnet.hudson.test.JenkinsRule; public class GitChangeSetBadArgsTest { @@ -59,8 +61,7 @@ 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)); } @@ -70,8 +71,7 @@ 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,9 +81,7 @@ 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 3632420570..898d0f9736 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.assertEquals; import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.Collections; +import static org.junit.Assert.assertEquals; import org.junit.Test; public class GitChangeSetBasicTest { @@ -22,9 +22,8 @@ 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 @@ -42,8 +41,7 @@ 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 @@ -65,8 +63,7 @@ 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()); } @@ -74,18 +71,15 @@ 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()); @@ -93,8 +87,7 @@ 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()); } @@ -120,7 +113,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); } @@ -145,20 +138,19 @@ 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,")); @@ -166,88 +158,72 @@ 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")); @@ -257,27 +233,23 @@ 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 7599cd3fc3..b813156066 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,4 +98,5 @@ 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 0706e7e248..77e78c5477 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java @@ -1,12 +1,11 @@ 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 094180f5b0..b2fb32f864 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 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 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 org.junit.Before; public class GitChangeSetListTest { diff --git a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java index 61f08d807c..53bf18397a 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java @@ -1,32 +1,37 @@ package hudson.plugins.git; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import org.jenkinsci.plugins.gitclient.Git; +import org.jenkinsci.plugins.gitclient.GitClient; + +import org.eclipse.jgit.lib.ObjectId; 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 jenkins.plugins.git.GitSampleRepoRule; -import org.eclipse.jgit.lib.ObjectId; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; 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 { @@ -60,13 +65,11 @@ 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); } @@ -94,16 +97,13 @@ 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 647fe2fb1c..e0b67e4785 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java @@ -1,5 +1,12 @@ 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; @@ -8,14 +15,6 @@ 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; @@ -66,42 +65,41 @@ 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; + } } } @@ -128,16 +126,12 @@ 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 @@ -158,9 +152,7 @@ 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 @@ -184,7 +176,8 @@ 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 e58feae7ee..af3a8614a2 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTest.java @@ -1,25 +1,26 @@ 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 @@ -34,8 +35,7 @@ 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,10 +45,8 @@ 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 @@ -58,8 +56,7 @@ 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())); } @@ -70,8 +67,7 @@ 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())); } @@ -82,8 +78,7 @@ 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())); } @@ -94,8 +89,7 @@ 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())); } @@ -106,8 +100,7 @@ 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())); } @@ -118,8 +111,7 @@ 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)); } @@ -130,8 +122,7 @@ 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)); } @@ -142,8 +133,7 @@ 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)); } @@ -154,8 +144,7 @@ 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)); } @@ -166,36 +155,39 @@ 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() @@ -214,8 +206,7 @@ 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); @@ -227,10 +218,8 @@ 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 dc25003340..90b6083228 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java @@ -1,13 +1,12 @@ 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 f8cfd0caf4..9570d87cef 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java @@ -1,10 +1,5 @@ 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; @@ -17,13 +12,20 @@ import java.util.List; import java.util.Random; import java.util.UUID; -import jenkins.plugins.git.CliGitCommand; -import jenkins.plugins.git.GitSampleRepoRule; + +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.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; @@ -57,8 +59,8 @@ public class GitChangeSetTruncateTest { private static class TestData { - public final String testDataCommitSummary; - public final String testDataTruncatedSummary; + final public String testDataCommitSummary; + final public String testDataTruncatedSummary; TestData(String commitSummary, String truncatedSummary) { this.testDataCommitSummary = commitSummary; @@ -68,29 +70,25 @@ private static class TestData { // 1 2 3 4 5 6 7 // 1234567890123456789012345678901234567890123456789012345678901234567890 - 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 + 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 }; public GitChangeSetTruncateTest(String gitImpl, String commitSummary, String truncatedSummary) throws Exception { @@ -98,14 +96,11 @@ 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); @@ -132,9 +127,7 @@ 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"); @@ -151,8 +144,7 @@ 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; gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java index 4a61dc17a4..d498e8b278 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java @@ -1,19 +1,22 @@ 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 { @@ -39,17 +42,11 @@ 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"); @@ -71,16 +68,11 @@ public static GitChangeSet genChangeSet( 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); } @@ -88,8 +80,7 @@ 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"); @@ -101,53 +92,48 @@ 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 3d120c0667..005e0288a2 100644 --- a/src/test/java/hudson/plugins/git/GitHooksTest.java +++ b/src/test/java/hudson/plugins/git/GitHooksTest.java @@ -1,26 +1,9 @@ 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; @@ -38,16 +21,34 @@ 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 { @@ -61,10 +62,10 @@ public void setGitTool() throws IOException { lr.record(GitHooksConfiguration.class.getName(), Level.ALL).capture(1024); GitTool tool = new GitTool("my-git", "git", Collections.>emptyList()); r.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 r.jenkins.setLabelString("master"); - r.jenkins.setNumExecutors(3); // In case this changes in the future as well. + r.jenkins.setNumExecutors(3); //In case this changes in the future as well. } @After @@ -87,15 +88,19 @@ public void testPipelineFromScm() throws Exception { GitHooksConfiguration.get().setAllowedOnAgents(true); final DumbSlave agent = r.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 = r.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); @@ -110,7 +115,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); @@ -121,7 +126,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 = r.buildAndAssertSuccess(job); @@ -136,7 +141,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 = r.buildAndAssertSuccess(job); @@ -151,7 +156,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)); @@ -166,7 +171,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 = r.buildAndAssertSuccess(job); @@ -175,26 +180,19 @@ 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()); @@ -269,25 +267,23 @@ private WorkflowJob setupAndRunPipelineCheckout(String node) throws Exception { final WorkflowJob job = r.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 = r.buildAndAssertSuccess(job); r.assertLogNotContains("h4xor3d", run); final String commitFile2 = "commitFile2"; @@ -313,6 +309,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 1793249716..e0fd8fd508 100644 --- a/src/test/java/hudson/plugins/git/GitPublisherTest.java +++ b/src/test/java/hudson/plugins/git/GitPublisherTest.java @@ -23,15 +23,6 @@ */ 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.EnvVars; import hudson.FilePath; import hudson.Launcher; @@ -50,6 +41,14 @@ 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.jenkinsci.plugins.gitclient.UnsupportedCommand; +import org.jvnet.hudson.test.Issue; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -58,26 +57,29 @@ 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 org.jenkinsci.plugins.gitclient.JGitTool; -import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.jenkinsci.plugins.gitclient.UnsupportedCommand; +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.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,39 +102,32 @@ public void testMatrixBuild() throws Exception { commitNewFile("a"); MatrixProject mp = r.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 TestGitPublisher( - 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 TestGitPublisher( + 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 = r.buildAndAssertSuccess(mp); @@ -141,7 +136,7 @@ private Object writeReplace() { 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 @@ -156,19 +151,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, - true, - false)); + project.getPublishersList().add(new TestGitPublisher( + 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"); @@ -181,11 +176,9 @@ 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 */ @@ -202,53 +195,45 @@ 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() r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); MatrixProject mp = r.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 TestGitPublisher( - 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 TestGitPublisher( + 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 = r.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")); } @@ -258,19 +243,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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, - true, - false)); + project.getPublishersList().add(new TestGitPublisher( + 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"); @@ -285,6 +270,7 @@ public void testMergeAndPush() throws Exception { String sha1 = getHeadRevision(build1, "integration"); assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); + } @Issue("JENKINS-12402") @@ -293,21 +279,19 @@ 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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, - true, - false)); + project.getPublishersList().add(new TestGitPublisher( + 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"); @@ -315,10 +299,7 @@ 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"); @@ -339,12 +320,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 @@ -371,11 +352,9 @@ 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") @@ -384,21 +363,19 @@ 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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, - true, - false)); + project.getPublishersList().add(new TestGitPublisher( + 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"); @@ -406,10 +383,7 @@ 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 @@ -434,10 +408,9 @@ 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"); @@ -463,18 +436,13 @@ 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") @@ -483,21 +451,19 @@ 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 TestGitPublisher( - Collections.emptyList(), - Collections.singletonList(new BranchToPush("origin", "integration")), - Collections.emptyList(), - true, - true, - false)); + project.getPublishersList().add(new TestGitPublisher( + 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"); @@ -505,10 +471,7 @@ 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 @@ -528,17 +491,15 @@ 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 @@ -557,71 +518,49 @@ 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 TestGitPublisher( - 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 TestGitPublisher( + 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"); @@ -632,18 +571,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); @@ -651,9 +590,7 @@ 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 @@ -678,14 +615,10 @@ 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"); @@ -704,22 +637,16 @@ 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); @@ -733,51 +660,47 @@ 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 TestGitPublisher( - 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"); + project.getPublishersList().add(new TestGitPublisher( + Collections.emptyList(), + Collections.singletonList(new BranchToPush("origin", "integration")), + Collections.emptyList(), + true, true, false)); - testGitClient.checkout(null, "topic1"); - final String commitFile1 = "commitFile1"; - commitNewFile(commitFile1); - final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertTrue(build1.getWorkspace().child(commitFile1).exists()); + // create initial commit and then run the build against it: + commitNewFile("commitFileBase"); + testGitClient.branch("integration"); + build(project, Result.SUCCESS, "commitFileBase"); - String sha1 = getHeadRevision(build1, "integration"); - assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name()); + 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()); } @Test @@ -787,8 +710,7 @@ public void testRebaseBeforePush() throws Exception { GitSCM scm = new GitSCM( remoteConfigs(), Collections.singletonList(new BranchSpec("master")), - null, - null, + null, null, Collections.emptyList()); project.setScm(scm); @@ -796,7 +718,10 @@ public void testRebaseBeforePush() throws Exception { btp.setRebaseBeforePush(true); GitPublisher rebasedPublisher = new TestGitPublisher( - 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)); @@ -816,6 +741,7 @@ 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"); } @@ -824,12 +750,12 @@ public void testRebaseBeforePush() throws Exception { @Test public void testMergeAndPushWithCharacteristicEnvVar() throws Exception { // jgit doesn't work because of missing PerBuildTag - // GitTool tool = new JGitTool(Collections.emptyList()); - // r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); + //GitTool tool = new JGitTool(Collections.emptyList()); + //r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); 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 @@ -867,12 +793,14 @@ 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; @@ -880,9 +808,7 @@ 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()); @@ -908,9 +834,7 @@ 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"; @@ -926,13 +850,12 @@ 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); + } /** @@ -963,8 +886,8 @@ protected GitClient getGitClient( gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); return gitClient; } - } - + } + private boolean existsTag(String tag) throws InterruptedException { return existsTagInRepo(testGitClient, tag); } @@ -991,7 +914,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==';'; } } @@ -1004,11 +927,9 @@ 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. @@ -1021,4 +942,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen return true; } + + + } diff --git a/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java b/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java index 1a7be1f435..e3c7fef5ee 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.Before; import org.junit.Test; +import org.junit.Before; 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,8 +101,6 @@ 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 2699a1cc78..044c55b2fe 100644 --- a/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java @@ -23,9 +23,6 @@ */ 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; @@ -33,6 +30,9 @@ 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,7 +44,9 @@ 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; @@ -76,6 +78,7 @@ 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 4715ac84d3..2e2c9ac384 100644 --- a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java @@ -1,14 +1,5 @@ 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.assumeFalse; -import static org.junit.Assume.assumeTrue; - import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; @@ -42,6 +33,16 @@ 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.assumeFalse; +import static org.junit.Assume.assumeTrue; + import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.storage.file.UserConfigFile; import org.eclipse.jgit.util.FS; @@ -85,14 +86,12 @@ public static void gpgsignCheck() throws Exception { } UserConfigFile userConfig = new UserConfigFile(null, userGitConfig, xdgGitConfig, FS.DETECTED); userConfig.load(); - gpgsignEnabled = userConfig.getBoolean( - ConfigConstants.CONFIG_COMMIT_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false) - || userConfig.getBoolean(ConfigConstants.CONFIG_TAG_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false); + gpgsignEnabled = userConfig.getBoolean(ConfigConstants.CONFIG_COMMIT_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false) || + userConfig.getBoolean(ConfigConstants.CONFIG_TAG_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false); } @ClassRule public static Stopwatch stopwatch = new Stopwatch(); - @Rule public TestName testName = new TestName(); @@ -132,8 +131,9 @@ 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); r.configRoundtrip(p); r.assertEqualDataBoundBeans(scm, p.getScm()); @@ -162,8 +162,9 @@ 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 */ @@ -248,8 +249,7 @@ 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(); @@ -270,8 +270,7 @@ 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); @@ -288,22 +287,16 @@ 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()); r.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 @@ -315,8 +308,7 @@ public void testMergeWithAgent() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, - null, + null, null, Collections.emptyList()); scm.getExtensions().add(new TestPreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); addChangelogToBranchExtension(scm); @@ -333,9 +325,7 @@ 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"); @@ -343,15 +333,11 @@ 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()); r.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()); } /** @@ -386,15 +372,14 @@ public void testMergeWithMatrixBuild() throws Exception { * without issue. */ assumeFalse("gpgsign enabled", gpgsignEnabled); - // Create a matrix project and a couple of axes + //Create a matrix project and a couple of axes MatrixProject project = r.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); @@ -411,9 +396,7 @@ 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"); @@ -421,15 +404,11 @@ 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()); r.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 @@ -513,25 +492,19 @@ 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()); r.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 bbf4a22e38..7efada4462 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -1,20 +1,5 @@ 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; @@ -22,6 +7,8 @@ import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; +import org.htmlunit.html.HtmlPage; + import hudson.EnvVars; import hudson.FilePath; import hudson.Functions; @@ -47,6 +34,26 @@ 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; @@ -56,42 +63,42 @@ 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 org.eclipse.jgit.util.SystemReader; -import org.htmlunit.html.HtmlPage; -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 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.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}. @@ -109,7 +116,6 @@ public class GitSCMTest extends AbstractGitTestCase { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); - @Rule public TestName testName = new TestName(); @@ -133,12 +139,13 @@ 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()); @@ -167,10 +174,9 @@ 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(); @@ -215,18 +221,13 @@ public void manageShouldAccessGlobalConfig() throws Exception { final String MANAGER = "manager"; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.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(); @@ -234,9 +235,8 @@ 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,47 +294,37 @@ 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()); r.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(); @@ -342,9 +332,7 @@ public void testBasicRemotePoll() throws Exception { assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.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)); @@ -354,8 +342,7 @@ 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"); @@ -375,22 +362,19 @@ 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"; @@ -411,12 +395,10 @@ 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); @@ -444,12 +426,10 @@ 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); @@ -495,11 +475,10 @@ 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"; @@ -518,14 +497,8 @@ 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)); @@ -540,8 +513,7 @@ 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); @@ -576,8 +548,7 @@ 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); @@ -600,9 +571,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 { @@ -612,8 +583,7 @@ 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(); @@ -648,15 +618,12 @@ 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)); @@ -667,7 +634,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"); } } @@ -687,12 +654,9 @@ 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"; @@ -714,24 +678,18 @@ 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")); } /** @@ -743,43 +701,36 @@ 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 @@ -791,7 +742,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 { @@ -803,36 +754,28 @@ 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()); r.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()); } /** @@ -843,7 +786,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()); @@ -868,8 +811,7 @@ 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()); } @@ -881,7 +823,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()); @@ -906,8 +848,7 @@ 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()); } @@ -919,7 +860,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()); @@ -936,10 +877,7 @@ 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"); @@ -948,8 +886,7 @@ 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()); } @@ -961,7 +898,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()); @@ -978,10 +915,7 @@ 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"); @@ -991,8 +925,7 @@ 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()); } @@ -1004,7 +937,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()); @@ -1030,8 +963,7 @@ 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()); } @@ -1043,7 +975,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()); @@ -1069,8 +1001,7 @@ 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()); } @@ -1083,7 +1014,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()); @@ -1100,10 +1031,7 @@ 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"); @@ -1112,8 +1040,7 @@ 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()); } @@ -1126,7 +1053,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()); @@ -1144,10 +1071,7 @@ 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"); @@ -1156,8 +1080,7 @@ 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()); } @@ -1171,39 +1094,32 @@ 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()); r.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 @@ -1216,22 +1132,16 @@ 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()); @@ -1242,9 +1152,7 @@ public void testBasicExcludedRegion() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.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) { @@ -1261,8 +1169,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"; @@ -1311,33 +1219,21 @@ 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()); } /* @@ -1426,21 +1322,15 @@ 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()); @@ -1451,46 +1341,36 @@ public void testBasicExcludedUser() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.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()); r.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") @@ -1508,25 +1388,19 @@ 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()); r.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 @@ -1540,29 +1414,21 @@ 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 @@ -1570,36 +1436,28 @@ 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 @@ -1612,14 +1470,12 @@ 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) { @@ -1664,9 +1520,7 @@ 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); @@ -1692,17 +1546,15 @@ 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"); @@ -1711,13 +1563,9 @@ 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); @@ -1725,24 +1573,17 @@ 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()); } /* @@ -1766,13 +1607,9 @@ 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); @@ -1782,20 +1619,17 @@ 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: @@ -1819,7 +1653,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()); @@ -1840,10 +1674,9 @@ 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"); @@ -1858,31 +1691,32 @@ 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())); r.jenkins.rebuildDependencyGraph(); + FreeStyleBuild ub = r.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 - Thread.sleep(100); + for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop + Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); - assertNotNull("downstream build didn't happen", db); + assertNotNull("downstream build didn't happen",db); db = r.waitForCompletion(db); r.assertBuildStatusSuccess(db); } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) - public static void assertCulprits(String assertMsg, Set actual, PersonIdent[] expected) { - List fullNames = actual.stream().map(User::getFullName).collect(Collectors.toList()); + static public 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())); } } @@ -1893,10 +1727,9 @@ 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(); @@ -1923,8 +1756,10 @@ 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()); @@ -1937,30 +1772,23 @@ 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(); @@ -1972,7 +1800,7 @@ public void testEmailCommitter() throws Exception { r.assertBuildStatusSuccess(build); } - + @Issue("JENKINS-59868") @Test public void testNonExistentWorkingDirectoryPoll() throws Exception { @@ -1983,10 +1811,9 @@ 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); @@ -2002,13 +1829,10 @@ 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 @@ -2023,7 +1847,10 @@ 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"; @@ -2034,23 +1861,17 @@ 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()); r.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 { @@ -2066,7 +1887,10 @@ 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); r.assertBuildStatusSuccess(build); @@ -2102,18 +1926,14 @@ 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"); @@ -2124,12 +1944,10 @@ 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)); } @@ -2153,12 +1971,9 @@ public void testMerge() throws Exception { GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), - null, - null, + null, null, Collections.emptyList()); - scm.getExtensions() - .add(new GitSCMSlowTest.TestPreBuildMerge(new UserMergeOptions( - "origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); + scm.getExtensions().add(new GitSCMSlowTest.TestPreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); addChangelogToBranchExtension(scm); project.setScm(scm); @@ -2173,9 +1988,7 @@ 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"); @@ -2183,15 +1996,11 @@ 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()); r.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") @@ -2203,12 +2012,9 @@ 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); @@ -2230,10 +2036,7 @@ 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 @@ -2244,13 +2047,10 @@ 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: @@ -2264,69 +2064,56 @@ 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()); r.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"); @@ -2347,9 +2134,8 @@ 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",""); } } @@ -2359,8 +2145,7 @@ public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) @Test public void testDataCompatibility1() throws Exception { assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); - FreeStyleProject p = (FreeStyleProject) - r.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); + FreeStyleProject p = (FreeStyleProject) r.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); @@ -2389,65 +2174,46 @@ public void testCheckoutReturnsLatestValues() throws Exception { WorkflowJob p = r.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 = r.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_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, "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; @@ -2456,7 +2222,7 @@ private String getLineStartsWith(String text, String startOfLine) { } return ""; } - + @Test public void testPleaseDontContinueAnyway() throws Exception { /* Wastes time waiting for the build to fail */ @@ -2467,7 +2233,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())); @@ -2490,24 +2256,22 @@ public void testCheckoutToSpecificBranch() throws Exception { p.setScm(oldGit); FreeStyleBuild b = r.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
      * 
@@ -2515,24 +2279,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
      * 
@@ -2540,17 +2304,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)); } /* @@ -2559,33 +2323,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)); } /* @@ -2594,16 +2358,15 @@ 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()); @@ -2645,9 +2408,7 @@ 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()); @@ -2680,6 +2441,7 @@ public void testNormalCheckoutAfterSparseCheckout() throws Exception { assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); + } @Test @@ -2691,8 +2453,7 @@ 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"))); @@ -2703,16 +2464,17 @@ 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 @@ -2720,7 +2482,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); @@ -2730,7 +2492,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") @@ -2755,24 +2517,21 @@ 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(); r.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); @@ -2783,11 +2542,10 @@ 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; @@ -2817,39 +2575,37 @@ 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(); r.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 @@ -2860,8 +2616,7 @@ 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); @@ -2876,8 +2631,7 @@ 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(); r.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); @@ -2897,14 +2651,8 @@ 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); @@ -2913,14 +2661,9 @@ private int notifyAndCheckScmName( 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()); @@ -2928,15 +2671,15 @@ private int notifyAndCheckScmName( 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 @@ -2979,129 +2722,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"); - - /* This is the null that causes NPE */ - Branch branch = new Branch("origin/master", sha1); + assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); - List branchList = new ArrayList<>(); - branchList.add(branch); + /* This is the null that causes NPE */ + Branch branch = new Branch("origin/master", sha1); - Revision revision = new Revision(sha1, branchList); + List branchList = new ArrayList<>(); + branchList.add(branch); - /* 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); + Revision revision = new Revision(sha1, branchList); - /* List of build data that will be returned by the mocked BuildData */ - List buildDataList = new ArrayList<>(); - buildDataList.add(buildData); + /* 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); - /* 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); + /* List of build data that will be returned by the mocked BuildData */ + List buildDataList = new ArrayList<>(); + buildDataList.add(buildData); - final FreeStyleProject project = setupProject("*/*", false); - GitSCM scm = (GitSCM) project.getScm(); - scm.getExtensions().add(new LocalBranch("")); + /* 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); - EnvVars env = new EnvVars(); - scm.buildEnvVars(build, env); // NPE here before fix applied + final FreeStyleProject project = setupProject("*/*", false); + GitSCM scm = (GitSCM) project.getScm(); + scm.getExtensions().add(new LocalBranch("")); - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + 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")); - /* 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); - - final FreeStyleProject project = setupProject("*/*", false); - GitSCM scm = (GitSCM) project.getScm(); + /* 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); - EnvVars env = new EnvVars(); - scm.buildEnvVars(build, env); // NPE here before fix applied + final FreeStyleProject project = setupProject("*/*", false); + GitSCM scm = (GitSCM) project.getScm(); - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); + EnvVars env = new EnvVars(); + scm.buildEnvVars(build, env); // NPE here before fix applied + + 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 @@ -3174,8 +2917,7 @@ 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); @@ -3199,7 +2941,7 @@ public void testCommitMessageIsPrintedToLogs() throws Exception { sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); FreeStyleProject p = setupSimpleProject("master"); - Run run = r.buildAndAssertSuccess(p); + Run run = r.buildAndAssertSuccess(p); r.waitForMessage("Commit message: \"test commit\"", run); } @@ -3213,24 +2955,18 @@ 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)); } @@ -3246,16 +2982,14 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); - final String notificationPath = - r.getURL().toExternalForm() + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; + final String notificationPath = r.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) && (r.jenkins.getQueue().isEmpty())) { @@ -3273,10 +3007,8 @@ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws } private void setupJGit(GitSCM git) { - git.gitTool = "jgit"; - r.jenkins - .getDescriptorByType(GitTool.DescriptorImpl.class) - .setInstallations(new JGitTool(Collections.emptyList())); + git.gitTool="jgit"; + r.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 :). */ @@ -3301,7 +3033,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 74a93c31dd..c94836e3a4 100644 --- a/src/test/java/hudson/plugins/git/GitSCMUnitTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMUnitTest.java @@ -23,15 +23,9 @@ */ 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; @@ -47,7 +41,12 @@ 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 { @@ -55,7 +54,8 @@ 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,22 +87,13 @@ 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)); } @@ -231,48 +222,36 @@ 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()); } @@ -282,7 +261,9 @@ 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()); } @@ -291,12 +272,9 @@ 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)); } @@ -314,12 +292,9 @@ 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()); } @@ -333,9 +308,7 @@ 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())); } @@ -371,12 +344,9 @@ 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 81d0f423fd..2f64477128 100644 --- a/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusCrumbExclusionTest.java @@ -1,19 +1,21 @@ 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. */ @@ -58,8 +60,7 @@ 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); } @@ -255,8 +256,7 @@ 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/GitStatusSimpleTest.java b/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java index 7eded3470a..298490ea05 100644 --- a/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusSimpleTest.java @@ -2,9 +2,9 @@ import static org.junit.Assert.*; +import org.eclipse.jgit.transport.URIish; import java.util.ArrayList; import java.util.List; -import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/hudson/plugins/git/GitStatusTest.java b/src/test/java/hudson/plugins/git/GitStatusTest.java index 2b19594e6d..74561ba0ce 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTest.java @@ -1,9 +1,5 @@ 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; @@ -21,19 +17,26 @@ import hudson.util.RunList; import java.io.File; 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 javax.servlet.http.HttpServletRequest; +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 org.junit.After; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; + +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 { @@ -56,8 +59,7 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (r.jenkins != null) { - this.notifyCommitApiToken = - ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -97,8 +99,7 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); r.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); } }); } @@ -160,8 +161,7 @@ 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(); @@ -256,8 +256,7 @@ 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); } @@ -294,8 +293,7 @@ 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(); } @@ -303,29 +301,25 @@ 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); @@ -337,8 +331,7 @@ 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); @@ -350,8 +343,7 @@ 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 @@ -377,11 +369,12 @@ 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 @@ -404,8 +397,7 @@ 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); } @@ -435,7 +427,9 @@ 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 @@ -460,7 +454,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 { @@ -486,12 +480,14 @@ 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(); r.waitForMessage("aaa aaaccc ccc", build); @@ -518,8 +514,7 @@ 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 } /** @@ -538,8 +533,7 @@ 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); @@ -563,13 +557,12 @@ 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 @@ -593,8 +586,7 @@ 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"); @@ -621,10 +613,7 @@ 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 @@ -637,10 +626,7 @@ 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 @@ -650,8 +636,7 @@ 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 2a4f27ac67..cf9ce2af1d 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java @@ -1,8 +1,5 @@ package hudson.plugins.git; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - import hudson.model.FreeStyleProject; import hudson.model.Run; import hudson.model.View; @@ -12,7 +9,10 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import javax.servlet.http.HttpServletRequest; +import org.mockito.Mockito; +import static org.mockito.Mockito.mock; + +import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.experimental.theories.DataPoints; @@ -20,7 +20,8 @@ import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; -import org.mockito.Mockito; + +import javax.servlet.http.HttpServletRequest; @RunWith(Theories.class) public class GitStatusTheoriesTest extends AbstractGitProject { @@ -44,8 +45,7 @@ public void setUp() throws Exception { this.branch = "**"; this.sha1 = "7bb68ef21dc90bd4f7b08eca876203b2e049198d"; if (r.jenkins != null) { - this.notifyCommitApiToken = - ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); + this.notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); } } @@ -88,29 +88,30 @@ public void waitForAllJobsToComplete() throws Exception { Logger.getLogger(GitStatusTheoriesTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); r.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); @@ -118,17 +119,14 @@ 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); @@ -140,8 +138,7 @@ 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); diff --git a/src/test/java/hudson/plugins/git/GitTagActionTest.java b/src/test/java/hudson/plugins/git/GitTagActionTest.java index bf7379974a..2e70a2c44d 100644 --- a/src/test/java/hudson/plugins/git/GitTagActionTest.java +++ b/src/test/java/hudson/plugins/git/GitTagActionTest.java @@ -1,18 +1,5 @@ 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.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.IOException; import java.io.StringWriter; @@ -27,13 +14,32 @@ import java.util.Map; import java.util.Random; import java.util.Set; -import javax.servlet.ServletException; -import jenkins.plugins.git.GitSampleRepoRule; + +import hudson.EnvVars; +import hudson.Extension; +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 org.eclipse.jgit.lib.ObjectId; -import org.htmlunit.html.HtmlForm; -import org.htmlunit.html.HtmlPage; +import org.eclipse.jgit.util.SystemReader; 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 org.htmlunit.html.HtmlForm; +import org.htmlunit.html.HtmlPage; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -42,6 +48,8 @@ import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import javax.servlet.ServletException; + /** * Test git tag action. Low value test that was created as part of * another investigation. @@ -72,7 +80,8 @@ public class GitTagActionTest { @ClassRule public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - public GitTagActionTest() {} + public GitTagActionTest() { + } private static FreeStyleProject p; private static GitClient workspaceGitClient = null; @@ -213,9 +222,7 @@ 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 */ @@ -281,16 +288,17 @@ public TestTagWorkerThread(Map tagSet, String ignoredComment) { } @Override - protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) - throws IOException, InterruptedException { + protected GitClient getGitClient(TaskListener listener, EnvVars environment, FilePath workspace) throws IOException, InterruptedException { GitClient gitClient = super.getGitClient(listener, environment, workspace); gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); gitClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); return gitClient; } } + } + private static Set getMatchingTagNames() throws Exception { Set tags = workspaceGitClient.getTags(); Set matchingTagNames = new HashSet<>(); diff --git a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java index 3a4ba43f4d..8fe98e3bf4 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java @@ -3,15 +3,19 @@ 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 a2c93ace55..b8f8d6108a 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java @@ -9,14 +9,18 @@ * 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 0d9390b036..545c4fecc7 100644 --- a/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java +++ b/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java @@ -1,17 +1,18 @@ 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 @@ -46,8 +47,7 @@ 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 43604b7624..b0e2628163 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.FreeStyleBuild; import hudson.model.FreeStyleProject; +import hudson.model.FreeStyleBuild; import hudson.model.Result; import hudson.plugins.git.util.BuildData; + import java.util.Collections; +import static org.junit.Assert.*; import org.junit.Test; /** @@ -57,25 +57,21 @@ 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/Security2478Test.java b/src/test/java/hudson/plugins/git/Security2478Test.java index dd1ea1cbd9..b7476342e1 100644 --- a/src/test/java/hudson/plugins/git/Security2478Test.java +++ b/src/test/java/hudson/plugins/git/Security2478Test.java @@ -1,9 +1,6 @@ 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; @@ -15,6 +12,10 @@ 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 @@ -23,6 +24,7 @@ public class Security2478Test { @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + @Before public void setUpAllowNonRemoteCheckout() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; @@ -43,15 +45,13 @@ public void checkoutShouldNotAbortWhenLocalSourceAndRunningOnAgent() throws Exce sampleRepo.git("commit", "--all", "--message=test commit"); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "pipeline"); - String script = "node {\n" - + " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" - + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + "}"; + String script = "node {\n" + + " checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '" + sampleRepo.fileUrl() + "', credentialsId: '']]])\n" + + "}"; p.setDefinition(new CpsFlowDefinition(script, true)); WorkflowRun run = r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0)); - r.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); + r.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,17 +63,15 @@ 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 = r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0)); - r.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); + r.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 0dd8e97fea..a53c348d0a 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git; -import static org.junit.Assert.*; - import hudson.EnvVars; import hudson.model.TaskListener; import hudson.util.StreamTaskListener; @@ -15,6 +13,7 @@ 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; @@ -23,13 +22,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 a32614d7c8..82df452e5d 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java @@ -23,16 +23,15 @@ */ 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 6c51c98ac2..b21275fcef 100644 --- a/src/test/java/hudson/plugins/git/TestGitRepo.java +++ b/src/test/java/hudson/plugins/git/TestGitRepo.java @@ -4,58 +4,59 @@ import hudson.EnvVars; import hudson.FilePath; import hudson.model.TaskListener; -import hudson.model.User; import hudson.model.UserProperty; +import hudson.model.User; 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(); git.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); git.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); - } - + } + /** * Creates a commit in current repo. * @param fileName relative path to the file to be committed with default content @@ -80,8 +81,7 @@ 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); } @@ -96,8 +96,7 @@ public String commit( * @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); } @@ -113,13 +112,8 @@ public String commit( * @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 802abddff9..ad1a230859 100644 --- a/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git; -import static org.junit.Assert.*; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -11,8 +9,9 @@ import nl.jqno.equalsverifier.Warning; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.structs.describable.DescribableModel; -import org.junit.ClassRule; import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.ClassRule; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.jvnet.hudson.test.Issue; @@ -32,9 +31,11 @@ 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( @@ -47,16 +48,19 @@ 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, @@ -65,7 +69,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, @@ -101,16 +105,12 @@ 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,12 +118,8 @@ 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()); } @@ -238,4 +234,5 @@ 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 b65db833d9..d96eb41ef1 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java @@ -1,18 +1,20 @@ package hudson.plugins.git; -import static org.junit.Assert.assertEquals; - import hudson.util.FormValidation; -import java.util.ArrayList; -import java.util.List; import org.junit.Test; import org.jvnet.hudson.test.Issue; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + + 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<>(); @@ -22,14 +24,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<>(); @@ -37,14 +39,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<>(); @@ -52,50 +54,52 @@ 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 b3576fc1f5..604478f6fa 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java @@ -1,12 +1,8 @@ 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; @@ -15,9 +11,12 @@ 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.Rule; import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.Rule; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; @@ -30,24 +29,15 @@ 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"); @@ -59,24 +49,16 @@ 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 ddb3446b32..9bc582c005 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java @@ -1,8 +1,5 @@ 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; @@ -10,11 +7,13 @@ 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; @@ -40,16 +39,15 @@ 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")); } @@ -72,25 +70,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 @@ -98,8 +96,7 @@ 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)); } @@ -108,8 +105,7 @@ 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)); } @@ -118,8 +114,7 @@ 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 bbf994404c..dcec85f797 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import static org.junit.Assert.*; - import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -9,6 +7,7 @@ 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; @@ -72,4 +71,5 @@ 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 39580450aa..bbfad4818e 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java @@ -1,15 +1,17 @@ /** * Copyright 2010 Mirko Friedenhagen */ -package hudson.plugins.git.browser; -import static org.junit.Assert.*; +package hudson.plugins.git.browser; 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; @@ -17,8 +19,7 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; +import static org.junit.Assert.*; import org.junit.Test; /** @@ -50,15 +51,11 @@ 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)); @@ -66,17 +63,15 @@ 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)); @@ -86,13 +81,9 @@ 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 5dba4d93a3..130924f9b1 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java @@ -1,15 +1,17 @@ /** * Copyright 2010 Mirko Friedenhagen */ -package hudson.plugins.git.browser; -import static org.junit.Assert.*; +package hudson.plugins.git.browser; 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; @@ -17,8 +19,7 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; +import static org.junit.Assert.*; import org.junit.Test; /** @@ -51,15 +52,11 @@ 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)); @@ -67,17 +64,15 @@ 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)); @@ -87,13 +82,9 @@ 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 09d31a0b0f..3469f6d91f 100644 --- a/src/test/java/hudson/plugins/git/browser/CGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/CGitTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import static org.junit.Assert.*; - import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -9,6 +7,7 @@ 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; @@ -80,4 +79,5 @@ 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 454d5b7e9c..3d439a2eff 100644 --- a/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import static org.junit.Assert.*; - import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -9,6 +7,7 @@ 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; @@ -57,8 +56,7 @@ 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 749d06d9d6..f61278189d 100644 --- a/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import static org.junit.Assert.*; - import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -11,6 +9,7 @@ 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; @@ -50,12 +49,9 @@ 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); } @@ -69,9 +65,7 @@ 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 6891b31d94..dbf0ae77fa 100644 --- a/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java +++ b/src/test/java/hudson/plugins/git/browser/GitChangeSetSample.java @@ -31,18 +31,10 @@ 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 6d897c92c3..f5880e736d 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabTest.java @@ -1,19 +1,20 @@ 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 org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; @Deprecated @@ -25,8 +26,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); @@ -70,9 +71,7 @@ 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()); @@ -81,9 +80,7 @@ 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()); } @@ -104,7 +101,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()); @@ -140,7 +137,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()); @@ -150,23 +147,20 @@ 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 6d6cb93f43..3f94625476 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java @@ -12,7 +12,6 @@ public class GitLabWorkflowTest { @Rule public JenkinsRule r = new JenkinsRule(); - @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); @@ -22,15 +21,14 @@ 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 } @@ -48,8 +46,7 @@ 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 47558f7ffe..18af537757 100644 --- a/src/test/java/hudson/plugins/git/browser/GitListTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitListTest.java @@ -1,15 +1,17 @@ /** * Copyright 2010 Mirko Friedenhagen */ -package hudson.plugins.git.browser; -import static org.junit.Assert.*; +package hudson.plugins.git.browser; 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; @@ -17,8 +19,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; /** @@ -50,31 +52,24 @@ 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)); @@ -84,13 +79,9 @@ 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 3e57255caf..9232ef5b3d 100644 --- a/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java @@ -1,12 +1,15 @@ 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; @@ -14,11 +17,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 da00f828be..615868a630 100644 --- a/src/test/java/hudson/plugins/git/browser/GitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitWebTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; public class GitWebTest { @@ -38,10 +39,7 @@ 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 @@ -49,34 +47,24 @@ 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 e64c00354a..7e87701404 100644 --- a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java @@ -1,9 +1,8 @@ /** * Copyright 2010 Mirko Friedenhagen */ -package hudson.plugins.git.browser; -import static org.junit.Assert.*; +package hudson.plugins.git.browser; import hudson.EnvVars; import hudson.model.TaskListener; @@ -12,6 +11,10 @@ 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; @@ -20,11 +23,10 @@ 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 org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; import org.jvnet.hudson.test.Issue; @@ -38,12 +40,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 @@ -54,7 +56,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); } @@ -62,91 +64,68 @@ 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)); @@ -163,21 +142,13 @@ 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/"); } } } @@ -192,21 +163,13 @@ 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); } @@ -214,34 +177,28 @@ 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() { @@ -257,13 +214,9 @@ 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); } @@ -275,4 +228,5 @@ 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 6dde6a706e..ba7018164b 100644 --- a/src/test/java/hudson/plugins/git/browser/GitilesTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitilesTest.java @@ -1,13 +1,12 @@ 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; @@ -47,8 +46,7 @@ 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); } } @@ -59,8 +57,7 @@ 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 c050d3ddf2..09b44e6fab 100644 --- a/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; public class GitoriousWebTest { @@ -25,12 +26,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 @@ -43,51 +44,35 @@ 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 3afcf76595..81d1806eca 100644 --- a/src/test/java/hudson/plugins/git/browser/GogsGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/GogsGitTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; /** @@ -28,12 +29,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 @@ -46,13 +47,9 @@ 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)); } @@ -62,15 +59,12 @@ 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)); @@ -80,13 +74,9 @@ 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 cd1d527044..61f75c1a5b 100644 --- a/src/test/java/hudson/plugins/git/browser/KilnGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/KilnGitTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; /** @@ -28,12 +29,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 @@ -46,31 +47,24 @@ 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)); @@ -80,13 +74,9 @@ 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 97a267b9fb..904404e43d 100644 --- a/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java +++ b/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java @@ -1,11 +1,10 @@ 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 { @@ -35,8 +34,7 @@ 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); } @@ -46,10 +44,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 adeaabd2e9..af0fb384de 100644 --- a/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; +import static org.junit.Assert.*; 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,54 +46,37 @@ 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 e35cd23e5c..f080d4e991 100644 --- a/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java +++ b/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; public class RhodeCodeTest { @@ -25,12 +26,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 @@ -43,32 +44,23 @@ 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)); @@ -78,13 +70,9 @@ 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 64736f2feb..b6398c3f85 100644 --- a/src/test/java/hudson/plugins/git/browser/StashTest.java +++ b/src/test/java/hudson/plugins/git/browser/StashTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.browser; -import static org.junit.Assert.*; - import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; import java.net.URL; @@ -9,6 +7,7 @@ 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; @@ -50,11 +49,9 @@ 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 da55444b28..ae3806d0e9 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java @@ -1,22 +1,23 @@ 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 java.net.URL; -import java.util.ArrayList; -import java.util.Collections; 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; + public class TFS2013GitRepositoryBrowserTest { private static final String repoUrl = "http://tfs/tfs/project/_git/repo"; @@ -27,8 +28,7 @@ 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,8 +71,7 @@ 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); } @@ -84,8 +83,7 @@ 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 f4d0553b68..10d6198b78 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java @@ -1,12 +1,9 @@ package hudson.plugins.git.browser; +import org.htmlunit.html.HtmlPage; 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.htmlunit.html.HtmlPage; import org.jenkinsci.plugins.gitclient.JGitTool; import org.junit.Assert; import org.junit.Rule; @@ -14,6 +11,10 @@ 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 @@ -26,8 +27,7 @@ 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 a0c4ae405b..bdd2ac3335 100644 --- a/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java @@ -1,12 +1,13 @@ 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; @@ -14,8 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import org.jenkinsci.plugins.gitclient.Git; -import org.jenkinsci.plugins.gitclient.GitClient; + +import static org.junit.Assert.*; import org.junit.Test; /** @@ -40,24 +41,16 @@ 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)); } @@ -67,17 +60,16 @@ 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 @@ -85,22 +77,16 @@ 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 2c3953cd4f..ca8d3e658e 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 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.assertTrue; - 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.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; + public class GitLabConfiguratorTest { private final GitLabConfigurator configurator = new GitLabConfigurator(); @@ -50,8 +50,7 @@ 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")); } @@ -80,6 +79,7 @@ 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,6 +94,7 @@ public void testInstanceWithNullRepo() throws Exception { assertEquals(String.valueOf(expectedConfiguration.getVersion()), String.valueOf(instance.getVersion())); } + @Test @Deprecated public void testInstanceWithEmptyVersion() throws Exception { @@ -144,4 +145,5 @@ 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 991b6e9e59..60ebf1d205 100644 --- a/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java @@ -5,8 +5,6 @@ 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; @@ -17,73 +15,79 @@ 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 r = new JenkinsRule(); + @Rule + public JenkinsRule r = 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) { - r.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) { + r.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 = r.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 = r.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 c80fe49396..b4ac5866fa 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java @@ -1,16 +1,18 @@ package hudson.plugins.git.extensions.impl; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class AuthorInChangelogTest { @Test public void equalsContract() { - EqualsVerifier.forClass(AuthorInChangelog.class).usingGetClass().verify(); + EqualsVerifier.forClass(AuthorInChangelog.class) + .usingGetClass() + .verify(); } @Test @@ -18,4 +20,5 @@ 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 86ac43942a..8df2bfaf84 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java @@ -7,17 +7,19 @@ 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 { @@ -44,8 +46,7 @@ public void waitForAllJobsToComplete() { Logger.getLogger(GitStatusTest.class.getName()).log(Level.INFO, "Waiting for {0}", run); r.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); } }); } @@ -57,7 +58,9 @@ 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"; @@ -75,8 +78,8 @@ public void testSingleRevision() throws Exception { final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile); r.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); } @@ -87,7 +90,9 @@ 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 d30d12971f..0db3c9bf2d 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java @@ -1,18 +1,19 @@ 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 f67c525ee6..1d0822716a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java @@ -1,7 +1,5 @@ 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; @@ -14,13 +12,15 @@ 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 683f6a7375..371a4d3063 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java @@ -12,7 +12,6 @@ public class CheckoutOptionWorkflowTest { @Rule public JenkinsRule r = new JenkinsRule(); - @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); @@ -22,14 +21,13 @@ 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 2e6db959f6..82e71d7d08 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 0bb7191099..f51efc61d7 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java @@ -4,13 +4,14 @@ 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; @@ -44,7 +45,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 39d042e7e6..d963bd4923 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java @@ -1,8 +1,5 @@ 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; @@ -15,12 +12,6 @@ import hudson.tasks.BatchFile; import hudson.tasks.Builder; import hudson.tasks.Shell; -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 org.jenkinsci.plugins.gitclient.JGitTool; import org.junit.Before; import org.junit.Test; @@ -28,6 +19,15 @@ 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.*; + @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,7 +74,8 @@ 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 = r.buildAndAssertSuccess(project); @@ -103,9 +104,8 @@ 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,8 +122,7 @@ 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. @@ -132,10 +131,8 @@ 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 a8a3975f8f..675a3b0818 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java @@ -3,13 +3,15 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import hudson.model.FreeStyleProject; +import java.io.IOException; +import java.util.Set; + import hudson.model.Result; +import hudson.model.FreeStyleProject; import hudson.plugins.git.TestGitRepo; -import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; -import java.io.IOException; -import java.util.Set; +import hudson.plugins.git.extensions.GitSCMExtension; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; @@ -43,15 +45,11 @@ 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 @@ -59,23 +57,17 @@ 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 d0a4a40295..4778c9e8c7 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java @@ -2,14 +2,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - -import hudson.model.FreeStyleProject; import hudson.model.Result; +import hudson.model.FreeStyleProject; import hudson.plugins.git.TestGitRepo; -import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; +import hudson.plugins.git.extensions.GitSCMExtension; + import java.io.IOException; import java.util.Set; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.junit.Test; @@ -43,16 +44,11 @@ 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 dc0bf6d414..e10f6e91f2 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java @@ -1,11 +1,10 @@ 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 25ec14db0d..341ae31b5c 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/EnforceGitClient.java @@ -4,6 +4,7 @@ import hudson.plugins.git.extensions.FakeGitSCMExtension; import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; + import org.kohsuke.stapler.DataBoundConstructor; /** @@ -12,19 +13,21 @@ 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 2d8075892c..a34b6d30c2 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java @@ -7,6 +7,8 @@ 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 3f70114798..c8816c0e9e 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java @@ -7,6 +7,8 @@ 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 2b889cd933..a8f046d5f5 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java @@ -1,16 +1,18 @@ package hudson.plugins.git.extensions.impl; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + 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 7275d9ba92..e3764a327e 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/LogHandler.java @@ -44,7 +44,8 @@ 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 b7e597a487..b0a072d9d4 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java @@ -1,64 +1,54 @@ 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 9d1738c096..b8799f51ec 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java @@ -1,21 +1,24 @@ package hudson.plugins.git.extensions.impl; -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 @@ -33,6 +36,7 @@ public void before() throws Exception { repo = new TestGitRepo("repo", tmp.newFolder(), listener); project = setupBasicProject(repo); } + } public static class NoRulesTest extends PathRestrictionExtensionTest { @@ -45,9 +49,7 @@ 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)); } } @@ -61,12 +63,11 @@ 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 @@ -77,17 +78,13 @@ 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)); } } @@ -101,20 +98,17 @@ 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 @@ -125,33 +119,21 @@ 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)); } } @@ -164,39 +146,24 @@ 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 02d2940b21..7f784ed73a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.extensions.impl; -import static org.junit.Assert.*; - import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; @@ -16,10 +14,13 @@ 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; @@ -44,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()); @@ -56,54 +57,37 @@ 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 db01be31dd..ee7dc7170a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java @@ -7,6 +7,8 @@ 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 66c7ded44c..bc6d7d0575 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java @@ -24,17 +24,13 @@ */ package hudson.plugins.git.extensions.impl; -import hudson.FilePath; -import hudson.Functions; -import hudson.model.Result; -import hudson.model.TaskListener; -import hudson.plugins.git.GitSCM; -import hudson.plugins.git.util.GitUtilsTest; -import hudson.util.LogTaskListener; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; + +import hudson.plugins.git.GitSCM; +import hudson.plugins.git.util.GitUtilsTest; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.util.SystemReader; @@ -52,11 +48,16 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +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(); @@ -94,18 +95,16 @@ 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(); @@ -139,4 +138,5 @@ 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 f711f208b9..ebcb8858c5 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java @@ -24,21 +24,13 @@ */ 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; @@ -49,6 +41,17 @@ 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 @@ -81,31 +84,22 @@ 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); localClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); localClient.config(GitClient.ConfigLevel.LOCAL, "tag.gpgSign", "false"); 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)); @@ -124,7 +118,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); @@ -153,7 +147,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); @@ -178,7 +172,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); @@ -197,7 +191,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"; @@ -208,9 +202,7 @@ 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 8faf98d96a..7a18475882 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java @@ -7,6 +7,8 @@ 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 916c333b20..5e8ca27aae 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java @@ -23,25 +23,27 @@ */ package hudson.plugins.git.extensions.impl; -import static org.hamcrest.MatcherAssert.*; -import static org.hamcrest.Matchers.*; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; 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; @@ -185,5 +187,6 @@ 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 73f37df304..42b2ae9906 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java @@ -4,13 +4,14 @@ 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; @@ -38,7 +39,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 a3c283855c..dbd659b760 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java @@ -1,25 +1,30 @@ 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; @@ -32,8 +37,7 @@ 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, @@ -64,8 +68,7 @@ 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")); } @@ -89,8 +92,7 @@ public void testIsDisableSubmodules() { @Test public void testIsDisableSubmodulesTrue() { - submoduleOption = new SubmoduleOption( - true, + submoduleOption = new SubmoduleOption(true, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, SUBMODULES_REFERENCE_REPOSITORY, @@ -106,8 +108,7 @@ 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, @@ -123,8 +124,7 @@ 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,8 +140,7 @@ 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, @@ -158,8 +157,7 @@ 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, @@ -176,8 +174,7 @@ 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, @@ -232,37 +229,33 @@ 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 @@ -281,8 +274,7 @@ 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 7ff1046c32..d0c1dda03b 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java @@ -1,8 +1,5 @@ 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; @@ -10,52 +7,48 @@ 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 { +public class UserExclusionTest extends GitSCMExtensionTest{ + + FreeStyleProject project; + TestGitRepo repo; - FreeStyleProject project; - TestGitRepo repo; + @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); - } + @Override + protected GitSCMExtension getExtension() { + return new UserExclusion("Jane Doe"); + } - @Override - protected GitSCMExtension getExtension() { - return new UserExclusion("Jane Doe"); - } + @Test + public void test() throws Exception { - @Test - public void test() throws Exception { + repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - 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, "excluded user commit"); - repo.commit("repo-init", repo.janeDoe, "excluded user commit"); + assertFalse("scm polling should ignore excluded user", project.poll(listener).hasChanges()); - assertFalse( - "scm polling should ignore excluded user", - 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/UserIdentityTest.java b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java index 5f9603d2d8..f702cb0874 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java @@ -1,8 +1,5 @@ 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; @@ -17,7 +14,10 @@ import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; -public class UserIdentityTest extends GitSCMExtensionTest { +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +public class UserIdentityTest extends GitSCMExtensionTest { TestGitRepo repo; GitClient git; @@ -35,9 +35,7 @@ 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"); @@ -50,7 +48,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())); @@ -60,6 +58,8 @@ 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 6471589135..6c18dfdc9a 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java @@ -1,8 +1,5 @@ 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; @@ -17,6 +14,9 @@ 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,6 +51,8 @@ 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 4e642c71b7..459b468860 100644 --- a/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java @@ -31,32 +31,20 @@ import hudson.plugins.git.extensions.impl.PreBuildMerge; import java.util.Collections; import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.junit.Rule; import org.junit.Test; +import org.junit.Rule; 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 62935303e4..9197f6bb8d 100644 --- a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java +++ b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java @@ -1,25 +1,26 @@ 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 hudson.plugins.git.ApiTokenPropertyConfiguration; -import java.util.Collection; -import java.util.Collections; -import jenkins.model.Jenkins; -import net.sf.json.JSONObject; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; import org.htmlunit.WebResponse; import org.htmlunit.util.NameValuePair; +import hudson.plugins.git.ApiTokenPropertyConfiguration; +import jenkins.model.Jenkins; +import net.sf.json.JSONObject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; 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 @@ -39,8 +40,7 @@ public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception try (JenkinsRule.WebClient wc = r.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,9 +55,7 @@ public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception public void adminPermissionsRequiredToRevokeApiTokens() throws Exception { try (JenkinsRule.WebClient wc = r.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(); @@ -72,41 +70,45 @@ public void testBasicGenerationAndRevocation() throws Exception { try (JenkinsRule.WebClient wc = r.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)) + ) + ) + )); } } @@ -116,4 +118,5 @@ 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 88456039c5..87c2c706c1 100644 --- a/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java +++ b/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.util; -import static org.junit.Assert.*; - import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.AbstractGitRepository; @@ -10,117 +8,119 @@ 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 org.junit.Before; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; import org.junit.Test; import org.mockito.Mockito; -public class AncestryBuildChooserTest extends AbstractGitRepository { +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) cmd.setAuthor(author); + if (author != null) + cmd.setAuthor(author); if (committer != null) // cmd.setCommitter(new PersonIdent(committer,new Date())); cmd.setCommitter(committer); @@ -129,115 +129,114 @@ private void commit(String message, PersonIdent author, PersonIdent committer) { 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 ccc85f43fc..bff6e26a87 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 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 static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -77,9 +77,11 @@ 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 2aadaf085b..fb47137281 100644 --- a/src/test/java/hudson/plugins/git/util/BuildDataTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildDataTest.java @@ -1,24 +1,26 @@ 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; @@ -262,9 +264,7 @@ 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,32 +396,31 @@ 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)); } @@ -485,9 +484,7 @@ 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 353da36fbc..73c580da96 100644 --- a/src/test/java/hudson/plugins/git/util/BuildTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildTest.java @@ -1,8 +1,5 @@ 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; @@ -10,6 +7,9 @@ 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 eaac28c9c8..fa66a703ce 100644 --- a/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java +++ b/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java @@ -1,7 +1,5 @@ package hudson.plugins.git.util; -import static org.junit.Assert.*; - import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.AbstractGitRepository; @@ -12,14 +10,15 @@ 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 { @@ -87,8 +86,7 @@ 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()) @@ -100,8 +98,7 @@ 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); @@ -111,16 +108,9 @@ 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 52a0105399..1f421cb89e 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,36 +21,35 @@ 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 ea6b2e79a7..e7e42598f4 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 hudson.plugins.git.GitSCM; -import hudson.plugins.git.Revision; import java.util.Collection; import java.util.HashSet; + +import hudson.plugins.git.GitSCM; +import hudson.plugins.git.Revision; 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,14 +29,12 @@ 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())); } @@ -64,12 +62,11 @@ 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)); } @@ -84,12 +81,11 @@ 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)); } @@ -105,7 +101,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)); } @@ -121,8 +117,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)); } @@ -130,8 +126,7 @@ 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; @@ -140,7 +135,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)); } @@ -157,7 +152,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 6381da50d2..e58b3b031a 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java @@ -23,9 +23,6 @@ */ 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; @@ -36,6 +33,9 @@ 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 c2ec8b8824..5e793eeb13 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsTest.java @@ -23,11 +23,6 @@ */ 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; @@ -44,8 +39,12 @@ 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; @@ -60,7 +59,12 @@ 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; @@ -77,7 +81,11 @@ 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 2cadc2bdbb..e6b8ccee19 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java @@ -1,30 +1,5 @@ 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; @@ -41,13 +16,13 @@ import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitException; -import hudson.plugins.git.GitSCM; 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.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; @@ -63,10 +38,18 @@ 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; @@ -90,29 +73,44 @@ 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(); @@ -127,8 +125,7 @@ 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 @@ -236,32 +233,25 @@ 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()); @@ -269,8 +259,7 @@ 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()); } @@ -294,13 +283,9 @@ 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") @@ -326,8 +311,7 @@ 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") @@ -354,8 +338,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"); @@ -373,8 +357,7 @@ 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 */ @@ -413,19 +396,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); @@ -476,9 +459,12 @@ 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 abstract static class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner {} + public static abstract class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner { + + } @Test @Deprecated @@ -522,18 +508,17 @@ 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; @@ -551,7 +536,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; @@ -579,7 +564,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(); @@ -618,7 +603,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(); @@ -646,7 +631,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(); @@ -676,10 +661,12 @@ 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)); @@ -705,15 +692,17 @@ 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)); @@ -739,10 +728,12 @@ 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)); @@ -763,18 +754,14 @@ 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)); @@ -795,18 +782,15 @@ 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: @@ -814,15 +798,13 @@ 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(); } } @@ -847,18 +829,20 @@ 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") @@ -881,17 +865,20 @@ 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") @@ -933,9 +920,7 @@ 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 @@ -957,38 +942,48 @@ 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 { @@ -1011,15 +1006,7 @@ 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(); @@ -1028,9 +1015,7 @@ 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 */ @@ -1126,28 +1111,27 @@ 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(); @@ -1160,20 +1144,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 { @@ -1187,12 +1171,10 @@ 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"); @@ -1205,7 +1187,7 @@ public Map getRemoteReferences( @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) { @@ -1254,7 +1236,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 ddfaaaf286..6500a699d8 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java @@ -1,21 +1,22 @@ 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.Before; import org.junit.Test; + +import static org.junit.Assert.*; +import org.junit.Before; import org.mockito.Mockito; +import static org.mockito.Mockito.*; public class AbstractGitSCMSourceTrivialTest { @@ -208,4 +209,5 @@ 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 855fdeac3a..996181e239 100644 --- a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java @@ -1,14 +1,5 @@ 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; @@ -33,120 +24,231 @@ 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 468de36bcb..7406b92c6b 100644 --- a/src/test/java/jenkins/plugins/git/CliGitCommand.java +++ b/src/test/java/jenkins/plugins/git/CliGitCommand.java @@ -23,16 +23,14 @@ */ 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; @@ -42,8 +40,10 @@ 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,12 +97,7 @@ 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) { @@ -110,8 +105,7 @@ 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; } @@ -124,8 +118,7 @@ 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)); } } @@ -139,8 +132,7 @@ 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 + "'"); } } } @@ -158,9 +150,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"); + } } /** @@ -173,4 +165,5 @@ 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 a20a3d4bfb..0a24cbaffa 100644 --- a/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java +++ b/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java @@ -1,13 +1,7 @@ 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; @@ -18,18 +12,21 @@ 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 r = 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()) { @@ -53,6 +50,7 @@ public void removeRepos() throws IOException { } } + @Issue("JENKINS-48061") @Test @LocalData @@ -87,6 +85,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 9a4d1a5095..d7bea205aa 100644 --- a/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java +++ b/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java @@ -23,12 +23,6 @@ */ 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; @@ -43,6 +37,12 @@ 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,7 +54,8 @@ 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 9e321bb744..d5733251bf 100644 --- a/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java @@ -1,7 +1,5 @@ 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; @@ -11,12 +9,15 @@ 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 ada174cc43..f9f1f4c1c8 100644 --- a/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java +++ b/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java @@ -7,6 +7,8 @@ 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 135ab44607..11016cdf19 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java @@ -1,15 +1,5 @@ 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; @@ -24,25 +14,39 @@ 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 @@ -50,35 +54,26 @@ 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 @@ -87,16 +82,17 @@ 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 @@ -105,16 +101,17 @@ 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 @@ -123,68 +120,62 @@ 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 @@ -193,94 +184,87 @@ 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 @@ -289,16 +273,17 @@ 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 @@ -308,16 +293,17 @@ 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 @@ -326,88 +312,89 @@ 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 @@ -416,62 +403,63 @@ 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 @@ -485,16 +473,17 @@ 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 @@ -503,16 +492,17 @@ 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 @@ -521,79 +511,87 @@ 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 826d94b65a..64eb3718d5 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java @@ -25,24 +25,11 @@ 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.GitException; import hudson.plugins.git.GitSCM; +import hudson.plugins.git.GitException; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Collections; @@ -55,6 +42,7 @@ 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; @@ -66,6 +54,19 @@ 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} */ @@ -77,8 +78,8 @@ public class GitSCMFileSystemTest { @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - 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"; + 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"; /* 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 @@ -92,12 +93,9 @@ 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 { @@ -184,14 +182,7 @@ 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()); @@ -218,14 +209,11 @@ 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())); } @@ -314,7 +302,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": @@ -341,10 +329,7 @@ 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 = @@ -359,10 +344,7 @@ 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 = @@ -381,13 +363,9 @@ 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 = @@ -397,7 +375,8 @@ 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))); @@ -416,14 +395,7 @@ 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(); @@ -459,33 +431,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); } @@ -496,21 +468,17 @@ 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 679122be23..1b84d2f82a 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java @@ -1,18 +1,17 @@ package jenkins.plugins.git; -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; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + 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 9abcf45cb7..d61ec5d72f 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java @@ -7,6 +7,8 @@ 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 18a8d794cc..40efa21490 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java @@ -1,52 +1,34 @@ 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.plugins.git.ApiTokenPropertyConfiguration; +import hudson.EnvVars; +import hudson.FilePath; 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 javax.servlet.http.HttpServletRequest; + +import hudson.util.StreamTaskListener; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.plugins.git.traits.TagDiscoveryTrait; import jenkins.scm.api.SCMEventListener; @@ -66,9 +48,29 @@ 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 */ @@ -89,21 +91,20 @@ 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); r.getInstance().add(scmSourceOwner, "gitSourceOwner"); gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "", notifyCommitApiToken); - SCMHeadEvent event = r.getInstance() - .getExtensionList(SCMEventListener.class) - .get(SCMEventListenerImpl.class) - .waitSCMHeadEvent(1, TimeUnit.SECONDS); + SCMHeadEvent event = + r.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) { @@ -128,7 +129,8 @@ 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 { @@ -170,39 +172,40 @@ 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") @@ -215,47 +218,44 @@ 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,20 +290,15 @@ 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"))); } @@ -317,15 +312,13 @@ 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"))); } @@ -345,22 +338,21 @@ 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())); } @@ -372,10 +364,9 @@ public void gitSCMSourceShouldResolveToolsForMaster() throws Exception { return; } TaskListener log = StreamTaskListener.fromStdout(); - HelloToolInstaller inst = - new HelloToolInstaller(r.jenkins.getSelfLabel().getName(), "echo Hello", "git"); - GitTool t = new GitTool( - "myGit", null, Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); + HelloToolInstaller inst = new HelloToolInstaller(r.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(); @@ -400,8 +391,7 @@ 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); @@ -427,12 +417,13 @@ 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(); @@ -509,39 +500,49 @@ 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 @@ -579,7 +580,8 @@ 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": @@ -690,6 +692,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 7a66c4c3a2..e3db3797b8 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java @@ -1,17 +1,5 @@ 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; @@ -25,8 +13,10 @@ 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; @@ -53,6 +43,18 @@ 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 @@ -68,8 +70,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 @@ -107,23 +109,28 @@ 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 @@ -133,31 +140,35 @@ 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)), @@ -167,23 +178,37 @@ 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), @@ -191,12 +216,23 @@ 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/*")); @@ -204,14 +240,18 @@ 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)), @@ -219,22 +259,33 @@ 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/*")); @@ -249,7 +300,9 @@ 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("")); @@ -261,10 +314,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)); } @@ -272,14 +325,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("")); } @@ -288,14 +341,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/*")); } @@ -305,28 +358,31 @@ 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 7dfdd07e8c..0f60c015fa 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java @@ -23,11 +23,6 @@ */ 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; @@ -70,10 +65,14 @@ 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 */ { @@ -81,7 +80,7 @@ public class GitSCMTelescopeTest /* extends AbstractGitRepository */ { /* REPO can be allocated once for the whole test suite so long as nothing changes it */ @ClassRule - public static final GitSampleRepoRule READ_ONLY_REPO = new GitSampleRepoRule(); + static public final GitSampleRepoRule READ_ONLY_REPO = new GitSampleRepoRule(); private final String remote; private GitSCMTelescope telescope; @@ -135,8 +134,11 @@ 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"); @@ -145,7 +147,11 @@ 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; } @@ -317,7 +323,8 @@ public void testGetRevisions_String_StandardCredentials() throws Exception { /* ********************* Test helper classes **************************** */ private static class ItemImpl implements Item { - public ItemImpl() {} + public ItemImpl() { + } @Override public ItemGroup getParent() { @@ -443,11 +450,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."); } @@ -459,8 +466,8 @@ public SCM build(SCMHead scmh, SCMRevision scmr) { private static class GitSCMTelescopeImpl extends GitSCMTelescope { - private final String allowedRemote; - private final SCMRevision revision; + final private String allowedRemote; + final private SCMRevision revision; private List revisionList = new ArrayList<>(); public GitSCMTelescopeImpl(String allowedRemote, SCMRevision revision) { @@ -501,11 +508,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) { @@ -516,27 +523,22 @@ 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 26dfabfb63..70ee731934 100644 --- a/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java +++ b/src/test/java/jenkins/plugins/git/GitSampleRepoRule.java @@ -24,10 +24,12 @@ package jenkins.plugins.git; +import org.htmlunit.WebResponse; +import org.htmlunit.util.NameValuePair; import hudson.Launcher; import hudson.model.TaskListener; -import hudson.plugins.git.ApiTokenPropertyConfiguration; import hudson.plugins.git.GitSCM; +import hudson.plugins.git.ApiTokenPropertyConfiguration; import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; @@ -37,8 +39,6 @@ import jenkins.scm.impl.mock.AbstractSampleDVCSRepoRule; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.RepositoryBuilder; -import org.htmlunit.WebResponse; -import org.htmlunit.util.NameValuePair; import org.jvnet.hudson.test.JenkinsRule; /** @@ -75,16 +75,13 @@ 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"); @@ -101,12 +98,9 @@ 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")) { @@ -117,11 +111,7 @@ 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() { @@ -136,11 +126,7 @@ 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); } @@ -148,47 +134,30 @@ 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 6d2e4b4b39..989b80f22e 100644 --- a/src/test/java/jenkins/plugins/git/GitStepTest.java +++ b/src/test/java/jenkins/plugins/git/GitStepTest.java @@ -24,10 +24,6 @@ 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; @@ -48,6 +44,8 @@ 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; @@ -57,6 +55,7 @@ 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 @@ -66,10 +65,8 @@ public class GitStepTest { @Rule public JenkinsRule r = new JenkinsRule(); - @Rule public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - @Rule public GitSampleRepoRule otherRepo = new GitSampleRepoRule(); @@ -81,7 +78,6 @@ public static void setGitDefaults() throws Exception { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); - @Rule public TestName testName = new TestName(); @@ -108,7 +104,8 @@ 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); @@ -122,12 +119,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()); @@ -147,13 +144,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", ""); @@ -188,17 +185,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()); @@ -218,13 +215,9 @@ 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()); @@ -255,14 +248,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()); @@ -286,17 +279,17 @@ 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 'config --local commit.gpgsign false'\n" - + " rungit 'config --local tag.gpgSign false'\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 'config --local commit.gpgsign false'\n" + + " rungit 'config --local tag.gpgSign false'\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 613983b092..abe38698ad 100644 --- a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java @@ -1,12 +1,5 @@ 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; @@ -18,14 +11,9 @@ 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; @@ -43,6 +31,20 @@ 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. @@ -56,8 +58,7 @@ 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; @@ -65,8 +66,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; @@ -83,7 +84,6 @@ 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()); r.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")); } @@ -138,16 +138,14 @@ public void testResolveGitToolWithJenkins() throws IOException, InterruptedExcep String credentialsId = null; TestToolInstaller inst = new TestToolInstaller(r.jenkins.getSelfLabel().getName(), "echo Hello", "updated/git"); - GitTool t = new GitTool( - "myGit", - "default/git", - Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); + 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()); r.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")); } @@ -176,37 +174,25 @@ public void testResolutionGitToolOnAgent() throws Exception { agent.setLabelString("agent-windows"); TestToolInstaller inst = new TestToolInstaller(r.jenkins.getSelfLabel().getName(), "echo Hello", "myGit/git"); - GitTool toolOnMaster = new GitTool( - "myGit", - "default/git", - Collections.singletonList(new InstallSourceProperty(Collections.singletonList(inst)))); + 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()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(toolOnMaster, toolOnAgent, JTool); - agent.getNodeProperties() - .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), - toolOnMaster.getName(), - toolOnMaster.getHome()))); + agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnMaster.getName(), toolOnMaster.getHome()))); - agent.getNodeProperties() - .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), - toolOnAgent.getName(), - toolOnAgent.getHome()))); + agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnAgent.getName(), toolOnAgent.getHome()))); - agent.getNodeProperties() - .add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( - r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), JTool.getName(), null))); + agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation( + r.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")); } @@ -228,11 +214,10 @@ public void testSizeEstimationWithNoGitCache() throws Exception { List list = r.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 @@ -280,8 +265,7 @@ public void testSizeEstimationWithGitCache() throws Exception { List list = r.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 */ @@ -291,17 +275,13 @@ 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 */ @@ -311,8 +291,7 @@ 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())); @@ -324,19 +303,18 @@ 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)); } @@ -344,8 +322,7 @@ 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)); } @@ -358,31 +335,28 @@ 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")); } /* @@ -403,8 +377,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")); } @@ -424,11 +398,11 @@ public void testSizeEstimationWithAPIForJGit() throws Exception { GitTool tool = new JGitTool(Collections.emptyList()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); + buildAProject(sampleRepo, false); List list = r.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")); } @@ -449,8 +423,7 @@ 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")); } @@ -472,8 +445,7 @@ 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")); } @@ -493,8 +465,7 @@ 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")); } @@ -514,12 +485,12 @@ public void testGitToolChooserWithCustomGitTool() throws Exception { GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.emptyList()); r.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 @@ -534,8 +505,7 @@ public void testGitToolChooserWithBothGitAndJGit() throws Exception { GitTool jgitTool = new JGitTool(Collections.emptyList()); r.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")); } @@ -555,8 +525,7 @@ public void testGitToolChooserWithAllTools() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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")); } @@ -576,8 +545,7 @@ public void testGitToolChooserWithJGitApache() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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")); } @@ -595,8 +563,7 @@ public void testGitToolChooserWithJGitApacheAndGit() throws Exception { GitTool jGitApacheTool = new JGitApacheTool(Collections.emptyList()); r.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")); } @@ -618,8 +585,7 @@ 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")); } @@ -642,11 +608,8 @@ 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 @@ -668,8 +631,7 @@ 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")); } @@ -694,8 +656,7 @@ 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")); } @@ -736,8 +697,7 @@ 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")); } @@ -811,14 +771,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 = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( @@ -829,8 +789,7 @@ 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 = r.buildAndAssertSuccess(p); if (!noCredentials) { r.waitForMessage("using credential github", b); @@ -841,8 +800,11 @@ private void buildAProject(GitSampleRepoRule sampleRepo, boolean noCredentials) /* 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 = r.jenkins.createProject(WorkflowJob.class, "intentionally-failing-job-without-remote-config"); - p.setDefinition( - new CpsFlowDefinition("node {\n" + " checkout(\n" + " [$class: 'GitSCM']\n" + " )\n" + "}", true)); + p.setDefinition(new CpsFlowDefinition("node {\n" + + " checkout(\n" + + " [$class: 'GitSCM']\n" + + " )\n" + + "}", true)); WorkflowRun b = r.buildAndAssertStatus(hudson.model.Result.FAILURE, p); r.waitForMessage("Couldn't find any revision to build", b); } @@ -853,6 +815,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 b73e1ed47a..18891a961c 100644 --- a/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java @@ -1,15 +1,5 @@ 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; @@ -23,11 +13,20 @@ 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()); @@ -35,24 +34,21 @@ 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 48b4ad0cc1..46654be9d5 100644 --- a/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java +++ b/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java @@ -1,10 +1,5 @@ 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; @@ -12,6 +7,7 @@ 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; @@ -19,14 +15,6 @@ 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; @@ -51,6 +39,20 @@ 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 { @@ -74,7 +76,6 @@ public static Collection data() { @ClassRule public static Stopwatch stopwatch = new Stopwatch(); - @Rule public TestName testName = new TestName(); @@ -95,8 +96,7 @@ 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,7 +106,11 @@ 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&", @@ -118,26 +122,17 @@ private boolean isTimeAvailable() { "%interior-single-quote%_786'@**", }; 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 three 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)] - }, - { - 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)]}, + {userNames[random.nextInt(userNames.length)], passwords[random.nextInt(passwords.length)], gitTools[random.nextInt(gitTools.length)]}, }; public GitUsernamePasswordBindingTest(String username, String password, GitTool gitToolInstance) { @@ -148,28 +143,20 @@ 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); } @@ -187,9 +174,8 @@ 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); @@ -198,14 +184,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 { @@ -214,16 +200,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")); @@ -246,8 +232,7 @@ 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" @@ -259,7 +244,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 { @@ -267,13 +252,9 @@ 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)); @@ -288,7 +269,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()))); } @@ -297,9 +278,8 @@ 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); @@ -309,16 +289,10 @@ 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); @@ -329,23 +303,18 @@ 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 Exception { 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 3475c046ff..3b04744c94 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java @@ -1,16 +1,5 @@ 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; @@ -43,7 +32,6 @@ 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; @@ -51,20 +39,32 @@ 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,11 +74,12 @@ 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()); @@ -86,107 +87,142 @@ 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 fd9949695f..d2ba122324 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java @@ -1,15 +1,5 @@ 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; @@ -43,117 +33,152 @@ 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 d845e9783f..a060442df9 100644 --- a/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java +++ b/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java @@ -1,7 +1,5 @@ package jenkins.plugins.git; -import static org.junit.Assert.*; - import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; @@ -14,6 +12,8 @@ import org.eclipse.jgit.lib.Constants; import org.junit.Test; +import static org.junit.Assert.*; + public class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { private FreeStyleProject project; @@ -32,8 +32,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 +43,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,35 +61,26 @@ 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 4a0313107b..69f7ee8e48 100644 --- a/src/test/java/jenkins/plugins/git/ModernScmTest.java +++ b/src/test/java/jenkins/plugins/git/ModernScmTest.java @@ -24,10 +24,6 @@ */ 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; @@ -35,6 +31,10 @@ 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,8 +43,7 @@ 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 860776151a..a293f783bf 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 java.util.Random; import org.junit.runner.manipulation.Ordering; +import java.util.Random; + 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 da9b6a5e4d..611e4ba8ce 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 static org.junit.Assert.*; - import org.junit.Test; +import static org.junit.Assert.*; + public class DiscoverOtherRefsTraitTest { @Test @@ -46,4 +46,5 @@ 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 0d77eae914..a052738ed1 100644 --- a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java @@ -1,8 +1,5 @@ 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; @@ -13,6 +10,9 @@ 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 r = new JenkinsRule(); @@ -30,8 +30,7 @@ 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)); } @@ -40,8 +39,7 @@ 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)); } @@ -50,8 +48,7 @@ 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 673d7a9759..acfeae8833 100644 --- a/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java @@ -1,13 +1,11 @@ package jenkins.plugins.git.traits; -import java.util.Collections; -import java.util.Random; -import jenkins.plugins.git.GitSCMSource; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.GitSCMSource; 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; @@ -15,10 +13,12 @@ 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,29 +35,24 @@ 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); @@ -70,11 +65,8 @@ 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" @@ -85,8 +77,7 @@ 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); @@ -95,59 +86,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 = { - // Assembla now requires login to access the space - // " 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 + // Assembla now requires login to access the space + // " 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 23a66db835..1b6f0abc2e 100644 --- a/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java @@ -1,8 +1,5 @@ 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; @@ -10,6 +7,9 @@ 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,7 +21,8 @@ */ 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 c4f2290284..2283c836a2 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/TestCliGitAPIImpl.java @@ -36,4 +36,5 @@ 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 edf5b59eff..3dddfcc599 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java @@ -1,10 +1,11 @@ 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() @@ -14,8 +15,7 @@ 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 e4c0a18653..11caef6f5a 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java @@ -1,14 +1,11 @@ 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; @@ -21,14 +18,15 @@ import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.JenkinsRule; -public abstract class AbstractGitTagMessageExtensionTest< - J extends Job & ParameterizedJobMixIn.ParameterizedJob, R extends Run & Queue.Executable> { +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +public abstract class AbstractGitTagMessageExtensionTest & ParameterizedJobMixIn.ParameterizedJob, R extends Run & Queue.Executable> { - @Rule - public final JenkinsRule r = new JenkinsRule(); + @Rule public final JenkinsRule r = new JenkinsRule(); - @Rule - public final TemporaryFolder repoDir = new TemporaryFolder(); + @Rule public final TemporaryFolder repoDir = new TemporaryFolder(); private GitClient repo; @@ -38,8 +36,7 @@ public abstract class AbstractGitTagMessageExtensionTest< * @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 { @@ -53,9 +50,7 @@ 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(r.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()) - .in(repoDir.getRoot()) - .getClient(); + repo = Git.with(r.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()).in(repoDir.getRoot()).getClient(); repo.init(); } @@ -135,7 +130,8 @@ 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 @@ -158,8 +154,7 @@ 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."); @@ -185,4 +180,5 @@ 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 3f9f5da2a2..418640988b 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java @@ -1,8 +1,5 @@ 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; @@ -13,8 +10,12 @@ 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 { /** @@ -23,16 +24,14 @@ 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 { + 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 = r.createFreeStyleProject(); @@ -56,4 +55,5 @@ private static Builder createEnvEchoBuilder(String key, String envVarName) { } return new Shell(String.format("echo \"%s='${%s}'\"", key, envVarName)); } + } From 4499e958a1fd96e2399f187c54eccb816b658c6e Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Wed, 1 May 2024 11:38:41 -0600 Subject: [PATCH 23/30] Reduce doc diffs --- README.adoc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.adoc b/README.adoc index 18c12088b9..a84629610b 100644 --- a/README.adoc +++ b/README.adoc @@ -1233,7 +1233,6 @@ The Jenkins git plugin provides an option to trigger pipeline build process on t extensions: [firstBuildChangelog()], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]) - ---- [#merge-extensions] === Merge Extensions @@ -1439,7 +1438,6 @@ For example, they might choose to place the cache directories in `/var/cache/jen The default git cache directory location can be overridden by setting the property `jenkins.plugins.git.AbstractGitSCMSource.cacheRootDir=/var/cache/jenkins`. - [#git-publisher] == Git Publisher @@ -1606,7 +1604,7 @@ for (job in allItems) { def counter = 0; for (build in job.getBuilds()) { // It is possible for a build to have multiple BuildData actions - // since we can use the Mulitple SCM plugin. + // since we can use the Multiple SCM plugin. def gitActions = build.getActions(hudson.plugins.git.util.BuildData.class) if (gitActions != null) { for (action in gitActions) { From 8df79db1ed193a4a3ef18d1753b8a07774e52d04 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Wed, 1 May 2024 11:40:52 -0600 Subject: [PATCH 24/30] Use Unix file format for help --- .../git/extensions/impl/FirstBuildChangelog/help.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html index 0f4355d596..a0174b2e0e 100644 --- a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html +++ b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html @@ -1,3 +1,3 @@ -
- First builds will populate the changelog with the latest commit, if any, to allow for pipelines to consistently check and test for file changes. -
+
+ First builds will populate the changelog with the latest commit, if any, to allow for pipelines to consistently check and test for file changes. +
From 667a4faa2e8b7b8608849cd7d1573c0437070044 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Wed, 1 May 2024 11:42:16 -0600 Subject: [PATCH 25/30] Jenkins Pipeline symbols start with a lower case letter --- .../jenkins/plugins/git/traits/FirstBuildChangelogTrait.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java index 1fd20bb380..2547586181 100644 --- a/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/FirstBuildChangelogTrait.java @@ -36,7 +36,7 @@ public FirstBuildChangelogTrait(@CheckForNull FirstBuildChangelog extension) { * Our {@link hudson.model.Descriptor} */ @Extension - @Symbol("FirstBuildChangelog") + @Symbol("firstBuildChangelog") public static class DescriptorImpl extends GitSCMExtensionTraitDescriptor { /** * {@inheritDoc} From 11955ee21934417677db99fa3685f41a32a58852 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Wed, 1 May 2024 11:43:56 -0600 Subject: [PATCH 26/30] Remove blank line from doc example --- README.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.adoc b/README.adoc index a84629610b..52c9c2852f 100644 --- a/README.adoc +++ b/README.adoc @@ -1232,8 +1232,8 @@ The Jenkins git plugin provides an option to trigger pipeline build process on t checkout scmGit(branches: [[name: 'master']], extensions: [firstBuildChangelog()], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]) - ---- + [#merge-extensions] === Merge Extensions From 34be3838548803f7fdaa25885c55b546d9383b63 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Wed, 1 May 2024 12:03:58 -0600 Subject: [PATCH 27/30] First build changelog reports most recent commit as changelog The new extension reports the most recent commit as the changelog. It does not report the changes from a base branch, because there is no reliable method to identify the base branch from command line git. Also adjusts capitalization to be consistent with other parts of the documentation. --- README.adoc | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.adoc b/README.adoc index 52c9c2852f..c8ed9bc1d6 100644 --- a/README.adoc +++ b/README.adoc @@ -1220,12 +1220,14 @@ Inverse:: This is useful, for example, when you have jobs building your master and various release branches and you want a second job which builds all new feature branches. For example, branches which do not match these patterns without redundantly building master and the release branches again each time they change. -[#firstBuildBehavior] -==== First Build Changelog behavior +[#first-build-changelog] +==== First build changelog -image:/images/git-extension-for-first-build.png[First Build Changelog behavior] +image:/images/git-extension-for-first-build.png[First build changelog] -The Jenkins git plugin provides an option to trigger pipeline build process on the first commit on a branch. By default, no changelog is generated causing any pipeline process to not be triggered but with this option selected changes are found between the new branch and its parent commit. +The Jenkins git plugin provides an option to trigger a Pipeline build on the first commit on a branch. +By default, no changelog is generated for the first commit on a branch. +When the first build changelog option is enabled, the most recent commit on the branch will be used as the changelog of the first build of the branch. [source,groovy] ---- From 13816f4af2c4c999e85d543343ac8deed5659721 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Sat, 4 May 2024 09:21:03 -0600 Subject: [PATCH 28/30] Format new example same as prior examples. --- README.adoc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.adoc b/README.adoc index c8ed9bc1d6..9dacb7325a 100644 --- a/README.adoc +++ b/README.adoc @@ -1231,9 +1231,10 @@ When the first build changelog option is enabled, the most recent commit on the [source,groovy] ---- - checkout scmGit(branches: [[name: 'master']], - extensions: [firstBuildChangelog()], - userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]) +checkout scmGit( + branches: [[name: 'master']], + extensions: [ firstBuildChangelog() ], + userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]) ---- [#merge-extensions] From 81606a6eda18aa138b6b6d4de5138237181139c4 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Sat, 4 May 2024 09:29:03 -0600 Subject: [PATCH 29/30] Clarify first build option help and docs --- README.adoc | 4 ++-- .../plugins/git/extensions/impl/FirstBuildChangelog/help.html | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.adoc b/README.adoc index 9dacb7325a..b35fec2fe9 100644 --- a/README.adoc +++ b/README.adoc @@ -1226,8 +1226,8 @@ Inverse:: image:/images/git-extension-for-first-build.png[First build changelog] The Jenkins git plugin provides an option to trigger a Pipeline build on the first commit on a branch. -By default, no changelog is generated for the first commit on a branch. -When the first build changelog option is enabled, the most recent commit on the branch will be used as the changelog of the first build of the branch. +By default, no changelog is generated for the first build because the first build has no predecessor build for comparison. +When the first build changelog option is enabled, the most recent commit will be used as the changelog of the first build. [source,groovy] ---- diff --git a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html index a0174b2e0e..d8a8150dd2 100644 --- a/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html +++ b/src/main/resources/hudson/plugins/git/extensions/impl/FirstBuildChangelog/help.html @@ -1,3 +1,5 @@
- First builds will populate the changelog with the latest commit, if any, to allow for pipelines to consistently check and test for file changes. + First builds will populate the changelog with the latest commit, if any, to allow Pipelines to check and test for file changes. + By default, no changelog is generated for the first build because the first build has no predecessor build for comparison. + When the first build changelog option is enabled, the most recent commit on the branch will be used as the changelog of the first build.
From 61bb7582896bae3d9c4863de6b76fa9a18f9a314 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Sun, 28 Jul 2024 18:15:06 -0600 Subject: [PATCH 30/30] Remove comment as suggested by reviewer --- src/main/java/hudson/plugins/git/GitSCM.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/hudson/plugins/git/GitSCM.java b/src/main/java/hudson/plugins/git/GitSCM.java index 3c9413c265..e35b2ac452 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -1495,15 +1495,11 @@ private void computeChangeLog(GitClient git, Revision revToBuild, TaskListener l if (!exclusion) { FirstBuildChangelog firstBuildChangelog = getExtensions().get(FirstBuildChangelog.class); - if (firstBuildChangelog!=null&&firstBuildChangelog.isMakeChangelog()) { + if (firstBuildChangelog != null && firstBuildChangelog.isMakeChangelog()) { changelog.to(out).max(1).execute(); executed = true; listener.getLogger().println("First time build. Latest changes added to changelog."); } else { - // this is the first time we are building this branch, so there's no base line - // to compare against. - // if we force the changelog, it'll contain all the changes in the repo, which - // is not what we want. listener.getLogger().println("First time build. Skipping changelog."); } } else {