Skip to content

Commit 6f1e908

Browse files
committed
slight updates after merging jenkins GIT_BRANCH code
1 parent af597fe commit 6f1e908

File tree

6 files changed

+107
-80
lines changed

6 files changed

+107
-80
lines changed

src/main/java/pl/project13/maven/git/GitCommitIdMojo.java

Lines changed: 54 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import com.google.common.annotations.VisibleForTesting;
2121
import com.google.common.io.Closeables;
2222
import com.google.common.io.Files;
23-
2423
import org.apache.maven.plugin.AbstractMojo;
2524
import org.apache.maven.plugin.MojoExecutionException;
2625
import org.apache.maven.project.MavenProject;
@@ -31,7 +30,6 @@
3130
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
3231
import org.jetbrains.annotations.NotNull;
3332
import org.jetbrains.annotations.Nullable;
34-
3533
import pl.project13.jgit.DescribeCommand;
3634
import pl.project13.jgit.DescribeResult;
3735
import pl.project13.maven.git.log.LoggerBridge;
@@ -46,6 +44,8 @@
4644
import java.util.Map;
4745
import java.util.Properties;
4846

47+
import static com.google.common.base.Strings.isNullOrEmpty;
48+
4949
/**
5050
* Goal which puts git build-time information into property files or maven's properties.
5151
*
@@ -141,7 +141,7 @@ public class GitCommitIdMojo extends AbstractMojo {
141141
* into generateFile mode.
142142
* <p/>
143143
* The path here is relative to your projects src directory.
144-
*
144+
*
145145
* @parameter default-value="${project.build.outputDirectory}/git.properties"
146146
*/
147147
@SuppressWarnings("UnusedDeclaration")
@@ -255,7 +255,7 @@ public void execute() throws MojoExecutionException {
255255
if (dotGitDirectory != null) {
256256
log("dotGitDirectory", dotGitDirectory.getAbsolutePath());
257257
} else {
258-
log("dotGitDirectory is null");
258+
log("dotGitDirectory is null, aborting execution!");
259259
return;
260260
}
261261

@@ -268,7 +268,7 @@ public void execute() throws MojoExecutionException {
268268
logProperties(properties);
269269

270270
if (generateGitPropertiesFile) {
271-
generatePropertiesFile(properties, generateGitPropertiesFilename);
271+
generatePropertiesFile(properties, project.getBasedir(), generateGitPropertiesFilename);
272272
}
273273

274274
if (injectAllReactorProjects) {
@@ -278,7 +278,6 @@ public void execute() throws MojoExecutionException {
278278
handlePluginFailure(e);
279279
}
280280

281-
log();
282281
}
283282

284283
/**
@@ -292,13 +291,11 @@ private void handlePluginFailure(Exception e) throws MojoExecutionException {
292291
if (failOnUnableToExtractRepoInfo) {
293292
throw new MojoExecutionException("Could not complete Mojo execution...", e);
294293
} else {
295-
loggerBridge.error();
294+
loggerBridge.error(e.getMessage());
296295
}
297296
}
298297

299298
private void appendPropertiesToReactorProjects(@NotNull Properties properties) {
300-
log();
301-
302299
for (MavenProject mavenProject : reactorProjects) {
303300
Properties mavenProperties = mavenProject.getProperties();
304301

@@ -327,12 +324,9 @@ private File lookupGitDirectory() throws MojoExecutionException {
327324
}
328325

329326
private Properties initProperties() throws MojoExecutionException {
330-
log();
331327
if (generateGitPropertiesFile) {
332-
log();
333328
return properties = new Properties();
334329
} else if (!runningTests) {
335-
log();
336330
return properties = project.getProperties();
337331
} else {
338332
return properties = new Properties(); // that's ok for unit tests
@@ -359,7 +353,6 @@ void loadBuildTimeData(@NotNull Properties properties) {
359353
}
360354

361355
void loadGitData(@NotNull Properties properties) throws IOException, MojoExecutionException {
362-
log();
363356
Repository git = getGitRepository();
364357
ObjectReader objectReader = git.newObjectReader();
365358

@@ -382,7 +375,7 @@ void loadGitData(@NotNull Properties properties) throws IOException, MojoExecuti
382375

383376
try {
384377
// git.branch
385-
String branch = determineBranchName(git);
378+
String branch = determineBranchName(git, System.getenv());
386379
put(properties, BRANCH, branch);
387380

388381
// git.commit.id.describe
@@ -424,7 +417,7 @@ void loadGitData(@NotNull Properties properties) throws IOException, MojoExecuti
424417
}
425418

426419
private void putAbbrevCommitId(ObjectReader objectReader, Properties properties, RevCommit headCommit, int abbrevLength) throws MojoExecutionException {
427-
if(abbrevLength < 2 || abbrevLength > 40) {
420+
if (abbrevLength < 2 || abbrevLength > 40) {
428421
throw new MojoExecutionException("Abbreviated commit id lenght must be between 2 and 40, inclusive! Was [%s]. ".codePointBefore(abbrevLength) +
429422
"Please fix your configuration (the <abbrevLength/> element).");
430423
}
@@ -460,14 +453,19 @@ void putGitDescribe(@NotNull Properties properties, @NotNull Repository reposito
460453
}
461454
}
462455

463-
void generatePropertiesFile(@NotNull Properties properties, String generateGitPropertiesFilename) throws IOException {
456+
static int counter;
457+
458+
void generatePropertiesFile(@NotNull Properties properties, File base, String propertiesFilename) throws IOException {
464459
FileWriter fileWriter = null;
465-
File gitPropsFile = new File(generateGitPropertiesFilename);
460+
File gitPropsFile = new File(base, propertiesFilename);
466461
try {
467462
Files.createParentDirs(gitPropsFile);
468463

469464
fileWriter = new FileWriter(gitPropsFile);
470465
properties.store(fileWriter, "Generated by Git-Commit-Id-Plugin");
466+
467+
log("Writing properties file to [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName() + (++counter), ")...");
468+
471469
} catch (IOException ex) {
472470
throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
473471
} finally {
@@ -518,8 +516,8 @@ private boolean isNotEmpty(@Nullable String value) {
518516
return null != value && !" ".equals(value.trim().replaceAll(" ", ""));
519517
}
520518

521-
void log(String... interpolations) {
522-
loggerBridge.log((Object[]) interpolations);
519+
void log(String... parts) {
520+
loggerBridge.log((Object[]) parts);
523521
}
524522

525523
private boolean directoryExists(@Nullable File fileLocation) {
@@ -529,30 +527,49 @@ private boolean directoryExists(@Nullable File fileLocation) {
529527
private boolean directoryDoesNotExits(File fileLocation) {
530528
return !directoryExists(fileLocation);
531529
}
532-
530+
533531
/**
534532
* If running within Jenkins/Hudosn, honor the branch name passed via GIT_BRANCH env var. This
535533
* is necessary because Jenkins/Hudson alwways invoke build in a detached head state.
536-
*
534+
*
537535
* @param git
536+
* @param env
538537
* @return results of git.getBranch() or, if in Jenkins/Hudson, value of GIT_BRANCH
539538
*/
540-
protected String determineBranchName(Repository git) throws IOException {
541-
Map<String,String> env = System.getenv();
542-
return determineBranchName(git,env);
543-
}
544-
545-
protected String determineBranchName(Repository git, Map<String,String> env) throws IOException {
546-
String branch = git.getBranch();
547-
548-
// Special processing if we're in Jenkins/Hudson
549-
if (env.containsKey("HUDSON_URL") || env.containsKey("JENKINS_URL")) {
550-
String branchName = env.get("GIT_BRANCH");
551-
if (branchName!=null && branchName.length()>0) {
552-
branch=branchName;
553-
}
554-
}
555-
return branch;
539+
protected String determineBranchName(Repository git, Map<String, String> env) throws IOException {
540+
if (runningOnBuildServer(env)) {
541+
return determineBranchNameOnBuildServer(git, env);
542+
} else {
543+
return git.getBranch();
544+
}
545+
}
546+
547+
/**
548+
* Is "Jenkins aware", and prefers {@code GIT_BRANCH} to getting the branch via git if that enviroment variable is set.
549+
* The {@GIT_BRANCH} variable is set by Jenkins/Hudson when put in detached HEAD state, but it still knows which branch was cloned.
550+
*/
551+
protected String determineBranchNameOnBuildServer(Repository git, Map<String, String> env) throws IOException {
552+
String enviromentBasedBranch = env.get("GIT_BRANCH");
553+
if(isNullOrEmpty(enviromentBasedBranch)) {
554+
log("Detected that running on CI enviroment, but using repository branch, no GIT_BRANCH detected.");
555+
return git.getBranch();
556+
}else {
557+
log("Using enviroment variable based branch name.", "GIT_BRANCH =", enviromentBasedBranch);
558+
return enviromentBasedBranch;
559+
}
560+
}
561+
562+
/**
563+
* Detects if we're running on Jenkins or Hudson, based on expected env variables.
564+
* <p/>
565+
* TODO: How can we detect Bamboo, TeamCity etc? Pull requests welcome.
566+
*
567+
* @return true if running
568+
* @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-JenkinsSetEnvironmentVariables">JenkinsSetEnvironmentVariables</a>
569+
* @param env
570+
*/
571+
private boolean runningOnBuildServer(Map<String, String> env) {
572+
return env.containsKey("HUDSON_URL") || env.containsKey("JENKINS_URL");
556573
}
557574

558575
// SETTERS FOR TESTS ----------------------------------------------------

src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ public class FileSystemMavenSandbox {
4646
* Test should copy content of this folder to ".git" in correct destination
4747
*/
4848
private File gitRepoSourceDir;
49+
4950
@Nullable
5051
private File gitRepoTargetDir;
5152

@@ -153,6 +154,8 @@ public MavenProject getChildProject() {
153154
return childProject;
154155
}
155156

157+
public File getSandboxDir() { return gitRepoTargetDir.getAbsoluteFile(); }
158+
156159
@NotNull
157160
private MavenProject createProject(File basedir, String packaging) {
158161
MavenProject project = new MavenProject();
@@ -166,5 +169,12 @@ public static enum CleanUp {
166169
NO_CLEANUP
167170
}
168171

169-
172+
@Override
173+
public String toString() {
174+
return "FileSystemMavenSandbox{" +
175+
"gitRepoTargetDir=" + gitRepoTargetDir +
176+
", gitRepoSourceDir=" + gitRepoSourceDir +
177+
", rootSandboxPath='" + rootSandboxPath + '\'' +
178+
'}';
179+
}
170180
}

src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import org.apache.maven.plugin.MojoExecutionException;
2121
import org.apache.maven.project.MavenProject;
2222
import org.fest.util.Files;
23-
import org.jetbrains.annotations.NotNull;
2423
import org.junit.Test;
2524
import pl.project13.maven.git.FileSystemMavenSandbox.CleanUp;
2625
import pl.project13.test.utils.AssertException;
@@ -160,11 +159,6 @@ private void alterMojoSettings(String parameterName, Object parameterValue) {
160159
setInternalState(mojo, parameterName, parameterValue);
161160
}
162161

163-
private void setProjectToExecuteMojoIn(@NotNull MavenProject project) {
164-
setInternalState(mojo, "project", project);
165-
setInternalState(mojo, "dotGitDirectory", new File(project.getBasedir(), ".git"));
166-
}
167-
168162
private void assertGitPropertiesPresentInProject(Properties properties) {
169163
assertThat(properties).satisfies(new ContainsKeyCondition("git.build.time"));
170164
assertThat(properties).satisfies(new ContainsKeyCondition("git.branch"));

src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,19 @@
1717

1818
package pl.project13.maven.git;
1919

20+
import com.google.common.collect.Maps;
2021
import org.apache.maven.project.MavenProject;
2122
import org.eclipse.jgit.lib.Repository;
2223
import org.junit.Before;
2324
import org.junit.Test;
2425

25-
import com.google.common.collect.Maps;
26-
2726
import java.io.File;
2827
import java.io.IOException;
2928
import java.util.Map;
3029
import java.util.Properties;
3130

3231
import static org.fest.assertions.Assertions.assertThat;
3332
import static org.mockito.Mockito.*;
34-
import static org.junit.Assert.assertEquals;
3533

3634
/**
3735
* I'm not a big fan of this test - let's move to integration test from now on.
@@ -97,37 +95,38 @@ public void shouldSkipDescribeWhenConfiguredToDoSo() throws Exception {
9795

9896
@Test
9997
public void shouldUseJenkinsBranchInfoWhenAvailable() throws IOException {
100-
Repository git = mock(Repository.class);
101-
Map<String,String> env = Maps.newHashMap();
102-
103-
String detachedHeadSHA1 = "16bb801934e652f5e291a003db05e364d83fba25";
104-
String ciUrl = "http://myciserver.com";
105-
106-
when(git.getBranch()).thenReturn(detachedHeadSHA1);
107-
108-
// In a detached head state, getBranch() will return the SHA1...standard behavior
109-
assertEquals(detachedHeadSHA1, mojo.determineBranchName(git, env));
110-
111-
// Again, SHA1 will be returned if we're in jenkins, but GIT_BRANCH is not set
112-
env.put("JENKINS_URL", "http://myjenkinsserver.com");
113-
assertEquals(detachedHeadSHA1, mojo.determineBranchName(git, env));
114-
115-
// Now set GIT_BRANCH too and see that the branch name from env var is returned
116-
env.clear();
117-
env.put("JENKINS_URL", ciUrl);
118-
env.put("GIT_BRANCH", "mybranch");
119-
assertEquals("mybranch", mojo.determineBranchName(git, env));
120-
121-
122-
// Same, but for hudson
123-
env.clear();
124-
env.put("GIT_BRANCH", "mybranch");
125-
env.put("HUDSON_URL", ciUrl);
126-
assertEquals("mybranch", mojo.determineBranchName(git, env));
127-
128-
// GIT_BRANCH but no HUDSON_URL or JENKINS_URL
129-
env.clear();
130-
env.put("GIT_BRANCH", "mybranch");
131-
assertEquals(detachedHeadSHA1, mojo.determineBranchName(git, env));
98+
// given
99+
Repository git = mock(Repository.class);
100+
Map<String, String> env = Maps.newHashMap();
101+
102+
String detachedHeadSHA1 = "16bb801934e652f5e291a003db05e364d83fba25";
103+
String ciUrl = "http://myciserver.com";
104+
105+
when(git.getBranch()).thenReturn(detachedHeadSHA1);
106+
107+
// when
108+
// in a detached head state, getBranch() will return the SHA1...standard behavior
109+
assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env));
110+
111+
// again, SHA1 will be returned if we're in jenkins, but GIT_BRANCH is not set
112+
env.put("JENKINS_URL", "http://myjenkinsserver.com");
113+
assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env));
114+
115+
// now set GIT_BRANCH too and see that the branch name from env var is returned
116+
env.clear();
117+
env.put("JENKINS_URL", ciUrl);
118+
env.put("GIT_BRANCH", "mybranch");
119+
assertThat("mybranch").isEqualTo(mojo.determineBranchName(git, env));
120+
121+
// same, but for hudson
122+
env.clear();
123+
env.put("GIT_BRANCH", "mybranch");
124+
env.put("HUDSON_URL", ciUrl);
125+
assertThat("mybranch").isEqualTo(mojo.determineBranchName(git, env));
126+
127+
// GIT_BRANCH but no HUDSON_URL or JENKINS_URL
128+
env.clear();
129+
env.put("GIT_BRANCH", "mybranch");
130+
assertThat(detachedHeadSHA1).isEqualTo(mojo.determineBranchName(git, env));
132131
}
133132
}

src/test/java/pl/project13/maven/git/GitIntegrationTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package pl.project13.maven.git;
1919

2020
import com.google.common.base.Optional;
21+
import org.apache.maven.project.MavenProject;
2122
import org.eclipse.jgit.api.Git;
2223
import org.jetbrains.annotations.NotNull;
2324
import org.junit.Before;
@@ -74,4 +75,10 @@ public static void initializeMojoWithDefaults(GitCommitIdMojo mojo) {
7475
setInternalState(mojo, entry.getKey(), entry.getValue());
7576
}
7677
}
78+
79+
public void setProjectToExecuteMojoIn(@NotNull MavenProject project) {
80+
setInternalState(mojo, "project", project);
81+
setInternalState(mojo, "dotGitDirectory", new File(project.getBasedir(), ".git"));
82+
}
83+
7784
}

src/test/java/pl/project13/maven/git/GitSubmodulesTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject() throws Ex
6565
assertGitPropertiesPresentInProject(targetProject.getProperties());
6666
}
6767

68-
private void setProjectToExecuteMojoIn(@NotNull MavenProject project) {
68+
public void setProjectToExecuteMojoIn(@NotNull MavenProject project) {
6969
setInternalState(mojo, "project", project);
7070
setInternalState(mojo, "dotGitDirectory", new File(project.getBasedir(), ".git"));
7171
}

0 commit comments

Comments
 (0)