From 3071963405d978387d9ae8184d419c03704c6f95 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Sun, 20 Oct 2024 16:26:15 -0600 Subject: [PATCH 1/3] Use Java 17 language features instanceof pattern matching Formatted strings --- pom.xml | 17 +++++++ .../java/hudson/plugins/git/BranchSpec.java | 2 + .../plugins/git/GitBranchSpecifierColumn.java | 3 +- .../java/hudson/plugins/git/GitPublisher.java | 3 ++ .../git/GitRevisionBuildParameters.java | 4 +- src/main/java/hudson/plugins/git/GitSCM.java | 15 +++--- .../git/GitSCMBackwardCompatibility.java | 2 + .../java/hudson/plugins/git/GitStatus.java | 6 +-- .../plugins/git/RevisionParameterAction.java | 2 + .../hudson/plugins/git/SubmoduleConfig.java | 3 +- .../hudson/plugins/git/UserMergeOptions.java | 4 +- .../hudson/plugins/git/UserRemoteConfig.java | 12 ++--- .../plugins/git/browser/AssemblaWeb.java | 2 + .../plugins/git/browser/BitbucketServer.java | 2 + .../plugins/git/browser/BitbucketWeb.java | 2 + .../java/hudson/plugins/git/browser/CGit.java | 2 + .../browser/FisheyeGitRepositoryBrowser.java | 6 ++- .../git/browser/GitBlitRepositoryBrowser.java | 8 ++-- .../hudson/plugins/git/browser/GitLab.java | 2 + .../hudson/plugins/git/browser/GitList.java | 2 + .../git/browser/GitRepositoryBrowser.java | 2 + .../hudson/plugins/git/browser/GitWeb.java | 2 + .../hudson/plugins/git/browser/GithubWeb.java | 2 + .../hudson/plugins/git/browser/Gitiles.java | 2 + .../plugins/git/browser/GitoriousWeb.java | 2 + .../hudson/plugins/git/browser/GogsGit.java | 2 + .../hudson/plugins/git/browser/KilnGit.java | 2 + .../plugins/git/browser/Phabricator.java | 8 ++-- .../plugins/git/browser/RedmineWeb.java | 2 + .../hudson/plugins/git/browser/RhodeCode.java | 2 + .../hudson/plugins/git/browser/Stash.java | 2 + .../browser/TFS2013GitRepositoryBrowser.java | 4 +- .../plugins/git/browser/ViewGitWeb.java | 2 + .../git/extensions/GitSCMExtension.java | 28 +++++------ .../extensions/impl/SparseCheckoutPath.java | 2 + .../plugins/git/opt/PreBuildMergeOptions.java | 2 + .../git/util/AncestryBuildChooser.java | 4 +- .../java/hudson/plugins/git/util/Build.java | 2 + .../hudson/plugins/git/util/BuildChooser.java | 2 + .../hudson/plugins/git/util/BuildData.java | 4 ++ .../hudson/plugins/git/util/GitUtils.java | 5 +- .../plugins/git/util/InverseBuildChooser.java | 2 + .../git/util/RevCommitRepositoryCallback.java | 3 ++ .../plugins/git/AbstractGitSCMSource.java | 22 ++++----- .../jenkins/plugins/git/DisableHooks.java | 3 ++ .../plugins/git/GitRemoteHeadRefAction.java | 3 ++ .../jenkins/plugins/git/GitSCMBuilder.java | 7 ++- .../jenkins/plugins/git/GitSCMFileSystem.java | 16 +++---- .../jenkins/plugins/git/GitSCMSource.java | 29 +++++------- .../jenkins/plugins/git/GitSCMTelescope.java | 29 +++++------- .../java/jenkins/plugins/git/UnsetHooks.java | 4 +- .../GitSCMExtensionTraitDescriptor.java | 3 +- .../git/traits/PruneStaleBranchTrait.java | 3 +- .../plugins/git/AbstractGitProject.java | 4 +- .../plugins/git/AbstractGitTestCase.java | 4 +- .../plugins/git/FIPSModeUrlCheckTest.java | 26 ++++++----- .../plugins/git/GitChangeSetTruncateTest.java | 2 +- .../java/hudson/plugins/git/GitSCMTest.java | 46 ++++++++++--------- .../hudson/plugins/git/GitStatusTest.java | 4 +- .../java/hudson/plugins/git/GitStepTest.java | 8 ++-- .../plugins/git/browser/GithubWebTest.java | 4 +- .../impl/BuildSingleRevisionOnlyTest.java | 4 +- .../impl/CloneOptionHonorRefSpecTest.java | 4 +- .../plugins/git/AbstractGitSCMSourceTest.java | 11 ++--- .../git/BrowsersJCasCCompatibilityTest.java | 2 +- .../jenkins/plugins/git/GitSCMSourceTest.java | 4 +- .../plugins/git/GitToolChooserTest.java | 12 +++-- .../git/traits/GitSCMExtensionTraitTest.java | 4 +- .../GitTagMessageExtensionTest.java | 8 ++-- 69 files changed, 272 insertions(+), 181 deletions(-) diff --git a/pom.xml b/pom.xml index cb7a3c0d6d..b63cee0f2b 100644 --- a/pom.xml +++ b/pom.xml @@ -297,6 +297,23 @@ true + + org.openrewrite.maven + rewrite-maven-plugin + 5.42.0 + + + org.openrewrite.java.migrate.UpgradeToJava17 + + + + + org.openrewrite.recipe + rewrite-migrate-java + 2.26.1 + + + diff --git a/src/main/java/hudson/plugins/git/BranchSpec.java b/src/main/java/hudson/plugins/git/BranchSpec.java index e083a75bc0..2c6ce09367 100644 --- a/src/main/java/hudson/plugins/git/BranchSpec.java +++ b/src/main/java/hudson/plugins/git/BranchSpec.java @@ -6,6 +6,7 @@ import hudson.model.Descriptor; import org.kohsuke.stapler.DataBoundConstructor; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -32,6 +33,7 @@ */ @ExportedBean public class BranchSpec extends AbstractDescribableImpl implements Serializable { + @Serial private static final long serialVersionUID = -6177158367915899356L; private String name; diff --git a/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java b/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java index dd8c63119b..3c439af793 100644 --- a/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java +++ b/src/main/java/hudson/plugins/git/GitBranchSpecifierColumn.java @@ -26,8 +26,7 @@ public List getBranchSpecifier( final Item item ) { SCMTriggerItem s = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item); if(s != null) { for(SCM scm : s.getSCMs()) { - if (scm instanceof GitSCM) { - GitSCM gitScm = (GitSCM)scm; + if (scm instanceof GitSCM gitScm) { for(BranchSpec spec : gitScm.getBranches()) { branchSpec.add(spec.getName()); } diff --git a/src/main/java/hudson/plugins/git/GitPublisher.java b/src/main/java/hudson/plugins/git/GitPublisher.java index 2d2cbdef88..5a1890b858 100644 --- a/src/main/java/hudson/plugins/git/GitPublisher.java +++ b/src/main/java/hudson/plugins/git/GitPublisher.java @@ -30,11 +30,13 @@ import jakarta.servlet.ServletException; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class GitPublisher extends Recorder implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** @@ -482,6 +484,7 @@ private FormValidation checkFieldNotEmpty(String value, String field) { } public static abstract class PushConfig extends AbstractDescribableImpl implements Serializable { + @Serial private static final long serialVersionUID = 1L; private String targetRepoName; diff --git a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java index 29bab615a3..79a400bab0 100644 --- a/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java +++ b/src/main/java/hudson/plugins/git/GitRevisionBuildParameters.java @@ -55,9 +55,9 @@ public GitRevisionBuildParameters() { 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) { + if (build instanceof hudson.plugins.promoted_builds.Promotion 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 = promotion.getTargetBuild(); if (targetBuild != null) { data = targetBuild.getAction(BuildData.class); } diff --git a/src/main/java/hudson/plugins/git/GitSCM.java b/src/main/java/hudson/plugins/git/GitSCM.java index e650d9a8e5..b9b3096b50 100644 --- a/src/main/java/hudson/plugins/git/GitSCM.java +++ b/src/main/java/hudson/plugins/git/GitSCM.java @@ -75,12 +75,13 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; +import java.io.Serial; import java.io.Serializable; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.InvalidPathException; -import java.nio.file.Paths; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.AbstractList; import java.util.ArrayList; @@ -710,13 +711,13 @@ 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 ap ? GitUtils.getPollEnvironment(ap, 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 ap ? GitUtils.getPollEnvironment(ap, workspace, launcher, listener, false) : new EnvVars(); GitClient git = createClient(listener, environment, lastBuild, Jenkins.get(), null); @@ -784,7 +785,7 @@ 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 ap ? GitUtils.getPollEnvironment(ap, workspace, launcher, listener) : project.getEnvironment(node, listener); FilePath workingDirectory = workingDirectory(project,workspace,environment,listener); @@ -1175,8 +1176,7 @@ public EnvVars getEnvironment() { log.println("Multiple candidate revisions"); if (checkForMultipleRevisions) { Job job = build.getParent(); - if (job instanceof AbstractProject) { - AbstractProject project = (AbstractProject) job; + if (job instanceof AbstractProject project) { 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 " @@ -1416,7 +1416,7 @@ private static boolean isRemoteUrlValid(String remoteUrl) { } try { // Check for local remotes with no protocol like /path/to/repo.git/ - return !Files.exists(Paths.get(remoteUrl)); + return !Files.exists(Path.of(remoteUrl)); } catch (InvalidPathException e) { return true; } @@ -1937,6 +1937,7 @@ public void populateEnvironmentVariables(Map env) { // } } + @Serial private static final long serialVersionUID = 1L; @Whitelisted diff --git a/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java b/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java index 89ba40779c..0c394e8d9b 100644 --- a/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java +++ b/src/main/java/hudson/plugins/git/GitSCMBackwardCompatibility.java @@ -13,6 +13,7 @@ import hudson.util.DescribableList; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.Set; @@ -486,5 +487,6 @@ public String getLocalBranch() { } + @Serial 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 6d3dba3c39..470831fa6b 100644 --- a/src/main/java/hudson/plugins/git/GitStatus.java +++ b/src/main/java/hudson/plugins/git/GitStatus.java @@ -430,9 +430,9 @@ public List onNotifyCommit(String origin, URIish uri, Strin } if (!branchFound) continue; urlFound = true; - if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob && ((ParameterizedJobMixIn.ParameterizedJob) project).isDisabled())) { + if (!(project instanceof ParameterizedJobMixIn.ParameterizedJob job && job.isDisabled())) { //JENKINS-30178 Add default parameters defined in the job - if (project instanceof Job) { + if (project instanceof Job job) { Set buildParametersNames = new HashSet<>(); if (allowNotifyCommitParameters || !safeParameters.isEmpty()) { for (ParameterValue parameterValue: allBuildParameters) { @@ -442,7 +442,7 @@ public List onNotifyCommit(String origin, URIish uri, Strin } } - List jobParametersValues = getDefaultParametersValues((Job) project); + List jobParametersValues = getDefaultParametersValues(job); for (ParameterValue defaultParameterValue : jobParametersValues) { if (!buildParametersNames.contains(defaultParameterValue.getName())) { allBuildParameters.add(defaultParameterValue); diff --git a/src/main/java/hudson/plugins/git/RevisionParameterAction.java b/src/main/java/hudson/plugins/git/RevisionParameterAction.java index f3b6b64791..5e7dcc8297 100644 --- a/src/main/java/hudson/plugins/git/RevisionParameterAction.java +++ b/src/main/java/hudson/plugins/git/RevisionParameterAction.java @@ -35,6 +35,7 @@ import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.GitClient; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -200,6 +201,7 @@ public void foldIntoExisting(Queue.Item item, Queue.Task owner, List oth } } + @Serial private static final long serialVersionUID = 2L; private static final Logger LOGGER = Logger.getLogger(RevisionParameterAction.class.getName()); } diff --git a/src/main/java/hudson/plugins/git/SubmoduleConfig.java b/src/main/java/hudson/plugins/git/SubmoduleConfig.java index ae830cda1a..0550ce9cfb 100644 --- a/src/main/java/hudson/plugins/git/SubmoduleConfig.java +++ b/src/main/java/hudson/plugins/git/SubmoduleConfig.java @@ -3,7 +3,7 @@ import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted; import org.kohsuke.stapler.DataBoundConstructor; - +import java.io.Serial; import java.util.Collection; import java.util.Collections; @@ -16,6 +16,7 @@ */ @Deprecated public class SubmoduleConfig implements java.io.Serializable { + @Serial private static final long serialVersionUID = 1L; private static final String[] EMPTY_ARRAY = new String[0]; String submoduleName = null; diff --git a/src/main/java/hudson/plugins/git/UserMergeOptions.java b/src/main/java/hudson/plugins/git/UserMergeOptions.java index e4ff9915a2..0c97515002 100644 --- a/src/main/java/hudson/plugins/git/UserMergeOptions.java +++ b/src/main/java/hudson/plugins/git/UserMergeOptions.java @@ -168,8 +168,8 @@ public String getDisplayName() { public Map customInstantiate(Map arguments) { Map r = new HashMap<>(arguments); Object mergeStrategy = r.get("mergeStrategy"); - if (mergeStrategy instanceof String) { - r.put("mergeStrategy", ((String) mergeStrategy).toUpperCase(Locale.ROOT)); + if (mergeStrategy instanceof String string) { + r.put("mergeStrategy", string.toUpperCase(Locale.ROOT)); } return r; } diff --git a/src/main/java/hudson/plugins/git/UserRemoteConfig.java b/src/main/java/hudson/plugins/git/UserRemoteConfig.java index 3020ca0451..3aaa7bbfe8 100644 --- a/src/main/java/hudson/plugins/git/UserRemoteConfig.java +++ b/src/main/java/hudson/plugins/git/UserRemoteConfig.java @@ -119,8 +119,8 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project, return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( - project instanceof Queue.Task - ? Tasks.getAuthenticationOf((Queue.Task) project) + project instanceof Queue.Task t + ? Tasks.getAuthenticationOf(t) : ACL.SYSTEM, project, StandardUsernameCredentials.class, @@ -155,8 +155,8 @@ 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) + .listCredentialsInItem(StandardUsernameCredentials.class, project, project instanceof Queue.Task t + ? Tasks.getAuthenticationOf2(t) : ACL.SYSTEM2, GitURIRequirementsBuilder.fromUri(url).build(), GitClient.CREDENTIALS_MATCHER)) { @@ -199,8 +199,8 @@ public FormValidation doCheckUrl(@AncestorInPath Item item, // get git executable on controller EnvVars environment; Jenkins jenkins = Jenkins.get(); - if (item instanceof Job) { - environment = ((Job) item).getEnvironment(jenkins, TaskListener.NULL); + if (item instanceof Job job) { + environment = job.getEnvironment(jenkins, TaskListener.NULL); } else { Computer computer = jenkins.toComputer(); environment = computer == null ? new EnvVars() : computer.buildEnvironment(TaskListener.NULL); diff --git a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java index e170f97d95..0e32208305 100644 --- a/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java +++ b/src/main/java/hudson/plugins/git/browser/AssemblaWeb.java @@ -23,6 +23,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.servlet.ServletException; import java.io.IOException; +import java.io.Serial; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -32,6 +33,7 @@ */ public class AssemblaWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java index f88620f960..5da4ebf444 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketServer.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketServer.java @@ -13,6 +13,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -20,6 +21,7 @@ */ public class BitbucketServer extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java index b633b33f3f..da57a37c49 100644 --- a/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java +++ b/src/main/java/hudson/plugins/git/browser/BitbucketWeb.java @@ -13,6 +13,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -20,6 +21,7 @@ */ public class BitbucketWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/CGit.java b/src/main/java/hudson/plugins/git/browser/CGit.java index 4120f60f1b..9ffedb1459 100644 --- a/src/main/java/hudson/plugins/git/browser/CGit.java +++ b/src/main/java/hudson/plugins/git/browser/CGit.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class CGit extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java index de0d3fecd4..bd69fc485f 100644 --- a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java @@ -20,12 +20,14 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.servlet.ServletException; import java.io.IOException; +import java.io.Serial; import java.net.URL; import java.util.regex.Pattern; public class FisheyeGitRepositoryBrowser extends GitRepositoryBrowser { - private static final long serialVersionUID = 2881872624557203410L; + @Serial + private static final long serialVersionUID = 2881872624557203410L; @DataBoundConstructor public FisheyeGitRepositoryBrowser(String repoUrl) { @@ -38,7 +40,7 @@ public URL getDiffLink(Path path) throws IOException { 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)); + return new URL(getUrl(), getPath(path) + "?r1=%s&r2=%s".formatted(r1, r2)); } @Override diff --git a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java index f759411f64..6c2e37345f 100644 --- a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java @@ -23,6 +23,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.servlet.ServletException; import java.io.IOException; +import java.io.Serial; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; @@ -30,6 +31,7 @@ public class GitBlitRepositoryBrowser extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; private final String projectName; @@ -44,7 +46,7 @@ public GitBlitRepositoryBrowser(String repoUrl, String projectName) { 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(), + (url.getPath() + "blobdiff?r=%s&h=%s&hb=%s").formatted(encodeString(projectName), path.getChangeSet().getId(), path.getChangeSet().getParentCommit())); } @@ -55,14 +57,14 @@ public URL getFileLink(Path path) throws IOException { } URL url = getUrl(); return new URL(url, - String.format(url.getPath() + "blob?r=%s&h=%s&f=%s", encodeString(projectName), path.getChangeSet().getId(), + (url.getPath() + "blob?r=%s&h=%s&f=%s").formatted(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, (url.getPath() + "commit?r=%s&h=%s").formatted(encodeString(projectName), changeSet.getId())); } public String getProjectName() { diff --git a/src/main/java/hudson/plugins/git/browser/GitLab.java b/src/main/java/hudson/plugins/git/browser/GitLab.java index eb26e0cee6..a452529791 100644 --- a/src/main/java/hudson/plugins/git/browser/GitLab.java +++ b/src/main/java/hudson/plugins/git/browser/GitLab.java @@ -15,6 +15,7 @@ import org.kohsuke.stapler.StaplerRequest2; import java.io.IOException; +import java.io.Serial; import java.net.URL; import edu.umd.cs.findbugs.annotations.NonNull; @@ -28,6 +29,7 @@ */ public class GitLab extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; private Double version; diff --git a/src/main/java/hudson/plugins/git/browser/GitList.java b/src/main/java/hudson/plugins/git/browser/GitList.java index 6bf3cfd32a..8158d793c5 100644 --- a/src/main/java/hudson/plugins/git/browser/GitList.java +++ b/src/main/java/hudson/plugins/git/browser/GitList.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class GitList extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java index 52f441c3f1..91d5c45bd3 100644 --- a/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitRepositoryBrowser.java @@ -12,6 +12,7 @@ import org.kohsuke.stapler.StaplerRequest2; import java.io.IOException; +import java.io.Serial; import java.net.IDN; import java.net.InetAddress; import java.net.MalformedURLException; @@ -225,5 +226,6 @@ public int hashCode() { } } + @Serial private static final long serialVersionUID = 1L; } diff --git a/src/main/java/hudson/plugins/git/browser/GitWeb.java b/src/main/java/hudson/plugins/git/browser/GitWeb.java index a0862ec2fc..8fc2f509a4 100644 --- a/src/main/java/hudson/plugins/git/browser/GitWeb.java +++ b/src/main/java/hudson/plugins/git/browser/GitWeb.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class GitWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/GithubWeb.java b/src/main/java/hudson/plugins/git/browser/GithubWeb.java index 6d525d3e75..84aab0693b 100644 --- a/src/main/java/hudson/plugins/git/browser/GithubWeb.java +++ b/src/main/java/hudson/plugins/git/browser/GithubWeb.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class GithubWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/Gitiles.java b/src/main/java/hudson/plugins/git/browser/Gitiles.java index f77251e204..44df39ecf9 100644 --- a/src/main/java/hudson/plugins/git/browser/Gitiles.java +++ b/src/main/java/hudson/plugins/git/browser/Gitiles.java @@ -12,6 +12,7 @@ import hudson.util.FormValidation.URLCheck; import java.io.IOException; +import java.io.Serial; import java.net.URISyntaxException; import java.net.URL; @@ -33,6 +34,7 @@ */ public class Gitiles extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java index 1b728c523c..6cdb8fbf52 100644 --- a/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java +++ b/src/main/java/hudson/plugins/git/browser/GitoriousWeb.java @@ -13,6 +13,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -20,6 +21,7 @@ */ public class GitoriousWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/GogsGit.java b/src/main/java/hudson/plugins/git/browser/GogsGit.java index fefa6de35b..0311ee992b 100644 --- a/src/main/java/hudson/plugins/git/browser/GogsGit.java +++ b/src/main/java/hudson/plugins/git/browser/GogsGit.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class GogsGit extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/KilnGit.java b/src/main/java/hudson/plugins/git/browser/KilnGit.java index 5bcece4fc8..1b7880b725 100644 --- a/src/main/java/hudson/plugins/git/browser/KilnGit.java +++ b/src/main/java/hudson/plugins/git/browser/KilnGit.java @@ -16,6 +16,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -23,6 +24,7 @@ */ public class KilnGit extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/Phabricator.java b/src/main/java/hudson/plugins/git/browser/Phabricator.java index c511db55be..e2102eeeb9 100644 --- a/src/main/java/hudson/plugins/git/browser/Phabricator.java +++ b/src/main/java/hudson/plugins/git/browser/Phabricator.java @@ -13,6 +13,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -20,6 +21,7 @@ */ public class Phabricator extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; private final String repo; @@ -44,7 +46,7 @@ public String getRepo() { */ @Override public URL getChangeSetLink(GitChangeSet changeSet) throws IOException { - return new URL(getUrl(), String.format("/r%s%s", this.getRepo(), changeSet.getId())); + return new URL(getUrl(), "/r%s%s".formatted(this.getRepo(), changeSet.getId())); } /** @@ -61,7 +63,7 @@ public URL getChangeSetLink(GitChangeSet changeSet) throws IOException { public URL getDiffLink(Path path) throws IOException { final GitChangeSet changeSet = path.getChangeSet(); final String sha = changeSet.getId(); - final String spec = String.format("/diffusion/%s/change/master/%s;%s", this.getRepo(), path.getPath(), sha); + final String spec = "/diffusion/%s/change/master/%s;%s".formatted(this.getRepo(), path.getPath(), sha); return new URL(getUrl(), spec); } @@ -77,7 +79,7 @@ public URL getDiffLink(Path path) throws IOException { public URL getFileLink(Path path) throws IOException { final GitChangeSet changeSet = path.getChangeSet(); final String sha = changeSet.getId(); - final String spec = String.format("/diffusion/%s/history/master/%s;%s", this.getRepo(), path.getPath(), sha); + final String spec = "/diffusion/%s/history/master/%s;%s".formatted(this.getRepo(), path.getPath(), sha); return encodeURL(new URL(getUrl(), spec)); } diff --git a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java index 5106f56fe1..43414e59b3 100644 --- a/src/main/java/hudson/plugins/git/browser/RedmineWeb.java +++ b/src/main/java/hudson/plugins/git/browser/RedmineWeb.java @@ -14,6 +14,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -23,6 +24,7 @@ */ public class RedmineWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/RhodeCode.java b/src/main/java/hudson/plugins/git/browser/RhodeCode.java index fc11d50fe4..a5064bf236 100644 --- a/src/main/java/hudson/plugins/git/browser/RhodeCode.java +++ b/src/main/java/hudson/plugins/git/browser/RhodeCode.java @@ -15,6 +15,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -22,6 +23,7 @@ */ public class RhodeCode extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/Stash.java b/src/main/java/hudson/plugins/git/browser/Stash.java index 71942b227c..3aeafc89c4 100644 --- a/src/main/java/hudson/plugins/git/browser/Stash.java +++ b/src/main/java/hudson/plugins/git/browser/Stash.java @@ -14,6 +14,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.io.Serial; import java.net.URL; /** @@ -21,6 +22,7 @@ */ public class Stash extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; @DataBoundConstructor diff --git a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java index fda7468d07..f0d6ea3f62 100644 --- a/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowser.java @@ -39,13 +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 = "commit/%s#path=%s&_a=compare".formatted(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 = "commit/%s#path=%s&_a=history".formatted(path.getChangeSet().getId(), path.getPath()); return encodeURL(new URL(getRepoUrl(path.getChangeSet()), spec)); } diff --git a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java index f5ec81299d..f04c38c41a 100644 --- a/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java +++ b/src/main/java/hudson/plugins/git/browser/ViewGitWeb.java @@ -24,6 +24,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.servlet.ServletException; import java.io.IOException; +import java.io.Serial; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; @@ -31,6 +32,7 @@ public class ViewGitWeb extends GitRepositoryBrowser { + @Serial private static final long serialVersionUID = 1L; private final String projectName; diff --git a/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java b/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java index 98180eee62..d2bd9e0d09 100644 --- a/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java +++ b/src/main/java/hudson/plugins/git/extensions/GitSCMExtension.java @@ -82,8 +82,8 @@ public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, Tas * @throws GitException on git error */ 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); + if (context instanceof AbstractProject project) { + return getWorkingDirectory(scm, project, workspace, environment, listener); } return null; } @@ -136,8 +136,8 @@ public FilePath getWorkingDirectory(GitSCM scm, AbstractProject context, F * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + return decorateRevisionToBuild(scm, abstractBuild, git, buildListener, marked, rev); } else { return rev; } @@ -163,8 +163,8 @@ public Revision decorateRevisionToBuild(GitSCM scm, AbstractBuild build, Gi * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + beforeCheckout(scm, abstractBuild, git, buildListener); } } @@ -192,8 +192,8 @@ public void beforeCheckout(GitSCM scm, AbstractBuild build, GitClient git, * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + onCheckoutCompleted(scm, abstractBuild, git, buildListener); } } @@ -252,8 +252,8 @@ public void determineSupportForJGit(GitSCM scm, @NonNull UnsupportedCommand unsu * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + decorateCloneCommand(scm, abstractBuild, git, buildListener, cmd); } } @@ -307,8 +307,8 @@ public void decorateFetchCommand(GitSCM scm, @CheckForNull Run run, GitClie * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + decorateMergeCommand(scm, abstractBuild, git, buildListener, cmd); } } @@ -331,8 +331,8 @@ public void decorateMergeCommand(GitSCM scm, AbstractBuild build, GitClien * @throws GitException on git error */ 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); + if (build instanceof AbstractBuild abstractBuild && listener instanceof BuildListener buildListener) { + decorateCheckoutCommand(scm, abstractBuild, git, buildListener, cmd); } } 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..fe2d0d8efa 100644 --- a/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java +++ b/src/main/java/hudson/plugins/git/extensions/impl/SparseCheckoutPath.java @@ -10,11 +10,13 @@ import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted; import org.kohsuke.stapler.DataBoundConstructor; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; public class SparseCheckoutPath extends AbstractDescribableImpl implements Serializable { + @Serial private static final long serialVersionUID = -6177158367915899356L; @SuppressFBWarnings(value="SE_TRANSIENT_FIELD_NOT_RESTORED", justification="Default value is OK in deserialization") diff --git a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java index 798aba91d7..c74057b9c4 100644 --- a/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java +++ b/src/main/java/hudson/plugins/git/opt/PreBuildMergeOptions.java @@ -6,6 +6,7 @@ import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; +import java.io.Serial; import java.io.Serializable; /** @@ -15,6 +16,7 @@ */ @ExportedBean(defaultVisibility = 999) public class PreBuildMergeOptions implements Serializable { + @Serial private static final long serialVersionUID = 2L; /** diff --git a/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java b/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java index e3af18e6e0..f0a12bec58 100644 --- a/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/AncestryBuildChooser.java @@ -8,6 +8,7 @@ import hudson.remoting.VirtualChannel; import java.io.IOException; +import java.io.Serial; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; @@ -157,6 +158,7 @@ public String getDisplayName() { return Messages.BuildChooser_Ancestry(); } } - + + @Serial 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..8785a0f536 100644 --- a/src/main/java/hudson/plugins/git/util/Build.java +++ b/src/main/java/hudson/plugins/git/util/Build.java @@ -9,6 +9,7 @@ import org.kohsuke.stapler.export.ExportedBean; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -19,6 +20,7 @@ */ @ExportedBean(defaultVisibility = 999) public class Build implements Serializable, Cloneable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/hudson/plugins/git/util/BuildChooser.java b/src/main/java/hudson/plugins/git/util/BuildChooser.java index d574f3d775..cac973911e 100644 --- a/src/main/java/hudson/plugins/git/util/BuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/BuildChooser.java @@ -16,6 +16,7 @@ import org.jenkinsci.plugins.gitclient.GitClient; import java.io.IOException; +import java.io.Serial; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -259,6 +260,7 @@ public static List allApplicableTo(Item item) { return result; } + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/hudson/plugins/git/util/BuildData.java b/src/main/java/hudson/plugins/git/util/BuildData.java index de9c1c8c63..63c44ea57e 100644 --- a/src/main/java/hudson/plugins/git/util/BuildData.java +++ b/src/main/java/hudson/plugins/git/util/BuildData.java @@ -9,6 +9,8 @@ import hudson.plugins.git.Branch; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; + +import java.io.Serial; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; @@ -30,6 +32,7 @@ import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; + /** * Captures the Git related information for a build. * @@ -39,6 +42,7 @@ */ @ExportedBean(defaultVisibility = 999) public class BuildData implements Action, Serializable, Cloneable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/hudson/plugins/git/util/GitUtils.java b/src/main/java/hudson/plugins/git/util/GitUtils.java index 3ee5e46bda..68998f8a12 100644 --- a/src/main/java/hudson/plugins/git/util/GitUtils.java +++ b/src/main/java/hudson/plugins/git/util/GitUtils.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.io.Serial; import java.io.Serializable; import java.text.MessageFormat; import java.util.*; @@ -365,8 +366,7 @@ private static void addEnvironmentContributingActionsValues(EnvVars env, Abstrac List buildActions = b.getAllActions(); for (Action action : buildActions) { // most importantly, ParametersAction will be processed here (for parameterized builds) - if (action instanceof ParametersAction) { - ParametersAction envAction = (ParametersAction) action; + if (action instanceof ParametersAction envAction) { envAction.buildEnvironment(b, env); } } @@ -410,5 +410,6 @@ public static String[] fixupNames(String[] names, String[] urls) { private static final Logger LOGGER = Logger.getLogger(GitUtils.class.getName()); + @Serial private static final long serialVersionUID = 1L; } diff --git a/src/main/java/hudson/plugins/git/util/InverseBuildChooser.java b/src/main/java/hudson/plugins/git/util/InverseBuildChooser.java index 349d18f206..35c77958cc 100644 --- a/src/main/java/hudson/plugins/git/util/InverseBuildChooser.java +++ b/src/main/java/hudson/plugins/git/util/InverseBuildChooser.java @@ -10,6 +10,7 @@ import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; +import java.io.Serial; import java.util.*; /** @@ -103,6 +104,7 @@ public String getDisplayName() { } } + @Serial private static final long serialVersionUID = 1L; } diff --git a/src/main/java/hudson/plugins/git/util/RevCommitRepositoryCallback.java b/src/main/java/hudson/plugins/git/util/RevCommitRepositoryCallback.java index 33e1ca9cc7..2ee4b37755 100644 --- a/src/main/java/hudson/plugins/git/util/RevCommitRepositoryCallback.java +++ b/src/main/java/hudson/plugins/git/util/RevCommitRepositoryCallback.java @@ -2,6 +2,8 @@ import hudson.remoting.VirtualChannel; import java.io.IOException; +import java.io.Serial; + import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; @@ -11,6 +13,7 @@ * Retrieves {@link RevCommit} from given {@link Build} revision. */ public final class RevCommitRepositoryCallback implements RepositoryCallback { + @Serial private static final long serialVersionUID = 1L; private final Build revToBuild; diff --git a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java index 334f292f48..654807559b 100644 --- a/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java @@ -252,8 +252,8 @@ public String getGitTool() { public List getExtensions() { List extensions = new ArrayList<>(); for (SCMSourceTrait t : getTraits()) { - if (t instanceof GitSCMExtensionTrait) { - extensions.add(((GitSCMExtensionTrait) t).getExtension()); + if (t instanceof GitSCMExtensionTrait trait) { + extensions.add(trait.getExtension()); } } return Collections.unmodifiableList(extensions); @@ -441,25 +441,25 @@ protected SCMRevision retrieve(@NonNull final SCMHead head, @NonNull final TaskL return doRetrieve(new Retriever() { @Override public SCMRevision run(GitClient client, String remoteName) throws GitException, IOException, InterruptedException { - if (head instanceof GitTagSCMHead) { + if (head instanceof GitTagSCMHead mHead) { try { ObjectId objectId = client.revParse(Constants.R_TAGS + head.getName()); - return new GitTagSCMRevision((GitTagSCMHead) head, objectId.name()); + return new GitTagSCMRevision(mHead, objectId.name()); } catch (GitException e) { // tag does not exist return null; } - } else if (head instanceof GitBranchSCMHead) { + } else if (head instanceof GitBranchSCMHead mHead) { for (Branch b : client.getRemoteBranches()) { String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); if (branchName.equals(head.getName())) { - return new GitBranchSCMRevision((GitBranchSCMHead)head, b.getSHA1String()); + return new GitBranchSCMRevision(mHead, b.getSHA1String()); } } - } else if (head instanceof GitRefSCMHead) { + } else if (head instanceof GitRefSCMHead mHead) { try { - ObjectId objectId = client.revParse(((GitRefSCMHead) head).getRef()); - return new GitRefSCMRevision((GitRefSCMHead)head, objectId.name()); + ObjectId objectId = client.revParse(mHead.getRef()); + return new GitRefSCMRevision(mHead, objectId.name()); } catch (GitException e) { // ref could not be found return null; @@ -1253,8 +1253,8 @@ protected List retrieveActions(@CheckForNull SCMSourceEvent event, @NonN 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)) { + if (owner instanceof Actionable actionable) { + for (GitRemoteHeadRefAction a: actionable.getActions(GitRemoteHeadRefAction.class)) { if (getRemote().equals(a.getRemote())) { if (head.getName().equals(a.getName())) { return Collections.singletonList(new PrimaryInstanceMetadataAction()); diff --git a/src/main/java/jenkins/plugins/git/DisableHooks.java b/src/main/java/jenkins/plugins/git/DisableHooks.java index 4edb8e51c3..e7c0fc4735 100644 --- a/src/main/java/jenkins/plugins/git/DisableHooks.java +++ b/src/main/java/jenkins/plugins/git/DisableHooks.java @@ -3,6 +3,8 @@ import hudson.Functions; import hudson.remoting.VirtualChannel; import java.io.IOException; +import java.io.Serial; + import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.jenkinsci.plugins.gitclient.RepositoryCallback; @@ -11,6 +13,7 @@ * Disables git hooks. This can get remotely executed on agents. */ class DisableHooks implements RepositoryCallback { + @Serial private static final long serialVersionUID = 1L; static final String DISABLED_WIN = "NUL:"; diff --git a/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java b/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java index 4bf85259c0..a08ca7310a 100644 --- a/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java +++ b/src/main/java/jenkins/plugins/git/GitRemoteHeadRefAction.java @@ -2,6 +2,8 @@ import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.InvisibleAction; + +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -10,6 +12,7 @@ */ public class GitRemoteHeadRefAction extends InvisibleAction implements Serializable { + @Serial private static final long serialVersionUID = 1L; @NonNull diff --git a/src/main/java/jenkins/plugins/git/GitSCMBuilder.java b/src/main/java/jenkins/plugins/git/GitSCMBuilder.java index 886e528585..bd0227913d 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMBuilder.java +++ b/src/main/java/jenkins/plugins/git/GitSCMBuilder.java @@ -499,15 +499,14 @@ public GitSCM build() { extensions.add(new GitSCMSourceDefaults(head() instanceof TagSCMHead)); } SCMRevision revision = revision(); - if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) { + if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl impl) { // remove any conflicting BuildChooserSetting if present extensions.removeIf(gitSCMExtension -> gitSCMExtension instanceof BuildChooserSetting); extensions.add(new BuildChooserSetting(new AbstractGitSCMSource.SpecificRevisionBuildChooser( - (AbstractGitSCMSource.SCMRevisionImpl) revision))); + impl))); } SCMHead scmHead = head(); - if (scmHead instanceof GitRefSCMHead) { - GitRefSCMHead gitHead = (GitRefSCMHead) scmHead; + if (scmHead instanceof GitRefSCMHead gitHead) { withRefSpec(gitHead.getRef()); } try { diff --git a/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java b/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java index 6d2599c184..b63c09d254 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java +++ b/src/main/java/jenkins/plugins/git/GitSCMFileSystem.java @@ -212,8 +212,8 @@ public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputS try (Writer out = new OutputStreamWriter(changeLogStream, StandardCharsets.UTF_8)) { changelog.includes(commitId); ObjectId fromCommitId; - if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) { - fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash()); + if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl impl) { + fromCommitId = ObjectId.fromString(impl.getHash()); changelog.excludes(fromCommitId); } else { fromCommitId = null; @@ -257,15 +257,15 @@ public static class BuilderImpl extends SCMFileSystem.Builder { @Override public boolean supports(SCM source) { - return source instanceof GitSCM - && ((GitSCM) source).getUserRemoteConfigs().size() == 1 - && ((GitSCM) source).getBranches().size() == 1 - && !((GitSCM) source).getBranches().get(0).getName().equals("*") // JENKINS-57587 + return source instanceof GitSCM gscm + && gscm.getUserRemoteConfigs().size() == 1 + && gscm.getBranches().size() == 1 + && !gscm.getBranches().get(0).getName().equals("*") // JENKINS-57587 && ( - ((GitSCM) source).getBranches().get(0).getName().matches( + gscm.getBranches().get(0).getName().matches( "^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" ) - || ((GitSCM) source).getBranches().get(0).getName().matches( + || gscm.getBranches().get(0).getName().matches( "^((\\Q" + Constants.R_TAGS + "\\E.*)|([^/]+)|(\\*/[^/*]+(/[^/*]+)*))$" ) ); diff --git a/src/main/java/jenkins/plugins/git/GitSCMSource.java b/src/main/java/jenkins/plugins/git/GitSCMSource.java index a18116b5b1..fc811b7044 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMSource.java +++ b/src/main/java/jenkins/plugins/git/GitSCMSource.java @@ -220,8 +220,7 @@ protected Object readResolve() throws ObjectStreamException { EXTENSIONS: for (GitSCMExtension extension : extensions) { for (SCMSourceTraitDescriptor d : SCMSourceTrait.all()) { - if (d instanceof GitSCMExtensionTraitDescriptor) { - GitSCMExtensionTraitDescriptor descriptor = (GitSCMExtensionTraitDescriptor) d; + if (d instanceof GitSCMExtensionTraitDescriptor descriptor) { if (descriptor.getExtensionClass().isInstance(extension)) { try { SCMSourceTrait trait = descriptor.convertToTrait(extension); @@ -331,8 +330,7 @@ public void setExtensions(@CheckForNull List extensions) { EXTENSIONS: for (GitSCMExtension extension : Util.fixNull(extensions)) { for (SCMSourceTraitDescriptor d : SCMSourceTrait.all()) { - if (d instanceof GitSCMExtensionTraitDescriptor) { - GitSCMExtensionTraitDescriptor descriptor = (GitSCMExtensionTraitDescriptor) d; + if (d instanceof GitSCMExtensionTraitDescriptor descriptor) { if (descriptor.getExtensionClass().isInstance(extension)) { try { SCMSourceTrait trait = descriptor.convertToTrait(extension); @@ -369,12 +367,12 @@ public String getRawRefSpecs() { String remoteName = null; RefSpecsSCMSourceTrait refSpecs = null; for (SCMSourceTrait trait : traits) { - if (trait instanceof RemoteNameSCMSourceTrait) { - remoteName = ((RemoteNameSCMSourceTrait) trait).getRemoteName(); + if (trait instanceof RemoteNameSCMSourceTrait sourceTrait) { + remoteName = sourceTrait.getRemoteName(); if (refSpecs != null) break; } - if (trait instanceof RefSpecsSCMSourceTrait) { - refSpecs = (RefSpecsSCMSourceTrait) trait; + if (trait instanceof RefSpecsSCMSourceTrait sourceTrait) { + refSpecs = sourceTrait; if (remoteName != null) break; } } @@ -432,7 +430,7 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, return new StandardListBoxModel() .includeEmptyValue() .includeMatchingAs( - context instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task)context) : ACL.SYSTEM, + context instanceof Queue.Task t ? Tasks.getAuthenticationOf(t) : ACL.SYSTEM, context, StandardUsernameCredentials.class, URIRequirementBuilder.fromUri(remote).build(), @@ -475,8 +473,8 @@ public FormValidation doCheckCredentialsId(@AncestorInPath Item context, for (ListBoxModel.Option o : CredentialsProvider.listCredentialsInItem( StandardUsernameCredentials.class, context, - context instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) context) + context instanceof Queue.Task t + ? Tasks.getAuthenticationOf2(t) : ACL.SYSTEM2, URIRequirementBuilder.fromUri(remote).build(), GitClient.CREDENTIALS_MATCHER)) { @@ -584,8 +582,7 @@ public String getSourceName() { @Override public boolean isMatch(SCMSource source) { - if (source instanceof GitSCMSource) { - GitSCMSource git = (GitSCMSource) source; + if (source instanceof GitSCMSource git) { GitSCMSourceContext ctx = new GitSCMSourceContext<>(null, SCMHeadObserver.none()) .withTraits(git.getTraits()); @@ -611,8 +608,7 @@ public boolean isMatch(SCMSource source) { @NonNull @Override public Map heads(@NonNull SCMSource source) { - if (source instanceof GitSCMSource) { - GitSCMSource git = (GitSCMSource) source; + if (source instanceof GitSCMSource git) { GitSCMSourceContext ctx = new GitSCMSourceContext<>(null, SCMHeadObserver.none()) .withTraits(git.getTraits()); @@ -649,8 +645,7 @@ public boolean isMatch(@NonNull SCM scm) { } else { for (final SCMSourceOwner owner : SCMSourceOwners.all()) { for (SCMSource source : owner.getSCMSources()) { - if (source instanceof GitSCMSource) { - GitSCMSource git = (GitSCMSource) source; + if (source instanceof GitSCMSource git) { GitSCMSourceContext ctx = new GitSCMSourceContext<>(null, SCMHeadObserver.none()) .withTraits(git.getTraits()); diff --git a/src/main/java/jenkins/plugins/git/GitSCMTelescope.java b/src/main/java/jenkins/plugins/git/GitSCMTelescope.java index 9862c34d92..59057b7c6b 100644 --- a/src/main/java/jenkins/plugins/git/GitSCMTelescope.java +++ b/src/main/java/jenkins/plugins/git/GitSCMTelescope.java @@ -71,8 +71,8 @@ public abstract class GitSCMTelescope extends SCMFileSystem.Builder { @CheckForNull public static GitSCMTelescope of(@NonNull GitSCM source) { for (SCMFileSystem.Builder b : ExtensionList.lookup(SCMFileSystem.Builder.class)) { - if (b instanceof GitSCMTelescope && b.supports(source)) { - return (GitSCMTelescope) b; + if (b instanceof GitSCMTelescope telescope && b.supports(source)) { + return telescope; } if (b instanceof GitSCMFileSystem.BuilderImpl) { // telescopes must come before the fallback GitSCMFileSystem.BuilderImpl otherwise they would @@ -93,8 +93,8 @@ public static GitSCMTelescope of(@NonNull GitSCM source) { @CheckForNull public static GitSCMTelescope of(@NonNull AbstractGitSCMSource source) { for (SCMFileSystem.Builder b : ExtensionList.lookup(SCMFileSystem.Builder.class)) { - if (b instanceof GitSCMTelescope && b.supports(source)) { - return (GitSCMTelescope) b; + if (b instanceof GitSCMTelescope telescope && b.supports(source)) { + return telescope; } if (GitSCMFileSystem.BuilderImpl.class.equals(b.getClass())) { // telescopes must come before the fallback GitSCMFileSystem.BuilderImpl otherwise they would @@ -132,9 +132,7 @@ public abstract void validate(@NonNull String remote, @CheckForNull StandardCred */ @Override public final boolean supports(@NonNull SCM source) { - if (source instanceof GitSCM) { - // we only support the GitSCM if the branch is completely unambiguous - GitSCM git = (GitSCM) source; + if (source instanceof GitSCM git) { List configs = git.getUserRemoteConfigs(); List branches = git.getBranches(); if (configs.size() == 1) { @@ -153,8 +151,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 agscms && source.getOwner() != null && supports( + agscms.getRemote()); } /** @@ -164,9 +162,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())) { - AbstractGitSCMSource git = (AbstractGitSCMSource) source; + if (source instanceof AbstractGitSCMSource git && owner != null && supports( + git.getRemote())) { String remote = git.getRemote(); StandardUsernameCredentials credentials = git.getCredentials(); validate(remote, credentials); @@ -181,9 +178,7 @@ public final SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead hea @Override public final SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, SCMRevision rev) throws IOException, InterruptedException { - if (scm instanceof GitSCM) { - // we only support the GitSCM if the branch is completely unambiguous - GitSCM git = (GitSCM) scm; + if (scm instanceof GitSCM git) { List configs = git.getUserRemoteConfigs(); List branches = git.getBranches(); if (configs.size() == 1) { @@ -196,8 +191,8 @@ public final SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, SCMRevis if (credentialsId != null) { List urlCredentials = CredentialsProvider .lookupCredentialsInItem(StandardUsernameCredentials.class, owner, - owner instanceof Queue.Task - ? Tasks.getAuthenticationOf2((Queue.Task) owner) + owner instanceof Queue.Task t + ? Tasks.getAuthenticationOf2(t) : ACL.SYSTEM2, URIRequirementBuilder.fromUri(remote).build()); credentials = CredentialsMatchers.firstOrNull( urlCredentials, diff --git a/src/main/java/jenkins/plugins/git/UnsetHooks.java b/src/main/java/jenkins/plugins/git/UnsetHooks.java index 453cb41a1c..54cebbb89f 100644 --- a/src/main/java/jenkins/plugins/git/UnsetHooks.java +++ b/src/main/java/jenkins/plugins/git/UnsetHooks.java @@ -2,6 +2,7 @@ import hudson.remoting.VirtualChannel; import java.io.IOException; +import java.io.Serial; import java.util.logging.Logger; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; @@ -13,6 +14,7 @@ class UnsetHooks implements RepositoryCallback { private static final Logger LOGGER = Logger.getLogger(UnsetHooks.class.getName()); + @Serial private static final long serialVersionUID = 1L; @Override @@ -20,7 +22,7 @@ public Object invoke(Repository repo, VirtualChannel channel) throws IOException final StoredConfig repoConfig = repo.getConfig(); final String val = repoConfig.getString("core", null, "hooksPath"); if (val != null && !val.isEmpty() && !DisableHooks.DISABLED_NIX.equals(val) && !DisableHooks.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(() -> "core.hooksPath explicitly set to %s and will be left intact on %s.".formatted(val, repo.getDirectory())); } else { repoConfig.unset("core", null, "hooksPath"); repoConfig.save(); diff --git a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java index f4f2243be7..f6cea04a4e 100644 --- a/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java +++ b/src/main/java/jenkins/plugins/git/traits/GitSCMExtensionTraitDescriptor.java @@ -109,8 +109,7 @@ protected GitSCMExtensionTraitDescriptor(Class clazz, protected GitSCMExtensionTraitDescriptor() { super(); Type bt = Types.getBaseClass(clazz, GitSCMExtensionTrait.class); - if (bt instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType) bt; + if (bt instanceof ParameterizedType pt) { // this 'extension' is the closest approximation of E of GitSCMExtensionTrait. extension = Types.erasure(pt.getActualTypeArguments()[0]); if (!GitSCMExtension.class.isAssignableFrom(extension) || GitSCMExtension.class == extension) { diff --git a/src/main/java/jenkins/plugins/git/traits/PruneStaleBranchTrait.java b/src/main/java/jenkins/plugins/git/traits/PruneStaleBranchTrait.java index 6c7494aa1d..a1e9b21022 100644 --- a/src/main/java/jenkins/plugins/git/traits/PruneStaleBranchTrait.java +++ b/src/main/java/jenkins/plugins/git/traits/PruneStaleBranchTrait.java @@ -52,8 +52,7 @@ public PruneStaleBranchTrait() { */ @Override protected void decorateContext(SCMSourceContext context) { - if (context instanceof GitSCMSourceContext) { - GitSCMSourceContext ctx = (GitSCMSourceContext) context; + if (context instanceof GitSCMSourceContext ctx) { ctx.pruneRefs(true); } } diff --git a/src/test/java/hudson/plugins/git/AbstractGitProject.java b/src/test/java/hudson/plugins/git/AbstractGitProject.java index 0800d8749a..4b468ca9fd 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitProject.java +++ b/src/test/java/hudson/plugins/git/AbstractGitProject.java @@ -254,8 +254,8 @@ public String invoke(File f, VirtualChannel channel) throws IOException, Interru protected EnvVars getEnvVars(FreeStyleProject project) { for (hudson.tasks.Builder b : project.getBuilders()) { - if (b instanceof CaptureEnvironmentBuilder) { - return ((CaptureEnvironmentBuilder) b).getEnvVars(); + if (b instanceof CaptureEnvironmentBuilder builder) { + return builder.getEnvVars(); } } return new EnvVars(); diff --git a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java index bcb83147cb..5b3cd44207 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java +++ b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java @@ -279,8 +279,8 @@ protected MatrixBuild build(final MatrixProject project, final Result expectedRe protected EnvVars getEnvVars(FreeStyleProject project) { for (hudson.tasks.Builder b : project.getBuilders()) { - if (b instanceof CaptureEnvironmentBuilder) { - return ((CaptureEnvironmentBuilder)b).getEnvVars(); + if (b instanceof CaptureEnvironmentBuilder builder) { + return builder.getEnvVars(); } } return new EnvVars(); diff --git a/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java b/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java index 453cfb4c7b..e5e7fba9be 100644 --- a/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java +++ b/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java @@ -222,11 +222,13 @@ public void gitStepTLSCheck() throws Throwable { { // http with creds rejected p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " dir('foo') {\n" + - " git url: 'http://foo.com/beer.git', credentialsId: 'yup'\n" + - " }\n" + - "}", true)); + """ + node { + dir('foo') { + git url: 'http://foo.com/beer.git', credentialsId: 'yup' + } + } + """, true)); WorkflowRun b = r.buildAndAssertStatus(Result.FAILURE, p); r.assertLogContains(Messages.git_fips_url_notsecured(), b); } @@ -272,12 +274,14 @@ public void checkoutStepTLSCheck() throws Throwable { // http with creds rejected // Intentionally using modern syntax to check compatibility p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " dir('foo') {\n" + - " checkout scmGit(branches: [[name: 'master']],\n" + - " userRemoteConfigs: [[credentialsId: 'foocreds', url: 'http://github.com/foo/beer.git']])\n" + - " }\n" + - "}", true)); + """ + node { + dir('foo') { + checkout scmGit(branches: [[name: 'master']], + userRemoteConfigs: [[credentialsId: 'foocreds', url: 'http://github.com/foo/beer.git']]) + } + } + """, true)); WorkflowRun b = r.buildAndAssertStatus(Result.FAILURE, p); r.assertLogContains(Messages.git_fips_url_notsecured(), b); } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java index 9570d87cef..eb1bc5a362 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java @@ -142,7 +142,7 @@ public static void createRepo() throws Exception { private ObjectId commitOneFile(GitClient gitClient, final String commitSummary) throws Exception { String path = "One-File.txt"; - String content = String.format("A random UUID: %s\n", UUID.randomUUID()); + String content = "A random UUID: %s\n".formatted(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 commitMessage = commitSummary + commitMessageBody; diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index 10e9881b09..d535db9694 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -2192,28 +2192,30 @@ 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 { + def tokenBranch = '' + def tokenRevision = '' + def checkout1 = checkout([$class: 'GitSCM', branches: [[name: 'git-1.1']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]]) + echo "checkout1: ${checkout1}" + tokenBranch = tm '${GIT_BRANCH}' + tokenRevision = tm '${GIT_REVISION}' + echo "token1: ${tokenBranch}" + echo "revision1: ${tokenRevision}" + def checkout2 = checkout([$class: 'GitSCM', branches: [[name: 'git-2.0.2']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]]) + echo "checkout2: ${checkout2}" + tokenBranch = tm '${GIT_BRANCH,all=true}' + tokenRevision = tm '${GIT_REVISION,length=8}' + echo "token2: ${tokenBranch}" + echo "revision2: ${tokenRevision}" + def checkout3 = checkout([$class: 'GitSCM', branches: [[name: 'git-3.0.0']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']]]) + echo "checkout3: ${checkout3}" + tokenBranch = tm '${GIT_BRANCH,fullName=true}' + tokenRevision = tm '${GIT_REVISION,length=6}' + echo "token3: ${tokenBranch}" + echo "revision3: ${tokenRevision}" + } + """, true)); WorkflowRun b = r.buildAndAssertSuccess(p); String log = b.getLog(); diff --git a/src/test/java/hudson/plugins/git/GitStatusTest.java b/src/test/java/hudson/plugins/git/GitStatusTest.java index 64637ccd8b..65613cb26a 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTest.java @@ -308,8 +308,8 @@ public void testDoNotifyCommitBranchWithWildcard() throws Exception { private void assertAdditionalParameters(Collection actions) { for (Action action: actions) { - if (action instanceof ParametersAction) { - final List parameters = ((ParametersAction) action).getParameters(); + if (action instanceof ParametersAction parametersAction) { + final List parameters = parametersAction.getParameters(); assertEquals(2, parameters.size()); for (ParameterValue value : parameters) { assertTrue((value.getName().equals("paramKey1") && value.getValue().equals("paramValue1")) diff --git a/src/test/java/hudson/plugins/git/GitStepTest.java b/src/test/java/hudson/plugins/git/GitStepTest.java index 72f5ee8b1a..d0c50efae9 100644 --- a/src/test/java/hudson/plugins/git/GitStepTest.java +++ b/src/test/java/hudson/plugins/git/GitStepTest.java @@ -317,9 +317,11 @@ private WorkflowJob createJob() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "demo"); p.addTrigger(new SCMTrigger("")); // no schedule, use notifyCommit only p.setDefinition(new CpsFlowDefinition( - "node {\n" + - " error('this should never be called')\n" + - "}", true)); + """ + node { + error('this should never be called') + } + """, true)); return p; } diff --git a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java index 6824c5ccfd..13b6810e58 100644 --- a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java @@ -155,7 +155,7 @@ public void testGuessBrowser() throws Exception { private void assertGuessURL(String repo, String web) throws Exception { RepositoryBrowser guess = new GitSCM(repo).guessBrowser(); - String actual = guess instanceof GithubWeb ? ((GithubWeb) guess).getRepoUrl() : null; + String actual = guess instanceof GithubWeb gw ? gw.getRepoUrl() : null; assertEquals("For repo '" + repo + "':", web, actual); } @@ -170,7 +170,7 @@ public void guessBrowserSCMSource() throws Exception { private void assertGuessURL(String remote, String web, String... refSpecs) { RepositoryBrowser guess = new MockSCMSource(remote, refSpecs).build(new SCMHead("master")).guessBrowser(); - String actual = guess instanceof GithubWeb ? ((GithubWeb) guess).getRepoUrl() : null; + String actual = guess instanceof GithubWeb gw ? gw.getRepoUrl() : null; assertEquals(web, actual); } 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..41bc70e0d5 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java @@ -79,7 +79,7 @@ public void testSingleRevision() throws Exception { r.assertBuildStatusSuccess(build); boolean result = build.getLog(100).contains( - String.format("Scheduling another build to catch up with %s", project.getName())); + "Scheduling another build to catch up with %s".formatted(project.getName())); Assert.assertFalse("Single revision scheduling did not prevent a build of a different revision", result); } @@ -109,7 +109,7 @@ public void testMultiRevision() throws Exception { final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile); r.assertBuildStatusSuccess(build); - r.waitForMessage(String.format("Scheduling another build to catch up with %s", project.getName()), build); + r.waitForMessage("Scheduling another build to catch up with %s".formatted(project.getName()), build); // Wait briefly for newly scheduled job to start. // Once job has started, waitForAllJobsToComplete will hold the test until job completes. 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..f76050fe35 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java @@ -61,9 +61,9 @@ public static Collection permuteRefSpecVariable() { private static Builder createEnvEchoBuilder(String envVarName) { if (isWindows()) { - return new BatchFile(String.format("echo %s=%%%s%%", envVarName, envVarName)); + return new BatchFile("echo %s=%%%s%%".formatted(envVarName, envVarName)); } - return new Shell(String.format("echo \"%s=${%s}\"", envVarName, envVarName)); + return new Shell("echo \"%s=${%s}\"".formatted(envVarName, envVarName)); } @Before diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java index b27cf42403..64a05d5917 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java @@ -227,8 +227,7 @@ public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() th Set scmHeadSet = source.fetch(listener); long now = System.currentTimeMillis(); for (SCMHead scmHead : scmHeadSet) { - if (scmHead instanceof GitTagSCMHead) { - GitTagSCMHead tagHead = (GitTagSCMHead) scmHead; + if (scmHead instanceof GitTagSCMHead tagHead) { // FAT file system time stamps only resolve to 2 second boundary // EXT3 file system time stamps only resolve to 1 second boundary long fileTimeStampFuzz = isWindows() ? 2000L : 1000L; @@ -520,8 +519,8 @@ private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception { List actions = source.fetchActions(null, listener); GitRemoteHeadRefAction refAction = null; for (Action a: actions) { - if (a instanceof GitRemoteHeadRefAction) { - refAction = (GitRemoteHeadRefAction) a; + if (a instanceof GitRemoteHeadRefAction action) { + refAction = action; break; } } @@ -533,8 +532,8 @@ private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception { PrimaryInstanceMetadataAction primary = null; for (Action a: actions) { - if (a instanceof PrimaryInstanceMetadataAction) { - primary = (PrimaryInstanceMetadataAction) a; + if (a instanceof PrimaryInstanceMetadataAction action) { + primary = action; break; } } diff --git a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java index 996181e239..84ef955eb7 100644 --- a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java @@ -131,7 +131,7 @@ protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenk final List browsers = new ArrayList<>(); for (LibraryConfiguration library : libraries) { - final String errorMessage = String.format("Error checking library %s", library.getName()); + final String errorMessage = "Error checking library %s".formatted(library.getName()); final LibraryRetriever retriever = library.getRetriever(); assertThat(errorMessage, retriever, instanceOf(SCMRetriever.class)); final SCM scm = ((SCMRetriever) retriever).getScm(); diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java index df9b80c75e..2aead56e05 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java @@ -425,8 +425,8 @@ protected SCMFileSystem build(@NonNull String remote, StandardCredentials creden @NonNull SCMHead head, final SCMRevision rev) throws IOException, InterruptedException { final String hash; - if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl) { - hash = ((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(); + if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl impl) { + hash = impl.getHash(); } else { switch (head.getName()) { case "foo": diff --git a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java index 87c4a096ee..8d9e950bd5 100644 --- a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java @@ -801,11 +801,13 @@ 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 { + checkout( + [$class: 'GitSCM'] + ) + } + """, true)); WorkflowRun b = r.buildAndAssertStatus(hudson.model.Result.FAILURE, p); r.waitForMessage("Couldn't find any revision to build", b); } diff --git a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java index a052738ed1..9402b2d644 100644 --- a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java @@ -20,8 +20,8 @@ public class GitSCMExtensionTraitTest { public List descriptors() { List list = new ArrayList<>(); for (Descriptor d : SCMSourceTrait.all()) { - if (d instanceof GitSCMExtensionTraitDescriptor) { - list.add((GitSCMExtensionTraitDescriptor) d); + if (d instanceof GitSCMExtensionTraitDescriptor descriptor) { + list.add(descriptor); } } return list; diff --git a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java index 418640988b..78de12bc6d 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java @@ -45,15 +45,15 @@ protected FreeStyleProject configureGitTagMessageJob(String refSpec, String bran protected void assertBuildEnvironment(FreeStyleBuild build, String expectedName, String expectedMessage) throws Exception { // In the freestyle shell step, unknown environment variables are returned as empty strings - r.waitForMessage(String.format("tag='%s'", Util.fixNull(expectedName)), build); - r.waitForMessage(String.format("msg='%s'", Util.fixNull(expectedMessage)), build); + r.waitForMessage("tag='%s'".formatted(Util.fixNull(expectedName)), build); + r.waitForMessage("msg='%s'".formatted(Util.fixNull(expectedMessage)), build); } private static Builder createEnvEchoBuilder(String key, String envVarName) { if (Functions.isWindows()) { - return new BatchFile(String.format("echo %s='%%%s%%'", key, envVarName)); + return new BatchFile("echo %s='%%%s%%'".formatted(key, envVarName)); } - return new Shell(String.format("echo \"%s='${%s}'\"", key, envVarName)); + return new Shell("echo \"%s='${%s}'\"".formatted(key, envVarName)); } } From f64466e66ea7d252cf9778dccfa3022255ab8d43 Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 21 Oct 2024 07:38:10 -0600 Subject: [PATCH 2/3] Remove OpenRewrite config from pom --- pom.xml | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/pom.xml b/pom.xml index b63cee0f2b..cb7a3c0d6d 100644 --- a/pom.xml +++ b/pom.xml @@ -297,23 +297,6 @@ true - - org.openrewrite.maven - rewrite-maven-plugin - 5.42.0 - - - org.openrewrite.java.migrate.UpgradeToJava17 - - - - - org.openrewrite.recipe - rewrite-migrate-java - 2.26.1 - - - From 2102a80a8788b5e26e3d519845989cf75c33f19c Mon Sep 17 00:00:00 2001 From: Mark Waite Date: Mon, 21 Oct 2024 09:22:44 -0600 Subject: [PATCH 3/3] Use formatted strings more widely No need to concatenate a string then use a formatted string for the rest --- .../git/browser/FisheyeGitRepositoryBrowser.java | 2 +- .../git/browser/GitBlitRepositoryBrowser.java | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java index bd69fc485f..eb3cc01cd4 100644 --- a/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowser.java @@ -40,7 +40,7 @@ public URL getDiffLink(Path path) throws IOException { 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) + "?r1=%s&r2=%s".formatted(r1, r2)); + return new URL(getUrl(), "%s?r1=%s&r2=%s".formatted(getPath(path), r1, r2)); } @Override diff --git a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java index 6c2e37345f..09ec87ed20 100644 --- a/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java +++ b/src/main/java/hudson/plugins/git/browser/GitBlitRepositoryBrowser.java @@ -46,8 +46,10 @@ public GitBlitRepositoryBrowser(String repoUrl, String projectName) { public URL getDiffLink(Path path) throws IOException { URL url = getUrl(); return new URL(url, - (url.getPath() + "blobdiff?r=%s&h=%s&hb=%s").formatted(encodeString(projectName), path.getChangeSet().getId(), - path.getChangeSet().getParentCommit())); + "%sblobdiff?r=%s&h=%s&hb=%s".formatted(url.getPath(), + encodeString(projectName), + path.getChangeSet().getId(), + path.getChangeSet().getParentCommit())); } @Override @@ -57,14 +59,18 @@ public URL getFileLink(Path path) throws IOException { } URL url = getUrl(); return new URL(url, - (url.getPath() + "blob?r=%s&h=%s&f=%s").formatted(encodeString(projectName), path.getChangeSet().getId(), - encodeString(path.getPath()))); + "%sblob?r=%s&h=%s&f=%s".formatted(url.getPath(), + encodeString(projectName), + path.getChangeSet().getId(), + encodeString(path.getPath()))); } @Override public URL getChangeSetLink(GitChangeSet changeSet) throws IOException { URL url = getUrl(); - return new URL(url, (url.getPath() + "commit?r=%s&h=%s").formatted(encodeString(projectName), changeSet.getId())); + return new URL(url, "%scommit?r=%s&h=%s".formatted(url.getPath(), + encodeString(projectName), + changeSet.getId())); } public String getProjectName() {