Search in sources :

Example 1 with GitLogEntry

use of com.google.copybara.git.GitRepository.GitLogEntry in project copybara by google.

the class GitHubPrOrigin method newReader.

@Override
public Reader<GitRevision> newReader(Glob originFiles, Authoring authoring) throws ValidationException {
    return new ReaderImpl(url, originFiles, authoring, gitOptions, gitOriginOptions, generalOptions, /*includeBranchCommitLogs=*/
    false, submoduleStrategy, firstParent, partialFetch, patchTransformation, describeVersion, /*configPath=*/
    null, /*workflowName=*/
    null) {

        /**
         * Disable rebase since this is controlled by useMerge field.
         */
        @Override
        protected void maybeRebase(GitRepository repo, GitRevision ref, Path workdir) throws RepoException, CannotResolveRevisionException {
        }

        @Override
        public Optional<Baseline<GitRevision>> findBaseline(GitRevision startRevision, String label) throws RepoException, ValidationException {
            if (!baselineFromBranch) {
                return super.findBaseline(startRevision, label);
            }
            return findBaselinesWithoutLabel(startRevision, /*limit=*/
            1).stream().map(e -> new Baseline<>(e.getSha1(), e)).findFirst();
        }

        @Override
        public ImmutableList<GitRevision> findBaselinesWithoutLabel(GitRevision startRevision, int limit) throws RepoException, ValidationException {
            String baseline = Iterables.getLast(startRevision.associatedLabels().get(GITHUB_BASE_BRANCH_SHA1), null);
            checkNotNull(baseline, "%s label should be present in %s", GITHUB_BASE_BRANCH_SHA1, startRevision);
            GitRevision baselineRev = getRepository().resolveReference(baseline);
            // Don't skip the first change as it is already the baseline
            BaselinesWithoutLabelVisitor<GitRevision> visitor = new BaselinesWithoutLabelVisitor<>(originFiles, limit, /*skipFirst=*/
            false);
            visitChanges(baselineRev, visitor);
            return visitor.getResult();
        }

        @Override
        public Endpoint getFeedbackEndPoint(Console console) throws ValidationException {
            gitHubOptions.validateEndpointChecker(endpointChecker);
            return new GitHubEndPoint(gitHubOptions.newGitHubApiSupplier(url, endpointChecker, ghHost), url, console, ghHost);
        }

        /**
         * Deal with the case of useMerge. We have a new commit (the merge) and first-parent from that
         * commit doesn't work for this case.
         */
        @Override
        public ChangesResponse<GitRevision> changes(@Nullable GitRevision fromRef, GitRevision toRef) throws RepoException, ValidationException {
            checkCondition(toRef.associatedLabels().containsKey(GITHUB_PR_USE_MERGE), "Cannot determine whether 'use_merge' was set.");
            if (toRef.associatedLabel(GITHUB_PR_USE_MERGE).contains("false")) {
                return super.changes(fromRef, toRef);
            }
            GitLogEntry merge = Iterables.getOnlyElement(getRepository().log(toRef.getSha1()).withLimit(1).run());
            // Fast-forward merge
            if (merge.getParents().size() == 1) {
                return super.changes(fromRef, toRef);
            }
            // HEAD of the Pull Request
            GitRevision gitRevision = merge.getParents().get(1);
            ChangesResponse<GitRevision> prChanges = super.changes(fromRef, gitRevision);
            // origin_files
            if (prChanges.isEmpty()) {
                return prChanges;
            }
            try {
                return ChangesResponse.forChanges(ImmutableList.<Change<GitRevision>>builder().addAll(prChanges.getChanges()).add(change(merge.getCommit())).build());
            } catch (EmptyChangeException e) {
                throw new RepoException("Error getting the merge commit information: " + merge, e);
            }
        }
    };
}
Also used : Path(java.nio.file.Path) GitHubUtil.asHeadRef(com.google.copybara.git.github.util.GitHubUtil.asHeadRef) Origin(com.google.copybara.Origin) CombinedStatus(com.google.copybara.git.github.api.CombinedStatus) Collections2(com.google.common.collect.Collections2) Review(com.google.copybara.git.github.api.Review) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) Matcher(java.util.regex.Matcher) Change(com.google.copybara.Change) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) Endpoint(com.google.copybara.Endpoint) Splitter(com.google.common.base.Splitter) GeneralOptions(com.google.copybara.GeneralOptions) Path(java.nio.file.Path) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) User(com.google.copybara.git.github.api.User) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) List(java.util.List) GitHubApi(com.google.copybara.git.github.api.GitHubApi) PullRequest(com.google.copybara.git.github.api.PullRequest) GitHubUtil.asMergeRef(com.google.copybara.git.github.util.GitHubUtil.asMergeRef) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) AutoValue(com.google.auto.value.AutoValue) Optional(java.util.Optional) Joiner(com.google.common.base.Joiner) AuthorAssociation(com.google.copybara.git.github.api.AuthorAssociation) Iterables(com.google.common.collect.Iterables) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ValidationException.checkCondition(com.google.copybara.exception.ValidationException.checkCondition) RepoException(com.google.copybara.exception.RepoException) SubmoduleStrategy(com.google.copybara.git.GitOrigin.SubmoduleStrategy) HashSet(java.util.HashSet) GitHubUtil(com.google.copybara.git.github.util.GitHubUtil) Label(com.google.copybara.git.github.api.Label) State(com.google.copybara.git.github.api.Status.State) ImmutableList(com.google.common.collect.ImmutableList) Issue(com.google.copybara.git.github.api.Issue) Nullable(javax.annotation.Nullable) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) CharMatcher(com.google.common.base.CharMatcher) ValidationException(com.google.copybara.exception.ValidationException) ReaderImpl(com.google.copybara.git.GitOrigin.ReaderImpl) PatchTransformation(com.google.copybara.transform.patch.PatchTransformation) Console(com.google.copybara.util.console.Console) TimeUnit(java.util.concurrent.TimeUnit) Authoring(com.google.copybara.authoring.Authoring) Checker(com.google.copybara.checks.Checker) Glob(com.google.copybara.util.Glob) CheckRun(com.google.copybara.git.github.api.CheckRun) Preconditions(com.google.common.base.Preconditions) Status(com.google.copybara.git.github.api.Status) GitHubHost(com.google.copybara.git.github.util.GitHubHost) GitHubPrUrl(com.google.copybara.git.github.util.GitHubHost.GitHubPrUrl) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ReaderImpl(com.google.copybara.git.GitOrigin.ReaderImpl) Change(com.google.copybara.Change) RepoException(com.google.copybara.exception.RepoException) Console(com.google.copybara.util.console.Console) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Nullable(javax.annotation.Nullable) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry)

Example 2 with GitLogEntry

use of com.google.copybara.git.GitRepository.GitLogEntry in project copybara by google.

the class WorkflowTest method testHgOriginNoFlags.

@Test
public void testHgOriginNoFlags() throws Exception {
    Path originPath = Files.createTempDirectory("origin");
    HgRepository origin = new HgRepository(originPath, true, DEFAULT_TIMEOUT).init();
    Path destinationPath = Files.createTempDirectory("destination");
    GitRepository destRepo = GitRepository.newBareRepo(destinationPath, getGitEnv(), true, DEFAULT_TIMEOUT, /*noVerify=*/
    false).init();
    String primaryBranch = destRepo.getPrimaryBranch();
    String config = "core.workflow(" + "    name = 'default'," + "    origin = hg.origin( url = 'file://" + origin.getHgDir() + "', ref = 'default'),\n" + "    destination = git.destination(" + "                                  url = 'file://" + destRepo.getGitDir() + "',\n" + "                                  fetch = '" + primaryBranch + "',\n" + "                                  push = '" + primaryBranch + "',\n" + "    ),\n" + "    authoring = " + authoring + "," + "    mode = '" + WorkflowMode.ITERATIVE + "'," + ")\n";
    Files.write(originPath.resolve("foo.txt"), "testing foo".getBytes(UTF_8));
    origin.hg(originPath, "add", "foo.txt");
    origin.hg(originPath, "commit", "-m", "add foo");
    options.gitDestination.committerName = "Foo";
    options.gitDestination.committerEmail = "foo@foo.com";
    options.setWorkdirToRealTempDir();
    options.setHomeDir(Files.createTempDirectory("home").toString());
    options.workflowOptions.initHistory = true;
    Migration workflow = loadConfig(config).getMigration("default");
    workflow.run(workdir, ImmutableList.of());
    ImmutableList<GitLogEntry> destCommits = destRepo.log("HEAD").run();
    assertThat(destCommits).hasSize(1);
    assertThat(destCommits.get(0).getBody()).contains("add foo");
    Files.write(originPath.resolve("bar.txt"), "testing bar".getBytes(UTF_8));
    origin.hg(originPath, "add", "bar.txt");
    origin.hg(originPath, "commit", "-m", "add bar");
    options.workflowOptions.initHistory = false;
    workflow.run(workdir, ImmutableList.of());
    destCommits = destRepo.log("HEAD").run();
    assertThat(destCommits).hasSize(2);
    assertThat(destCommits.get(0).getBody()).contains("add bar");
    assertThat(destCommits.get(1).getBody()).contains("add foo");
}
Also used : Path(java.nio.file.Path) FileSubjects.assertThatPath(com.google.copybara.testing.FileSubjects.assertThatPath) GitRepository(com.google.copybara.git.GitRepository) Migration(com.google.copybara.config.Migration) HgRepository(com.google.copybara.hg.HgRepository) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Test(org.junit.Test)

Example 3 with GitLogEntry

use of com.google.copybara.git.GitRepository.GitLogEntry in project copybara by google.

the class GerritDestinationTest method lastCommitChangeIdLineForRef.

private static String lastCommitChangeIdLineForRef(String originRef, GitRepository repo, String gitRef) throws RepoException {
    GitLogEntry log = Iterables.getOnlyElement(repo.log(gitRef).withLimit(1).run());
    assertThat(log.getBody()).contains("\n" + DummyOrigin.LABEL_NAME + ": " + originRef + "\n");
    String line = null;
    for (LabelFinder label : ChangeMessage.parseMessage(log.getBody()).getLabels()) {
        if (label.isLabel(GerritDestination.CHANGE_ID_LABEL)) {
            assertWithMessage(log.getBody() + " has a Change-Id label that doesn't" + " match the regex").that(label.getValue()).matches("I[0-9a-f]{40}$");
            // Multiple Change-Ids are not allowed.
            assertThat(line).isNull();
            line = label.getLine();
        }
    }
    assertWithMessage("Cannot find " + GerritDestination.CHANGE_ID_LABEL + " in:\n" + log.getBody()).that(line).isNotNull();
    return line;
}
Also used : LabelFinder(com.google.copybara.LabelFinder) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry)

Example 4 with GitLogEntry

use of com.google.copybara.git.GitRepository.GitLogEntry in project copybara by google.

the class GitDestinationIntegrateTest method testGerritFakeMergeNoChangeId.

@Test
public void testGerritFakeMergeNoChangeId() throws ValidationException, IOException, RepoException {
    Path workTree = Files.createTempDirectory("test");
    GitRepository repo = gitUtil.mockRemoteRepo("example.com/gerrit").withWorkTree(workTree);
    String label = new GerritIntegrateLabel(repo, options.general, "https://example.com/gerrit", 1020, 1, /*changeId=*/
    null).toString();
    assertThat(label).isEqualTo("gerrit https://example.com/gerrit 1020 Patch Set 1");
    GitRevision firstChange = singleChange(workTree, repo, "ignore_me", "Feature1 change");
    repo.simpleCommand("update-ref", "refs/changes/20/1020/1", firstChange.getSha1());
    GitTestUtil.createFakeGerritNodeDbMeta(repo, 1020, CHANGE_ID);
    GitDestination destination = destination(FAKE_MERGE);
    GitLogEntry previous = createBaseDestinationChange(destination);
    migrateOriginChange(destination, "Test change\n" + "\n" + GitModule.DEFAULT_INTEGRATE_LABEL + "=" + label + "\n", "some content");
    // Make sure commit adds new text
    String showResult = git("--git-dir", repoGitDir.toString(), "show", primaryBranch);
    assertThat(showResult).contains("some content");
    GitTesting.assertThatCheckout(repo(), primaryBranch).containsFile("test.txt", "some content").containsNoMoreFiles();
    GitLogEntry merge = getLastMigratedChange(primaryBranch);
    assertThat(merge.getBody()).isEqualTo("Merge Gerrit change 1020 Patch Set 1\n" + "\n" + "DummyOrigin-RevId: test\n");
    assertThat(Lists.transform(merge.getParents(), GitRevision::getSha1)).isEqualTo(Lists.newArrayList(previous.getCommit().getSha1(), firstChange.getSha1()));
    assertThat(console.getMessages().stream().filter(e -> e.getType() == MessageType.WARNING).findAny()).isEqualTo(Optional.empty());
}
Also used : Path(java.nio.file.Path) Writer(com.google.copybara.Destination.Writer) GitTestUtil(com.google.copybara.testing.git.GitTestUtil) Iterables(com.google.common.collect.Iterables) DummyRevision(com.google.copybara.testing.DummyRevision) Assert.assertThrows(org.junit.Assert.assertThrows) TransformResult(com.google.copybara.TransformResult) DummyOrigin(com.google.copybara.testing.DummyOrigin) RunWith(org.junit.runner.RunWith) RepoException(com.google.copybara.exception.RepoException) OptionsBuilder(com.google.copybara.testing.OptionsBuilder) MessageType(com.google.copybara.util.console.Message.MessageType) WriterContext(com.google.copybara.WriterContext) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Strategy(com.google.copybara.git.GitIntegrateChanges.Strategy) GitTestUtil.getGitEnv(com.google.copybara.testing.git.GitTestUtil.getGitEnv) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) GitTesting(com.google.copybara.git.testing.GitTesting) TransformResults(com.google.copybara.testing.TransformResults) Path(java.nio.file.Path) Before(org.junit.Before) DEFAULT_TIMEOUT(com.google.copybara.util.CommandRunner.DEFAULT_TIMEOUT) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) SkylarkTestExecutor(com.google.copybara.testing.SkylarkTestExecutor) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ValidationException(com.google.copybara.exception.ValidationException) IOException(java.io.IOException) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) DestinationStatus(com.google.copybara.Destination.DestinationStatus) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Glob(com.google.copybara.util.Glob) FAKE_MERGE_AND_INCLUDE_FILES(com.google.copybara.git.GitIntegrateChanges.Strategy.FAKE_MERGE_AND_INCLUDE_FILES) Optional(java.util.Optional) INCLUDE_FILES(com.google.copybara.git.GitIntegrateChanges.Strategy.INCLUDE_FILES) FAKE_MERGE(com.google.copybara.git.GitIntegrateChanges.Strategy.FAKE_MERGE) Joiner(com.google.common.base.Joiner) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Test(org.junit.Test)

Example 5 with GitLogEntry

use of com.google.copybara.git.GitRepository.GitLogEntry in project copybara by google.

the class GitDestinationIntegrateTest method testDefaultIntegration.

@Test
public void testDefaultIntegration() throws ValidationException, IOException, RepoException {
    Path repoPath = Files.createTempDirectory("test");
    GitRepository repo = GitRepository.newRepo(/*verbose*/
    true, repoPath, getGitEnv()).init();
    GitRevision feature1 = singleChange(repoPath, repo, "ignore_me", "Feature1 change");
    repo.simpleCommand("branch", "feature1");
    GitRevision feature2 = singleChange(repoPath, repo, "ignore_me2", "Feature2 change");
    repo.simpleCommand("branch", "feature2");
    GitDestination destination = destinationWithDefaultIntegrates();
    migrateOriginChange(destination, "Base change\n", "not important");
    GitLogEntry previous = getLastMigratedChange(primaryBranch);
    migrateOriginChange(destination, "Test change\n" + "\n" + GitModule.DEFAULT_INTEGRATE_LABEL + "=file://" + repo.getWorkTree().toString() + " feature1\n" + GitModule.DEFAULT_INTEGRATE_LABEL + "=file://" + repo.getWorkTree().toString() + " feature2\n", "some content");
    // Make sure commit adds new text
    String showResult = git("--git-dir", repoGitDir.toString(), "show", primaryBranch + "^1");
    assertThat(showResult).contains("some content");
    GitTesting.assertThatCheckout(repo(), primaryBranch).containsFile("test.txt", "some content").containsFile("ignore_me", "").containsFile("ignore_me2", "").containsNoMoreFiles();
    GitLogEntry feature1Merge = getLastMigratedChange(primaryBranch + "^1");
    assertThat(feature1Merge.getFiles()).containsExactly("test.txt", "ignore_me");
    assertThat(feature1Merge.getBody()).isEqualTo("Merge of " + feature1.getSha1() + "\n" + "\n" + DummyOrigin.LABEL_NAME + ": test\n");
    assertThat(Lists.transform(feature1Merge.getParents(), GitRevision::getSha1)).isEqualTo(Lists.newArrayList(previous.getCommit().getSha1(), feature1.getSha1()));
    GitLogEntry feature2Merge = getLastMigratedChange(primaryBranch);
    assertThat(feature2Merge.getBody()).isEqualTo("Merge of " + feature2.getSha1() + "\n" + "\n" + DummyOrigin.LABEL_NAME + ": test\n");
    assertThat(Lists.transform(feature2Merge.getParents(), GitRevision::getSha1)).isEqualTo(Lists.newArrayList(feature1Merge.getCommit().getSha1(), feature2.getSha1()));
}
Also used : Path(java.nio.file.Path) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Test(org.junit.Test)

Aggregations

GitLogEntry (com.google.copybara.git.GitRepository.GitLogEntry)29 Test (org.junit.Test)19 Path (java.nio.file.Path)12 DummyRevision (com.google.copybara.testing.DummyRevision)9 ImmutableList (com.google.common.collect.ImmutableList)6 WriterContext (com.google.copybara.WriterContext)6 Iterables (com.google.common.collect.Iterables)5 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)5 RepoException (com.google.copybara.exception.RepoException)5 ValidationException (com.google.copybara.exception.ValidationException)5 Glob (com.google.copybara.util.Glob)5 IOException (java.io.IOException)5 Optional (java.util.Optional)5 Joiner (com.google.common.base.Joiner)4 DestinationStatus (com.google.copybara.Destination.DestinationStatus)4 Author (com.google.copybara.authoring.Author)4 Lists (com.google.common.collect.Lists)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)3 Truth.assertWithMessage (com.google.common.truth.Truth.assertWithMessage)3 Writer (com.google.copybara.Destination.Writer)3