Example usage for org.eclipse.jgit.api Git add

List of usage examples for org.eclipse.jgit.api Git add

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git add.

Prototype

public AddCommand add() 

Source Link

Document

Return a command object to execute a Add command

Usage

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void isFile() throws Exception {
    // Given// w ww  . j  ava2s.  c  om
    String userName = "yobi";
    String projectName = "mytest";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;
    String repoPath = wcPath + "/.git";
    String dirName = "dir";
    String fileName = "file";

    Repository repository = new RepositoryBuilder().setGitDir(new File(repoPath)).build();
    repository.create(false);
    Git git = new Git(repository);
    FileUtils.forceMkdir(new File(wcPath + "/" + dirName));
    FileUtils.touch(new File(wcPath + "/" + fileName));
    git.add().addFilepattern(dirName).call();
    git.add().addFilepattern(fileName).call();
    git.commit().setMessage("test").call();
    repository.close();

    // When
    GitRepository gitRepository = new GitRepository(userName, projectName + "/");

    // Then
    assertThat(gitRepository.isFile(dirName)).isEqualTo(false);
    assertThat(gitRepository.isFile(fileName)).isEqualTo(true);
    assertThat(gitRepository.isFile("not_exist_file")).isEqualTo(false);
    assertThat(gitRepository.isFile(fileName, "not_exist_branch")).isEqualTo(false);
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void testGetAllBranches() throws IOException, GitAPIException {
    FakeApplication app = support.Helpers.makeTestApplication();
    Helpers.start(app);/*from   w  ww  . ja v a  2s. c o m*/

    // Given
    String userName = "wansoon";
    String projectName = "test";
    Project project = createProject(userName, projectName);
    project.save();

    String email = "test@email.com";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + "clone-" + projectName + ".git";
    String repoPath = wcPath + "/.git";
    String dirName = "dir";
    String fileName = "file";

    GitRepository gitRepository = new GitRepository(userName, projectName);
    gitRepository.create();

    Repository repository = new RepositoryBuilder().setGitDir(new File(repoPath)).build();
    repository.create(false);

    Git git = new Git(repository);
    FileUtils.forceMkdir(new File(wcPath + "/" + dirName));
    FileUtils.touch(new File(wcPath + "/" + fileName));
    git.add().addFilepattern(dirName).call();
    git.add().addFilepattern(fileName).call();
    git.commit().setMessage("test").setAuthor(userName, email).call();

    String branchName = "testBranch";
    git.branchCreate().setName(branchName).setForce(true).call();

    git.push().setRemote(GitRepository.getGitDirectoryURL(project))
            .setRefSpecs(new RefSpec(branchName + ":" + branchName)).setForce(true).call();

    repository.close();

    // When
    List<GitBranch> gitBranches = gitRepository.getBranches();
    gitRepository.close();

    // Then
    assertThat(gitBranches.size()).isEqualTo(1);
    assertThat(gitBranches.get(0).getShortName()).isEqualTo(branchName);

    Helpers.stop(app);
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getDiff_bigFile() throws IOException, GitAPIException {
    // given//from  w w  w  .  j  a v  a  2s .  co  m
    String userName = "yobi";
    String projectName = "testProject";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;

    String repoPath = wcPath + "/.git";
    File repoDir = new File(repoPath);
    Repository repo = new RepositoryBuilder().setGitDir(repoDir).build();
    repo.create(false);

    Git git = new Git(repo);
    String testFilePath = wcPath + "/readme.txt";
    BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath));

    char[] cbuf = new char[FileDiff.SIZE_LIMIT + 1];
    java.util.Arrays.fill(cbuf, 'a');
    out.write(cbuf); // Add a big file
    out.flush();
    git.add().addFilepattern("readme.txt").call();
    RevCommit commit = git.commit().setMessage("commit 1").call();

    // When
    FileDiff diff = GitRepository.getDiff(repo, commit).get(0);

    // Then
    assertThat(diff.a).describedAs("a").isNull();
    assertThat(diff.b).describedAs("b").isNotNull();
    assertThat(diff.hasError(FileDiff.Error.A_SIZE_EXCEEDED)).describedAs("a exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.B_SIZE_EXCEEDED)).describedAs("b exceeds the size limit.").isTrue();
    assertThat(diff.hasError(FileDiff.Error.DIFF_SIZE_EXCEEDED)).describedAs("The diff exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.OTHERS_SIZE_EXCEEDED))
            .describedAs("The others exceeds the size limit.").isFalse();
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getDiff_manyLines() throws IOException, GitAPIException {
    // given/*from  w w  w .  j  a v  a 2  s. c  o m*/
    String userName = "yobi";
    String projectName = "testProject";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;

    String repoPath = wcPath + "/.git";
    File repoDir = new File(repoPath);
    Repository repo = new RepositoryBuilder().setGitDir(repoDir).build();
    repo.create(false);

    Git git = new Git(repo);
    String testFilePath = wcPath + "/readme.txt";
    BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath));

    for (int i = 0; i < FileDiff.LINE_LIMIT + 1; i++) {
        out.write("a\n"); // Add a big file
    }
    out.flush();
    git.add().addFilepattern("readme.txt").call();
    RevCommit commit = git.commit().setMessage("commit 1").call();

    // When
    FileDiff diff = GitRepository.getDiff(repo, commit).get(0);

    // Then
    assertThat(diff.hasError(FileDiff.Error.A_SIZE_EXCEEDED)).describedAs("a exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.B_SIZE_EXCEEDED)).describedAs("b exceeds the size limit.").isTrue();
    assertThat(diff.hasError(FileDiff.Error.DIFF_SIZE_EXCEEDED)).describedAs("The diff exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.OTHERS_SIZE_EXCEEDED))
            .describedAs("The others exceeds the size limit.").isFalse();

}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getDiff_smallChangeOfBigFile() throws IOException, GitAPIException {
    // given/*from  www  .  j a  v  a2  s  . co  m*/
    String userName = "yobi";
    String projectName = "testProject";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;

    String repoPath = wcPath + "/.git";
    File repoDir = new File(repoPath);
    Repository repo = new RepositoryBuilder().setGitDir(repoDir).build();
    repo.create(false);

    Git git = new Git(repo);
    String testFilePath = wcPath + "/readme.txt";
    BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath));

    // Commit a big file
    for (int i = 0; i < FileDiff.LINE_LIMIT + 1; i++) {
        out.write("a\n"); // Add a big file
    }
    out.flush();
    git.add().addFilepattern("readme.txt").call();
    git.commit().setMessage("commit 1").call();

    // Modify the file
    out.write("b\n");
    out.flush();
    git.add().addFilepattern("readme.txt").call();
    RevCommit commit = git.commit().setMessage("commit 2").call();

    // When
    FileDiff diff = GitRepository.getDiff(repo, commit).get(0);

    // Then
    assertThat(diff.hasError(FileDiff.Error.A_SIZE_EXCEEDED)).describedAs("a exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.B_SIZE_EXCEEDED)).describedAs("b exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.DIFF_SIZE_EXCEEDED)).describedAs("The diff exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.OTHERS_SIZE_EXCEEDED))
            .describedAs("The others exceeds the size limit.").isFalse();
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getDiff_manyFiles() throws IOException, GitAPIException {
    // given/*from  w  w  w.  ja va 2s  .  c o m*/
    String userName = "yobi";
    String projectName = "testProject";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;

    String repoPath = wcPath + "/.git";
    File repoDir = new File(repoPath);
    Repository repo = new RepositoryBuilder().setGitDir(repoDir).build();
    repo.create(false);

    Git git = new Git(repo);

    // Add four big files
    for (int i = 0; i < 4; i++) {
        String testFilePath = wcPath + "/" + i + ".txt";
        BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath));
        char[] cbuf = new char[FileDiff.SIZE_LIMIT - 1];
        java.util.Arrays.fill(cbuf, 'a');
        out.write(cbuf);
        out.flush();
        git.add().addFilepattern(i + ".txt").call();
    }

    // Add a small file
    String testFilePath = wcPath + "/readme.txt";
    BufferedWriter out = new BufferedWriter(new FileWriter(testFilePath));
    out.write("hello");
    out.flush();
    git.add().addFilepattern("readme.txt").call();
    RevCommit commit = git.commit().setMessage("commit 1").call();

    // When
    List<FileDiff> diffs = GitRepository.getDiff(repo, commit);
    FileDiff diff = diffs.get(4);

    // Then
    assertThat(diff.hasError(FileDiff.Error.A_SIZE_EXCEEDED)).describedAs("a exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.B_SIZE_EXCEEDED)).describedAs("b exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.DIFF_SIZE_EXCEEDED)).describedAs("The diff exceeds the size limit.")
            .isFalse();
    assertThat(diff.hasError(FileDiff.Error.OTHERS_SIZE_EXCEEDED))
            .describedAs("The others exceeds the size limit.").isTrue();
}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;//from   www.  j a v  a  2 s. com
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}

From source file:ru.nikitenkogleb.androidtools.newappwizard.GitSupport.java

/**   Send changes to remote repository */
final void close(String userName, String userEmail, String initMessage) {
    if (!isSuccessful())
        return;//from   w w w  .  j a  v  a2 s.  c o  m
    FileRepository mRepository = null;
    Git mGit = null;
    try {

        mRepository = new FileRepository(new File(mProjectPath, ".git"));
        mGit = new Git(mRepository);

        mGit.add().addFilepattern(".").call();
        mGit.commit().setAll(true).setAuthor(userName, userEmail).setCommitter(userName, userEmail)
                .setMessage(initMessage).call();
        final PushCommand pushCommand = mGit.push().setRemote("origin").setPushAll();

        if (mSshConfigCallback != null)
            pushCommand.setTransportConfigCallback(mSshConfigCallback);
        else
            pushCommand.setCredentialsProvider(mHttpsCredentialsProvider);

        pushCommand.call();
    } catch (GitAPIException | IOException e) {
        e.printStackTrace();
    }

    if (mGit != null)
        mGit.close();
    if (mRepository != null)
        mRepository.close();
}

From source file:se.kth.karamel.backend.github.GithubApi.java

/**
 * Adds a file to the Github repo's index. If the file already exists, it will delete it and replace its contents with
 * the new contents. You wil subsequenty need to commit the change and push the commit to github.
 *
 * @param owner/* w w  w  .  j av a 2  s  . c o  m*/
 * @param repoName
 * @param fileName
 * @param contents
 * @throws KaramelException
 */
public synchronized static void addFile(String owner, String repoName, String fileName, String contents)
        throws KaramelException {
    File repoDir = getRepoDirectory(repoName);
    Git git = null;
    try {
        git = Git.open(repoDir);

        new File(repoDir + File.separator + fileName).delete();
        new File(repoDir + File.separator + fileName).getParentFile().mkdirs();
        try (PrintWriter out = new PrintWriter(repoDir + File.separator + fileName)) {
            out.println(contents);
        }
        git.add().addFilepattern(fileName).call();
    } catch (IOException | GitAPIException ex) {
        throw new KaramelException(ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }

    }
}

From source file:se.kth.karamel.backend.github.GithubApi.java

public synchronized static void removeFile(String owner, String repoName, String fileName)
        throws KaramelException {
    File repoDir = getRepoDirectory(repoName);
    Git git = null;
    try {//from  w w  w .j  av a2s . com
        git = Git.open(repoDir);
        new File(repoDir + File.separator + fileName).delete();
        git.add().addFilepattern(fileName).call();
        git.commit().setAuthor(user, email).setMessage("File removed by Karamel.").setAll(true).call();
        git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
        RepoItem toRemove = null;
        List<RepoItem> repos = cachedRepos.get(owner);
        for (RepoItem r : repos) {
            if (r.getName().compareToIgnoreCase(repoName) == 0) {
                toRemove = r;
            }
        }
        if (toRemove != null) {
            repos.remove(toRemove);
        }
    } catch (IOException | GitAPIException ex) {
        throw new KaramelException(ex.getMessage());
    } finally {
        if (git != null) {
            git.close();
        }
    }
}