Search in sources :

Example 6 with GitRepository

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

the class WorkflowTest method testTestWorkflowWithDiffInOrigin.

@Test
public void testTestWorkflowWithDiffInOrigin() throws Exception {
    GitRepository remote = GitRepository.newBareRepo(Files.createTempDirectory("gitdir"), getGitEnv(), /*verbose=*/
    true, DEFAULT_TIMEOUT, /*noVerify=*/
    false).withWorkTree(workdir);
    remote.init();
    String primaryBranch = remote.getPrimaryBranch();
    Files.write(workdir.resolve("foo.txt"), new byte[] {});
    remote.add().files("foo.txt").run();
    remote.simpleCommand("commit", "foo.txt", "-m", "message_a");
    GitRevision lastRev = remote.resolveReference(primaryBranch);
    Files.write(workdir.resolve("bar.txt"), "change content".getBytes(UTF_8));
    remote.add().files("bar.txt").run();
    remote.simpleCommand("commit", "bar.txt", "-m", "message_s");
    TestingConsole testingConsole = new TestingConsole().respondYes();
    options.workflowOptions.lastRevision = lastRev.getSha1();
    options.setWorkdirToRealTempDir().setConsole(testingConsole).setHomeDir(StandardSystemProperty.USER_HOME.value());
    Workflow<?, ?> workflow = (Workflow<?, ?>) new SkylarkTestExecutor(options).loadConfig("core.workflow(\n" + "    name = 'foo',\n" + "    origin = git.origin(url='" + remote.getGitDir() + "',\n" + "                        ref = '" + primaryBranch + "'\n" + "    ),\n" + "    destination = folder.destination(),\n" + "    mode = 'ITERATIVE',\n" + "    authoring = " + authoring + ",\n" + "    transformations = [metadata.replace_message(''),],\n" + ")\n").getMigration("foo");
    workflow.getWorkflowOptions().diffInOrigin = true;
    workflow.run(workdir, ImmutableList.of(primaryBranch));
    testingConsole.assertThat().onceInLog(MessageType.WARNING, "Change 1 of 1 \\(.*\\)\\: Continue to migrate with '" + workflow.getMode() + "'" + " to " + workflow.getDestination().getType() + "\\?");
}
Also used : GitRepository(com.google.copybara.git.GitRepository) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) GitRevision(com.google.copybara.git.GitRevision) SkylarkTestExecutor(com.google.copybara.testing.SkylarkTestExecutor) Test(org.junit.Test)

Example 7 with GitRepository

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

the class GerritApiTest method setUp.

@Before
public void setUp() throws Exception {
    OptionsBuilder options = new OptionsBuilder().setWorkdirToRealTempDir().setEnvironment(GitTestUtil.getGitEnv().getEnvironment()).setOutputRootToTmpDir();
    credentialsFile = Files.createTempFile("credentials", "test");
    Files.write(credentialsFile, "https://user:SECRET@copybara-not-real.com".getBytes(UTF_8));
    GitRepository repo = newBareRepo(Files.createTempDirectory("test_repo"), getGitEnv(), /*verbose=*/
    true, DEFAULT_TIMEOUT, /*noVerify=*/
    false).init().withCredentialHelper("store --file=" + credentialsFile);
    httpTransport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
            String requestString = method + " " + url;
            MockLowLevelHttpRequest request = new MockLowLevelHttpRequest();
            MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
            request.setResponse(response);
            apiCalled = new AtomicBoolean(false);
            for (Entry<Predicate<String>, byte[]> entry : requestToResponse.entrySet()) {
                if (entry.getKey().test(requestString)) {
                    apiCalled.set(true);
                    byte[] content = entry.getValue();
                    assertWithMessage("'" + method + " " + url + "'").that(content).isNotNull();
                    if (content.length == 0) {
                        // No content
                        response.setStatusCode(204);
                        return request;
                    }
                    response.setContent(content);
                    return request;
                }
            }
            response.setStatusCode(404);
            response.setContent(("NO BASE_URL MATCHED! (Returning 404) REQUEST: " + requestString));
            return request;
        }
    };
    GerritOptions gerritOptions = new GerritOptions(options.general, options.git) {

        @Override
        protected HttpTransport getHttpTransport() {
            return httpTransport;
        }

        @Override
        protected GitRepository getCredentialsRepo() {
            return repo;
        }
    };
    gerritApi = gerritOptions.newGerritApi(getHost() + "/foo/bar/baz");
}
Also used : GitRepository(com.google.copybara.git.GitRepository) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Entry(java.util.Map.Entry) 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) GerritOptions(com.google.copybara.git.GerritOptions) OptionsBuilder(com.google.copybara.testing.OptionsBuilder) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Before(org.junit.Before)

Example 8 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, DEFAULT_TIMEOUT, /*noVerify=*/
    false).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 {
                    System.err.println(getContentAsString());
                    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();
                }
            };
            MockLowLevelHttpResponse response = requestToResponse.get(requestString);
            if (response == null) {
                response = new MockLowLevelHttpResponse();
                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);
            }
            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 9 with GitRepository

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

the class GitMirrorTest method testMirrorDeletedOrigin.

/**
 * Regression that test that if we use a local repo cache we prune when fetching.
 *
 * <p>'other' should never be present in destRepo since at the time of the migration it was
 * not present in the origin and destRepo was empty.
 */
@Test
public void testMirrorDeletedOrigin() throws Exception {
    GitRepository destRepo1 = bareRepo(Files.createTempDirectory("dest1")).init();
    String cfgContent = "" + "git.mirror(" + "    name = 'one'," + "    origin = 'file://" + originRepo.getGitDir().toAbsolutePath() + "'," + "    destination = 'file://" + destRepo1.getGitDir().toAbsolutePath() + "'," + ")\n" + "git.mirror(" + "    name = 'two'," + "    origin = 'file://" + originRepo.getGitDir().toAbsolutePath() + "'," + "    destination = 'file://" + destRepo.getGitDir().toAbsolutePath() + "'," + ")";
    loadMigration(cfgContent, "one").run(workdir, /*sourceRef=*/
    null);
    originRepo.simpleCommand("branch", "-D", "other");
    Mirror mirror = (Mirror) loadMigration(cfgContent, "two");
    assertThat(mirror.getOriginDescription().get("ref")).containsExactly("refs/heads/*");
    assertThat(mirror.getDestinationDescription().get("ref")).containsExactly("refs/heads/*");
    mirror.run(workdir, /*sourceRef=*/
    null);
    checkRefDoesntExist("refs/heads/other");
}
Also used : GitRepository(com.google.copybara.git.GitRepository) Test(org.junit.Test)

Example 10 with GitRepository

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

the class WorkflowTest method checkLastRevStatus.

private void checkLastRevStatus(WorkflowMode mode) throws IOException, RepoException, ValidationException {
    Path originPath = Files.createTempDirectory("origin");
    Path destinationWorkdir = Files.createTempDirectory("destination_workdir");
    GitRepository origin = GitRepository.newRepo(/*verbose*/
    true, originPath, getGitEnv()).init();
    GitRepository destinationBare = newBareRepo(Files.createTempDirectory("destination"), getGitEnv(), /*verbose=*/
    true, DEFAULT_TIMEOUT, /*noVerify=*/
    false);
    destinationBare.init();
    GitRepository destination = destinationBare.withWorkTree(destinationWorkdir);
    String primaryBranch = destination.getPrimaryBranch();
    String config = "core.workflow(" + "    name = '" + "default" + "'," + "    origin = git.origin(" + "                        url = 'file://" + origin.getWorkTree() + "'\n," + "                        ref = '" + primaryBranch + "'\n," + "                        ),\n" + "    destination = git.destination(" + "        url = 'file://" + destinationBare.getGitDir() + "',\n" + "        push = '" + primaryBranch + "',\n" + "        fetch = '" + primaryBranch + "'\n" + "    )," + "    authoring = " + authoring + "," + "    mode = '" + mode + "'," + ")\n";
    Files.write(originPath.resolve("foo.txt"), "not important".getBytes(UTF_8));
    origin.add().files("foo.txt").run();
    origin.commit("Foo <foo@bara.com>", ZonedDateTime.now(ZoneId.systemDefault()), "not important");
    String firstCommit = origin.parseRef("HEAD");
    Files.write(originPath.resolve("foo.txt"), "foo".getBytes(UTF_8));
    origin.add().files("foo.txt").run();
    origin.commit("Foo <foo@bara.com>", ZonedDateTime.now(ZoneId.systemDefault()), "change1");
    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.checkLastRevState = true;
    options.setLastRevision(firstCommit);
    loadConfig(config).getMigration("default").run(workdir, ImmutableList.of("HEAD"));
    // Modify destination last commit
    Files.write(destinationWorkdir.resolve("foo.txt"), "foo_changed".getBytes(UTF_8));
    destination.add().files("foo.txt").run();
    destination.simpleCommand("commit", "--amend", "-a", "-C", "HEAD");
    Files.write(originPath.resolve("foo.txt"), "foo_origin_changed".getBytes(UTF_8));
    origin.add().files("foo.txt").run();
    origin.commit("Foo <foo@bara.com>", ZonedDateTime.now(ZoneId.systemDefault()), "change2");
    options.setForce(false);
    options.setLastRevision(null);
    ValidationException thrown = assertThrows(ValidationException.class, () -> loadConfig(config).getMigration("default").run(workdir, ImmutableList.of("HEAD")));
    assertThat(thrown).hasMessageThat().contains("didn't result in an empty change. This means that the result change of" + " that migration was modified ouside of Copybara");
}
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)

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