Skip to content
This repository has been archived by the owner on Aug 10, 2022. It is now read-only.

Commit

Permalink
Merge pull request #89 from blindpirate/0.4.9
Browse files Browse the repository at this point in the history
0.4.9
  • Loading branch information
blindpirate committed May 4, 2017
2 parents 0d1ec86 + 4ec65d5 commit 2aa743d
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ dependencies {
build('goLock', 'installBuildDependencies')
assertLockIsVcs()

build('goLock', 'installBuildDependencies')
build('installBuildDependencies')

deleteDependencyTreeCache()
build('goLock', 'installBuildDependencies')
build('installBuildDependencies')
assert new File(resource, '.gogradle/build_gopath/src/github.com/my/dependency1/commit1.go').exists()
assert stdout.toString().contains('Resolving cached')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public class DefaultGoBinaryManager implements GoBinaryManager {
// go version go1.7.1 darwin/amd64
private static final Pattern GO_VERSION_OUTPUT_REGEX = Pattern.compile("go version go((\\d|\\.)+) .+");

private static final String IGNORE_LOCAL = "IGNORE_LOCAL";

private static Map<Boolean, String> urls = ImmutableMap.of(
TRUE, URL_UNDER_GFW,
FALSE, URL);
Expand Down Expand Up @@ -114,15 +116,10 @@ private void resolveIfNecessary() {
}

private void determineGoBinaryAndVersion() {
if (goExecutableIsSpecified()) {
Optional<Pair<Path, String>> pathAndVersion = tryGivenGoExecutable();
Assert.isTrue(pathAndVersion.isPresent(), "Cannot execute given go binary: " + setting.getGoExecutable());
Assert.isTrue(versionMatch(pathAndVersion.get().getRight()),
"Version not match: required is " + setting.getGoVersion()
+ ", given is " + pathAndVersion.get().getRight());
useGoExecutableOnHost(pathAndVersion.get().getLeft(), pathAndVersion.get().getRight());
} else {
Optional<Pair<Path, String>> binPathAndVersionOnHost = findGoBinAndVersionInPATH();
if (IGNORE_LOCAL.equals(setting.getGoExecutable())) {
fetchGoDistribution();
} else if ("go".equals(setting.getGoExecutable())) {
Optional<Pair<Path, String>> binPathAndVersionOnHost = findGoBinAndVersionHost();
if (binPathAndVersionOnHost.isPresent()) {
Path goBinPath = binPathAndVersionOnHost.get().getLeft();
String version = binPathAndVersionOnHost.get().getRight();
Expand All @@ -132,21 +129,28 @@ private void determineGoBinaryAndVersion() {
fetchSpecifiedVersion(setting.getGoVersion());
}
} else {
if (setting.getGoVersion() == null) {
fetchNewestStableVersion();
} else {
fetchSpecifiedVersion(setting.getGoVersion());
}
fetchGoDistribution();
}
} else {
Optional<Pair<Path, String>> pathAndVersion = tryGivenGoExecutable();
Assert.isTrue(pathAndVersion.isPresent(), "Cannot execute given go binary: " + setting.getGoExecutable());
Assert.isTrue(versionMatch(pathAndVersion.get().getRight()),
"Version not match: required is " + setting.getGoVersion()
+ ", given is " + pathAndVersion.get().getRight());
useGoExecutableOnHost(pathAndVersion.get().getLeft(), pathAndVersion.get().getRight());
}
}

private boolean versionMatch(String actualVersion) {
return setting.getGoVersion() == null || setting.getGoVersion().equals(actualVersion);
private void fetchGoDistribution() {
if (setting.getGoVersion() == null) {
fetchNewestStableVersion();
} else {
fetchSpecifiedVersion(setting.getGoVersion());
}
}

private boolean goExecutableIsSpecified() {
return !"go".equals(setting.getGoExecutable());
private boolean versionMatch(String actualVersion) {
return setting.getGoVersion() == null || setting.getGoVersion().equals(actualVersion);
}

private void useGoExecutableOnHost(Path goBinPathOnHost, String versionOnHost) {
Expand All @@ -173,7 +177,7 @@ private Optional<Pair<Path, String>> tryGivenGoExecutable() {
}

@SuppressWarnings({"checkstyle:localvariablename"})
private Optional<Pair<Path, String>> findGoBinAndVersionInPATH() {
private Optional<Pair<Path, String>> findGoBinAndVersionHost() {
String PATH = System.getenv("PATH");
String[] paths = StringUtils.splitAndTrim(PATH, File.pathSeparator);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@
import com.github.blindpirate.gogradle.core.BuildConstraintManager;
import com.github.blindpirate.gogradle.core.dependency.GogradleRootProject;
import com.github.blindpirate.gogradle.crossplatform.GoBinaryManager;
import com.github.blindpirate.gogradle.util.IOUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.TaskAction;

import javax.inject.Inject;
import java.io.File;
import java.util.List;

/**
* This task perform preparation such as Go executable and GOPATH.
*/
public class PrepareTask extends DefaultTask {

private static final Logger LOGGER = Logging.getLogger(PrepareTask.class);
@Inject
private GoBinaryManager goBinaryManager;

Expand All @@ -38,6 +44,21 @@ public void prepare() {
buildManager.prepareSymbolicLinks();
buildConstraintManager.prepareConstraints();
gogradleRootProject.initSingleton(setting.getPackagePath(), getProject().getRootDir());
deleteGogradleDotLockIfLockTaskExists();
}

private void deleteGogradleDotLockIfLockTaskExists() {
File gogradleDotLock = new File(getProject().getRootDir(), "gogradle.lock");
if (goLockExistsInCurrentTasks() && gogradleDotLock.exists()) {
LOGGER.warn("gogradle.lock already exists, it will be removed now.");
IOUtils.forceDelete(gogradleDotLock);
}
}

private boolean goLockExistsInCurrentTasks() {
List<String> taskNames = getProject().getGradle().getStartParameter().getTaskNames();
return taskNames.contains(GolangTaskContainer.LOCK_TASK_NAME)
|| taskNames.contains("gL");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,8 @@ private List<GoTestMethodResult> extractTestMethodResult(List<String> stdout) {

private Optional<GoTestMethodResult> extractOneTestMethod(List<String> middleLines) {
OptionalInt testResultLineIndex = IntStream.range(0, middleLines.size())
.filter(index -> middleLines.get(index).startsWith(TEST_FAIL)
|| middleLines.get(index).startsWith(TEST_PASS))
.filter(index -> middleLines.get(index).contains(TEST_FAIL)
|| middleLines.get(index).contains(TEST_PASS))
.findAny();
if (testResultLineIndex.isPresent()) {
String line = middleLines.get(testResultLineIndex.getAsInt());
Expand All @@ -163,8 +163,7 @@ private Optional<GoTestMethodResult> extractOneTestMethod(List<String> middleLin
long duration = toMilliseconds(parseDouble(matcher.group(3)));

String message = IntStream.range(1, middleLines.size())
.filter(i -> i != testResultLineIndex.getAsInt())
.mapToObj(middleLines::get)
.mapToObj(i -> mapToResultLine(i, middleLines, testResultLineIndex.getAsInt()))
.collect(Collectors.joining("\n"));

GoTestMethodResult result = new GoTestMethodResult(id,
Expand All @@ -182,6 +181,21 @@ private Optional<GoTestMethodResult> extractOneTestMethod(List<String> middleLin
return Optional.empty();
}

private String mapToResultLine(int index, List<String> lines, int testResultLineIndex) {
String line = lines.get(index);
if (index == testResultLineIndex) {
int testFailIndex = line.indexOf(TEST_FAIL);
int testPassIndex = line.indexOf(TEST_PASS);
if (testFailIndex > 0 || testPassIndex > 0) {
// they seemed to omit a new line
return line.substring(0, testFailIndex > 0 ? testFailIndex : testPassIndex);
} else {
return "";
}
}
return lines.get(index);
}

private Map<File, String> loadTestFiles(List<File> testFiles) {
return testFiles.
stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,15 @@ class DefaultGoBinaryManagerTest {
manager.getGoVersion()
}

@Test
void 'local go binary should be ignored if IGNORE_LOCAL is specified'() {
// given
turnOnMockGo()
when(setting.getGoExecutable()).thenReturn('IGNORE_LOCAL')
// then
'the newest stable version will be used if local binary not exist and no version specified'()
}

@Test
void 'local go binary should be ignored if it cannot be recognized'() {
// given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ package com.github.blindpirate.gogradle.task

import com.github.blindpirate.gogradle.GogradleRunner
import com.github.blindpirate.gogradle.support.WithResource
import com.github.blindpirate.gogradle.util.IOUtils
import org.gradle.api.Task
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.tasks.TaskContainerInternal
import org.gradle.api.invocation.Gradle
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Answers
import org.mockito.Mock

import static org.mockito.Mockito.verify
import static org.mockito.Mockito.when
import static org.mockito.Mockito.*

@RunWith(GogradleRunner)
@WithResource('')
Expand All @@ -17,11 +23,15 @@ class PrepareTaskTest extends TaskTest {

File resource

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
GradleInternal gradle

@Before
void setUp() {
task = buildTask(PrepareTask)
when(project.getRootDir()).thenReturn(resource)
when(setting.getPackagePath()).thenReturn('github.com/my/project')
when(project.getGradle()).thenReturn(gradle)
}

@Test
Expand All @@ -37,4 +47,31 @@ class PrepareTaskTest extends TaskTest {
verify(gogradleRootProject).initSingleton('github.com/my/project', resource)
}

@Test
void 'old gogradle.lock should be removed before locking'() {
// given
IOUtils.write(resource, 'gogradle.lock', '')
when(gradle.getStartParameter().getTaskNames()).thenReturn(["goLock"])
// when
task.prepare()
// then
assert !new File(resource, 'gogradle.lock').exists()

// given
IOUtils.write(resource, 'gogradle.lock', '')
when(gradle.getStartParameter().getTaskNames()).thenReturn(["gL"])
// when
task.prepare()
// then
assert !new File(resource, 'gogradle.lock').exists()

// given
IOUtils.write(resource, 'gogradle.lock', '')
when(gradle.getStartParameter().getTaskNames()).thenReturn(["gD"])
// when
task.prepare()
// then
assert new File(resource, 'gogradle.lock').exists()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ FAIL\ta\t0.006s'''
--- FAIL: Test_A1 (0.00s)
\ta1_test.go:9: Failed
=== RUN Test_A2
--- PASS: Test_A2 (0.00s)
SomeOutputWithoutNewline--- PASS: Test_A2 (0.00s)
\ta1_test.go:15: Passed
=== RUN Test_A3
--- PASS: Test_A3 (0.00s)
Expand Down Expand Up @@ -82,13 +82,12 @@ FAIL\tgithub.com/my/project/a\t0.006s'''
assert result.results[0].resultType == TestResult.ResultType.FAILURE

assert result.results[1].name == 'Test_A2'
assert result.results[1].message.trim() == 'a1_test.go:15: Passed'
assert result.results[1].message.trim() == 'SomeOutputWithoutNewline\n\ta1_test.go:15: Passed'
assert result.results[1].resultType == TestResult.ResultType.SUCCESS

assert result.results[2].name == 'Test_A3'
assert result.results[2].message.trim() == 'a2_test.go:7: Passed'
assert result.results[2].resultType == TestResult.ResultType.SUCCESS

}

@Test
Expand Down

0 comments on commit 2aa743d

Please sign in to comment.