Search in sources :

Example 1 with GitRepository

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

the class GithubApiTest method getTransport.

@Override
public GitHubApiTransport getTransport() throws Exception {
    credentialsFile = Files.createTempFile("credentials", "test");
    Files.write(credentialsFile, "https://user:SECRET@github.com".getBytes(UTF_8));
    GitRepository repo = newBareRepo(Files.createTempDirectory("test_repo"), getGitEnv(), /*verbose=*/
    true).init().withCredentialHelper("store --file=" + credentialsFile);
    requestToResponse = new HashMap<>();
    requestValidators = new HashMap<>();
    httpTransport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            String requestString = method + " " + url;
            MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {

                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    Predicate<String> validator = requestValidators.get(method + " " + url);
                    if (validator != null) {
                        assertWithMessage("Request content did not match expected values.").that(validator.test(getContentAsString())).isTrue();
                    }
                    return super.execute();
                }
            };
            byte[] content = requestToResponse.get(requestString);
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            if (content == null) {
                response.setContent(String.format("{ 'message' : 'This is not the repo you are looking for! %s %s'," + " 'documentation_url' : 'http://github.com/some_url'}", method, url));
                response.setStatusCode(404);
            } else {
                response.setContent(content);
            }
            request.setResponse(response);
            return request;
        }
    };
    return new GitHubApiTransportImpl(repo, httpTransport, "some_storage_file", new TestingConsole());
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Predicate(java.util.function.Predicate) GitRepository(com.google.copybara.git.GitRepository) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse)

Example 2 with GitRepository

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

the class WorkflowTest method reversibleCheckSymlinkError.

@Test
public void reversibleCheckSymlinkError() throws Exception {
    Path someRoot = Files.createTempDirectory("someRoot");
    Path originPath = someRoot.resolve("origin");
    Files.createDirectories(originPath);
    GitRepository origin = GitRepository.newRepo(/*verbose*/
    true, originPath, getGitEnv()).init();
    String primaryBranch = origin.getPrimaryBranch();
    String config = "core.workflow(\n" + "    name = 'default',\n" + String.format("    origin = git.origin( url = 'file://%s', ref = '%s'),\n", origin.getWorkTree(), primaryBranch) + "    destination = testing.destination(),\n" + "    authoring = " + authoring + ",\n" + "    origin_files = glob(['included/**']),\n" + "    reversible_check = True,\n" + "    mode = '" + WorkflowMode.SQUASH + "',\n" + ")\n";
    Migration workflow = loadConfig(config).getMigration("default");
    Path included = originPath.resolve("included");
    Files.createDirectory(included);
    Files.write(originPath.resolve("included/foo.txt"), "a".getBytes(UTF_8));
    Path fileOutsideCheckout = someRoot.resolve("file_outside_checkout");
    Files.write(fileOutsideCheckout, "THE CONTENT".getBytes(UTF_8));
    Files.createSymbolicLink(included.resolve("symlink"), included.relativize(fileOutsideCheckout));
    origin.add().files("included/foo.txt").run();
    origin.add().files("included/symlink").run();
    origin.commit("Foo <foo@bara.com>", ZonedDateTime.now(ZoneId.systemDefault()), "A commit");
    ValidationException expected = assertThrows(ValidationException.class, () -> workflow.run(workdir, ImmutableList.of()));
    assertThat(expected.getMessage()).matches("" + "Failed to perform reversible check of transformations due to symlink '.*' that " + "points outside the checkout dir. Consider removing this symlink from your " + "origin_files or, alternatively, set reversible_check = False in your " + "workflow.");
}
Also used : Path(java.nio.file.Path) FileSubjects.assertThatPath(com.google.copybara.testing.FileSubjects.assertThatPath) GitRepository(com.google.copybara.git.GitRepository) ValidationException(com.google.copybara.exception.ValidationException) Migration(com.google.copybara.config.Migration) Test(org.junit.Test)

Example 3 with GitRepository

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

the class WorkflowTest method testDryRunWithLocalGitPath.

/**
 * Regression test that checks that we reuse the same writer in dry-run mode for multiple
 * invocations inside the same migration so that state is kept.
 */
@Test
public void testDryRunWithLocalGitPath() throws Exception {
    Path originPath = Files.createTempDirectory("origin");
    Path destinationPath = Files.createTempDirectory("destination");
    GitRepository origin = GitRepository.newRepo(/*verbose*/
    true, originPath, getGitEnv()).init();
    GitRepository destination = GitRepository.newBareRepo(destinationPath, getGitEnv(), /*verbose=*/
    true, DEFAULT_TIMEOUT, /*noVerify=*/
    false).init();
    String primaryBranch = origin.getPrimaryBranch();
    String config = "core.workflow(" + "    name = 'default',\n" + "    origin = git.origin(\n" + "        url = 'file://" + origin.getWorkTree() + "',\n" + "        ref = '" + primaryBranch + "'\n" + "    ),\n" + "    destination = git.destination(" + "        url = 'file://" + destination.getGitDir() + "',\n" + "        push = '" + primaryBranch + "',\n" + "        fetch = '" + primaryBranch + "'\n" + "    ),\n" + "    authoring = " + authoring + ",\n" + "    mode = 'SQUASH',\n" + ")\n";
    addGitFile(originPath, origin, "foo.txt", "not important");
    commit(origin, "baseline\n\nOrigin-Label: 1234567");
    options.setWorkdirToRealTempDir();
    // Pass custom HOME directory so that we run an hermetic test and we
    // can add custom configuration to $HOME/.gitconfig.
    options.setEnvironment(GitTestUtil.getGitEnv().getEnvironment());
    options.setHomeDir(Files.createTempDirectory("home").toString());
    options.gitDestination.committerName = "Foo";
    options.gitDestination.committerEmail = "foo@foo.com";
    options.workflowOptions.initHistory = true;
    loadConfig(config).getMigration("default").run(Files.createTempDirectory("workdir"), ImmutableList.of());
    // Now run again with force and no changes so that it uses the default migrator (The affected
    // path
    options.gitDestination.localRepoPath = Files.createTempDirectory("temp").toString();
    options.workflowOptions.initHistory = false;
    options.general.dryRunMode = true;
    options.setForce(true);
    EmptyChangeException e = assertThrows(EmptyChangeException.class, () -> loadConfig(config).getMigration("default").run(Files.createTempDirectory("workdir"), ImmutableList.of()));
    assertThat(e).hasMessageThat().contains("Migration of the revision resulted in an empty change");
    assertThat(e).hasMessageThat().contains(destination.parseRef("HEAD"));
}
Also used : Path(java.nio.file.Path) FileSubjects.assertThatPath(com.google.copybara.testing.FileSubjects.assertThatPath) GitRepository(com.google.copybara.git.GitRepository) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Test(org.junit.Test)

Example 4 with GitRepository

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

the class WorkflowTest method testFirstParentAlreadyImportedInNoFirstParent.

/**
 * Regression that test that when using git.origin with first_parent = False, if the first parent
 * of a merge is already imported and the merge is a no-op, we detect the import as
 * EmptyChangeException instead of detecting the non-first parent as the change to import
 */
@Test
public void testFirstParentAlreadyImportedInNoFirstParent() throws Exception {
    Path originPath = Files.createTempDirectory("origin");
    GitRepository origin = GitRepository.newRepo(/*verbose*/
    true, originPath, getGitEnv()).init();
    String primaryBranch = origin.getPrimaryBranch();
    options.setForce(false);
    options.workflowOptions.initHistory = true;
    String config = "core.workflow(" + "    name = 'default'," + "    origin = git.origin( url = 'file://" + origin.getWorkTree() + "',\n" + "                         ref = '" + primaryBranch + "',\n" + "                         first_parent = False),\n" + "    destination = testing.destination(),\n" + "    authoring = " + authoring + "," + "    origin_files = glob(['included/**'])," + "    mode = '" + WorkflowMode.SQUASH + "'," + ")\n";
    Migration workflow = loadConfig(config).getMigration("default");
    addGitFile(originPath, origin, "included/foo.txt", "");
    GitRevision lastRev = commit(origin, "last_rev");
    workflow.run(workdir, ImmutableList.of());
    assertThat(destination.processed.get(0).getOriginRef()).isEqualTo(lastRev);
    origin.simpleCommand("checkout", "-b", "feature");
    addGitFile(originPath, origin, "included/foo.txt", "SHOULD NOT BE IN PRIMARY");
    commit(origin, "feature commit");
    origin.simpleCommand("revert", "HEAD");
    addGitFile(originPath, origin, "excluded/bar.txt", "don't migrate!");
    commit(origin, "excluded commit");
    origin.simpleCommand("checkout", primaryBranch);
    origin.simpleCommand("merge", "-s", "ours", "feature");
    EmptyChangeException e = assertThrows(EmptyChangeException.class, () -> workflow.run(workdir, ImmutableList.of()));
    assertThat(e).hasMessageThat().matches("No changes from " + lastRev.getSha1() + " up to .* match any origin_files.*");
}
Also used : Path(java.nio.file.Path) FileSubjects.assertThatPath(com.google.copybara.testing.FileSubjects.assertThatPath) GitRepository(com.google.copybara.git.GitRepository) GitRevision(com.google.copybara.git.GitRevision) Migration(com.google.copybara.config.Migration) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Test(org.junit.Test)

Example 5 with GitRepository

use of com.google.copybara.git.GitRepository 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)

Aggregations

GitRepository (com.google.copybara.git.GitRepository)17 Test (org.junit.Test)12 FileSubjects.assertThatPath (com.google.copybara.testing.FileSubjects.assertThatPath)10 Path (java.nio.file.Path)10 Migration (com.google.copybara.config.Migration)6 GitRevision (com.google.copybara.git.GitRevision)5 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)5 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)3 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)3 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)3 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)3 EmptyChangeException (com.google.copybara.exception.EmptyChangeException)3 ValidationException (com.google.copybara.exception.ValidationException)3 SkylarkTestExecutor (com.google.copybara.testing.SkylarkTestExecutor)3 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)2 IOException (java.io.IOException)2 Predicate (java.util.function.Predicate)2 ChangeRejectedException (com.google.copybara.exception.ChangeRejectedException)1 GerritOptions (com.google.copybara.git.GerritOptions)1 GitLogEntry (com.google.copybara.git.GitRepository.GitLogEntry)1