Skip to content

Commit

Permalink
fix: findings from static code analysis (PMD)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasbjerre committed Jan 29, 2024
1 parent 56ebc58 commit cf0bfeb
Show file tree
Hide file tree
Showing 16 changed files with 81 additions and 76 deletions.
24 changes: 12 additions & 12 deletions src/main/java/se/bjurr/gitchangelog/api/GitChangelogApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
import com.github.jknack.handlebars.io.FileTemplateLoader;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
Expand Down Expand Up @@ -50,17 +50,17 @@
import se.bjurr.gitchangelog.internal.util.ResourceLoader;

@SuppressFBWarnings("PATH_TRAVERSAL_IN")
public class GitChangelogApi {

public static GitChangelogApi gitChangelogApiBuilder() {
return new GitChangelogApi();
}
public final class GitChangelogApi {

private Settings settings;
private String templateContent;
private Handlebars handlebars;
private final AtomicInteger helperCounter = new AtomicInteger();

public static GitChangelogApi gitChangelogApiBuilder() {
return new GitChangelogApi();
}

private GitChangelogApi() {
this.settings = new Settings();
this.handlebars = new Handlebars();
Expand Down Expand Up @@ -103,7 +103,6 @@ public Settings getSettings() {
* @throws GitChangelogRepositoryException
*/
public void render(final Writer writer) throws GitChangelogRepositoryException {
Template template = null;
final String templateString = this.getTemplateString();

if (this.settings.getTemplateBaseDir() != null) {
Expand All @@ -112,18 +111,19 @@ public void render(final Writer writer) throws GitChangelogRepositoryException {
this.settings.getTemplateBaseDir(), this.settings.getTemplateSuffix()));
}

Template template;
try {
template = this.handlebars.compileInline(templateString);
} catch (final IOException e) {
throw new RuntimeException("Cannot render:\n\n" + templateString, e);
}

try {
final Changelog changelog = this.getChangelog(this.settings.isUseIntegrations());
final Map<String, Object> extendedVariables = this.settings.getExtendedVariables();
if (extendedVariables == null) {
throw new IllegalStateException("extendedVariables cannot be null");
}
final Changelog changelog = this.getChangelog(this.settings.isUseIntegrations());
final Context changelogContext = Context.newContext(changelog).combine(extendedVariables);
template.apply(changelogContext, writer);
} catch (final IOException e) {
Expand Down Expand Up @@ -175,7 +175,7 @@ public void prependToFile(final File file) throws GitChangelogRepositoryExceptio
final byte[] bytesToPrepend = this.render().getBytes(this.settings.getEncoding());
final byte[] originalBytes = Files.readAllBytes(file.toPath());

try (final FileOutputStream outputStream = new FileOutputStream(file)) {
try (final OutputStream outputStream = Files.newOutputStream(file.toPath())) {
outputStream.write(bytesToPrepend);
outputStream.write(originalBytes);
}
Expand All @@ -197,14 +197,14 @@ public SemanticVersion getNextSemanticVersion() throws GitChangelogRepositoryExc
}
}
final Changelog changelog = api.getChangelog(false);
final List<String> tags = api.getTagsAsStrings(changelog);
api.getTagsAsStrings(changelog);
final List<String> commits = api.getCommitMessages(changelog);
final String majorVersionPattern = api.settings.getSemanticMajorPattern().orElse(null);
final String minorVersionPattern = api.settings.getSemanticMinorPattern();
final String patchVersionPattern = api.settings.getSemanticPatchPattern();
final SemanticVersioning semanticVersioning =
new SemanticVersioning(
tags, commits, majorVersionPattern, minorVersionPattern, patchVersionPattern);
commits, majorVersionPattern, minorVersionPattern, patchVersionPattern);
return semanticVersioning.getNextVersion(highestSemanticVersion);
}

Expand Down Expand Up @@ -290,7 +290,7 @@ public GitChangelogApi withHandlebarsHelper(final String name, final Helper<?> h
* Custom issues are added to support any kind of issue management, perhaps something that is
* internal to your project. See {@link SettingsIssue}.
*/
public GitChangelogApi withCustomIssue(
public GitChangelogApi withCustomIssue( // NOPMD
final String name, final String pattern, final String link, final String title) {
this.settings.addCustomIssue(new SettingsIssue(name, pattern, link, title));
return this;
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/se/bjurr/gitchangelog/api/model/Commit.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
public class Commit implements Serializable {
private static final long serialVersionUID = 6622555148468372816L;

private final String authorEmailAddress;
private final String authorName;
private final String commitTime;
private final Long commitTimeLong;
private final String hash;
private final String hashFull;
private final Boolean merge;
private final String message;

private static List<String> notFirst(final List<String> stringList) {
return stringList.subList(1, stringList.size());
}
Expand Down Expand Up @@ -57,21 +66,12 @@ static List<String> toMessageItems(final String message) {

static String toMessageTitle(final String message) {
final List<String> stringList = toNoEmptyStringsList(message);
if (stringList.size() > 0) {
if (!stringList.isEmpty()) {
return stringList.get(0).trim();
}
return "";
}

private final String authorEmailAddress;
private final String authorName;
private final String commitTime;
private final Long commitTimeLong;
private final String hash;
private final String hashFull;
private final Boolean merge;
private final String message;

public Commit(
final String authorName,
final String authorEmailAddress,
Expand Down
5 changes: 1 addition & 4 deletions src/main/java/se/bjurr/gitchangelog/api/model/IssueType.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,6 @@ public boolean equals(final Object obj) {
} else if (!this.name.equals(other.name)) {
return false;
}
if (this.type != other.type) {
return false;
}
return true;
return this.type == other.type;
}
}
18 changes: 5 additions & 13 deletions src/main/java/se/bjurr/gitchangelog/internal/git/GitRepo.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.bjurr.gitchangelog.api.GitChangelogApiConstants;
import se.bjurr.gitchangelog.api.InclusivenessStrategy;
import se.bjurr.gitchangelog.api.exceptions.GitChangelogRepositoryException;
import se.bjurr.gitchangelog.internal.git.model.GitCommit;
Expand Down Expand Up @@ -126,7 +125,7 @@ public Optional<RevisionBoundary<ObjectId>> findObjectId(

/**
* @param from From, but not including, this commit. Except for the {@link
* GitChangelogApiConstants#ZERO_COMMIT}, it is included.
* se.bjurr.gitchangelog.api.GitChangelogApiConstants#ZERO_COMMIT}, it is included.
* @param to To and including this commit.
*/
public GitRepoData getGitRepoData(
Expand Down Expand Up @@ -239,22 +238,16 @@ private void addToTags(
}

private RevCommit firstCommit() {
Git git = null;
try {
git = new Git(this.repository);
final AnyObjectId master = this.getRef(HEAD);
final Iterator<RevCommit> itr = git.log().add(master).call().iterator();
try (Git git = new Git(this.repository)) {
final AnyObjectId head = this.getRef(HEAD);
final Iterator<RevCommit> itr = git.log().add(head).call().iterator();
RevCommit last = null;
while (itr.hasNext()) {
last = itr.next();
}
return last;
} catch (final Exception e) {
throw new RuntimeException("First commit not found in " + this.repository.getDirectory(), e);
} finally {
if (git != null) {
git.close();
}
}
}

Expand Down Expand Up @@ -585,7 +578,6 @@ private void populateCommitPerTag(
}
}
}
return;
}

private boolean shouldPrioritizeNewWork(
Expand Down Expand Up @@ -673,7 +665,7 @@ public List<String> getTags(
final RevisionBoundary<RevCommit> from = this.toRevCommit(fromObjectId);
final RevisionBoundary<RevCommit> to = this.toRevCommit(toObjectId);

final List<String> tags = new ArrayList<String>();
final List<String> tags = new ArrayList<>();
for (final Ref tagRef : this.tagsBetweenFromAndTo(from, to)) {
final String commitIdOfRef = this.getPeeled(tagRef).name();
if (commitIdOfRef.equals(to.getRevision().getName())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import se.bjurr.gitchangelog.internal.git.model.GitTag;
import se.bjurr.gitchangelog.internal.model.ParsedIssue;

public class GitRepoDataHelper {
public final class GitRepoDataHelper {
public static GitRepoData removeCommitsWithoutIssue(
final List<ParsedIssue> allParsedIssues, final GitRepoData gitRepoData) {
final Set<GitCommit> commitsWithIssues = new TreeSet<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
public class GitHubServiceFactory {
static Interceptor interceptor;
static Interceptor interceptor; // NOPMD

public static void setInterceptor(final Interceptor interceptor) {
GitHubServiceFactory.interceptor = interceptor;
Expand All @@ -27,7 +27,7 @@ public static synchronized GitHubService getGitHubService(
}
final File cacheDir = new File(".okhttpcache");
cacheDir.mkdir();
final Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);
final Cache cache = new Cache(cacheDir, 1024 * 1024 * 10); // NOPMD

final OkHttpClient.Builder builder =
new OkHttpClient.Builder().cache(cache).connectTimeout(10, SECONDS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ protected String getEndpoint(final String issue) {
}

public JiraClient withIssueAdditionalFields(final List<String> fields) {
final List<String> newFields = new ArrayList<String>(fields);
final List<String> newFields = new ArrayList<>(fields);
Collections.sort(newFields);
this.fields = Collections.unmodifiableList(newFields);
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,21 @@ public String getApi() {
}

protected String getEndpoint(final String issue) {
final String issueNo = getIssueNumber(issue);
final String endpoint = this.api + "/issues/" + issueNo + ".json";
return endpoint;
final String issueNo = this.getIssueNumber(issue);
return this.api + "/issues/" + issueNo + ".json";
}

protected RedmineIssue toRedmineIssue(final String issue, final String json) {
final String issueNo = getIssueNumber(issue);
final String issueNo = this.getIssueNumber(issue);
final String title = read(json, "$.issue.subject");
final String description = read(json, "$.issue.description");
final String type = read(json, "$.issue.tracker.name");
final String link = this.api + "/issues/" + issueNo;

final RedmineIssue redmineIssue = new RedmineIssue(title, description, link, issue, type);
return redmineIssue;
return new RedmineIssue(title, description, link, issue, type);
}

protected String getIssueNumber(String issue) {
protected String getIssueNumber(final String issue) {
return issue.startsWith("#") ? issue.substring(1) : issue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,21 @@ protected HttpURLConnection openConnection(final URL url) throws Exception {

protected String getResponse(final HttpURLConnection conn) throws Exception {
if (mockedRestClient == null) {
final InputStream inputStream = conn.getInputStream();
final InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, StandardCharsets.UTF_8);
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
return bufferedReader.readLine();
try (final InputStream inputStream = conn.getInputStream()) {
try (final InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
final StringBuilder sb = new StringBuilder();
while (true) {
final String nextline = bufferedReader.readLine();
if (nextline == null) {
break;
}
sb.append(nextline);
}
return sb.toString();
}
}
}
}
return mockedRestClient.getResponse(conn);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public List<ParsedIssue> parseForIssues(final boolean useIntegrations) {
continue;
}
if (!parsedIssuePerIssue.containsKey(matchedIssue)) {
ParsedIssue parsedIssue = null;
ParsedIssue parsedIssue;
if (issuePattern.getType() == GITHUB) {
parsedIssue = this.createParsedIssue(gitHubHelper, issuePattern, matchedIssue);
} else if (issuePattern.getType() == GITLAB) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ private List<ParsedIssue> filterWithCommits(final List<ParsedIssue> issues) {
}

private String format(final Date commitTime) {
final SimpleDateFormat df = new SimpleDateFormat(this.settings.getDateFormat());
final SimpleDateFormat df = new SimpleDateFormat(this.settings.getDateFormat(), Locale.ENGLISH);
df.setTimeZone(getTimeZone(this.settings.getTimeZone()));
return df.format(commitTime);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,18 @@ public class SemanticVersion implements Serializable {
private final int minor;
private final int major;
private String tag;
private VERSION_STEP versionStep;
private final VERSION_STEP versionStep;

public SemanticVersion(final int major, final int minor, final int patch) {
public SemanticVersion(
final int major, final int minor, final int patch, final VERSION_STEP versionStep) {
this.major = major;
this.minor = minor;
this.patch = patch;
this.versionStep = VERSION_STEP.NONE;
this.versionStep = versionStep;
}

public SemanticVersion(
final int major, final int minor, final int patch, final VERSION_STEP versionStep) {
this(major, minor, patch);
this.versionStep = versionStep;
public SemanticVersion(final int major, final int minor, final int patch) {
this(major, minor, patch, VERSION_STEP.NONE);
}

public int getMajor() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public enum VERSION_STEP {
private final Pattern patchPattern;

public SemanticVersioning(
final List<String> tags,
final List<String> commits,
final String majorPattern,
final String minorPattern,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,10 @@ public class Settings implements Serializable {
private String gitLabProjectName;

/** Regular expression to use when determining next semantic version based on commits. */
private String semanticMajorPattern = null;
private String semanticMajorPattern;

/** Regular expression to use when determining next semantic version based on commits. */
private String semanticMinorPattern = null;
private String semanticMinorPattern;

/** Regular expression to use when determining next semantic version based on commits. */
private String semanticPatchPattern;
Expand Down Expand Up @@ -645,7 +645,7 @@ private String isRegexp(final String pattern, final String string) {
try {
Pattern.compile(pattern);
} catch (final PatternSyntaxException e) {
throw new RuntimeException(pattern + " in " + string + " is not valid regexp.");
throw new RuntimeException(pattern + " in " + string + " is not valid regexp.", e);
}
return pattern;
}
Expand Down

0 comments on commit cf0bfeb

Please sign in to comment.