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:de.ks.blogging.grav.ui.post.BlogIntegrationBasicFixture.java

License:Apache License

public void createBlogFolders(boolean withGit) throws Exception {
    dateTime = LocalDateTime.now().withSecond(0).withNano(0);
    String tmpDir = StandardSystemProperty.JAVA_IO_TMPDIR.value();
    fileBlog1 = new File(tmpDir, "blog1");
    fileBlog2 = new File(tmpDir, "blog2");
    fileBlog1.mkdir();//w  w w .j  a  v a2  s  .  c o m
    fileBlog2.mkdir();

    Git git = null;
    if (withGit) {
        git = Git.init().setDirectory(fileBlog2).call();
    }

    Files.write(new File(fileBlog1, "blog1.md").toPath(), Arrays.asList(getBlog("post 1", "Hello Sauerland")));
    Files.write(new File(fileBlog2, "blog2_a.md").toPath(), Arrays.asList(getBlog("post 1", "Hello Woll")));
    if (git != null) {
        git.add().addFilepattern("blog2_a.md").call();
        RevCommit commit = git.commit().setAll(true).setMessage("commit 1").call();
        commit1 = commit.getId().getName();
    }
    Files.write(new File(fileBlog2, "blog2_b.md").toPath(), Arrays.asList(getBlog("post 2", "Ein Bier bitte")));
    if (git != null) {
        git.add().addFilepattern("blog2_b.md").call();
        RevCommit commit = git.commit().setAll(true).setMessage("commit 2").call();
        commit2 = commit.getId().getName();
    }
    if (git != null) {
        Files.write(new File(fileBlog2, "blog2_c.md").toPath(),
                Arrays.asList(getBlog("post 3", "Ein Tischgedeck bitte")));

        git.add().addFilepattern("blog2_c.md").call();
        RevCommit commit = git.commit().setAll(true).setMessage("commit 3").call();
        commit3 = commit.getId().getName();

        Files.move(new File(fileBlog2, "blog2_c.md").toPath(), new File(fileBlog2, "blog2_d.md").toPath());

        git.add().addFilepattern("blog2_c.md").addFilepattern("blog2_d.md").call();
        commit = git.commit().setAll(true).setMessage("commit moved").call();
        commitMoved = commit.getId().getName();

        Files.delete(new File(fileBlog2, "blog2_d.md").toPath());

        git.add().addFilepattern("blog2_d.md").call();
        commit = git.commit().setAll(true).setMessage("commit deleted").call();
        commitDeleted = commit.getId().getName();
    }
}

From source file:deployer.publishers.openshift.RhcApplicationGitRepoModificationsTest.java

License:Apache License

private void populateWithInitialFiles(Git git, File testDir) throws IOException, GitAPIException {
    log.debug("Git Repo Dir: " + git.getRepository().getDirectory().toString());
    log.debug("Test dir: " + testDir.toString());
    FileUtils.writeStringToFile(Files.resolve(testDir, "README"), "This is from the RhcApplication unit test.");
    File aDir = Files.resolve(testDir, "a-dir");
    Files.createDirectories(aDir);
    FileUtils.writeStringToFile(Files.resolve(aDir, "source.json"), "{'hello': 'world'}");
    FileUtils.writeStringToFile(Files.resolve(aDir, "AnotherFile.txt"), "A file about nothing");
    FileUtils.writeStringToFile(Files.resolve(testDir, "deployed_version.txt"), "v0.33333333333333333");
    log.info(git.add().addFilepattern(".").call().toString());
    log.info(git.commit().setAuthor("Unit Test", "unit.test@email.com").setMessage("Initial files").setAll(true)
            .call().toString());//from   w  ww . ja  v a2  s. com
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Commit file changes. IF flushing for commits is enabled changes will be
 * flushed./*w w  w.  java  2 s.c o m*/
 *
 * @param message commit message
 * @return this file
 * @throws IOException
 * @throws IllegalStateException if this file is currently not open
 */
public VersionedFile commit(String message) throws IOException {

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    Git git = null;

    try {

        //             this should NEVER happen
        if (hasConflicts()) {
            throw new IllegalStateException("File \"" + getFile().getPath() + "\" has conflicts!");
        }

        // ensures that message is not null
        if (message == null || message.isEmpty()) {
            message = "no message";
        }

        System.out.print(">> commit version ");

        // open the git repository
        git = Git.open(tmpFolder);

        // retrieve the current git status
        Status status = git.status().call();

        // rm command to tell git to remove files
        RmCommand rm = git.rm();

        boolean needsRM = false;

        // checks whether rm is necessary and adds relevant paths
        for (String removedFile : status.getMissing()) {
            rm.addFilepattern(removedFile);
            needsRM = true;
        }

        // calls the rm command if necessary
        if (needsRM) {
            rm.call();
        }

        // adds all remaining files
        git.add().addFilepattern(".").call();

        // perform the commit
        git.commit().setMessage(message).setAuthor(System.getProperty("user.name"), "?").call();

        commits = null;

        // updates the current version number
        currentVersion = getNumberOfVersions() - 1;

        System.out.println(currentVersion + ": ");
        System.out.println(">>> commit-id (SHA-1): " + getVersions().get(currentVersion).getName());

        if (isFlushCommits()) {
            flush();
        }

        closeGit(git);

        return this;

    } catch (NoFilepatternException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (NoHeadException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (NoMessageException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (UnmergedPathException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (ConcurrentRefUpdateException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (JGitInternalException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (WrongRepositoryStateException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (IOException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    }
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Initializes git repository./*from w  ww  .  ja v a2  s . com*/
 *
 * <p><b>Warning:</b> Be careful when calling this method. It will destroy
 * any existing repository!</p>
 *
 * @throws IOException
 */
private void initGit() throws IOException {

    File repoFile = new File(tmpFolder.getAbsolutePath() + "/.git");

    // delete existing repository
    if (repoFile.exists()) {
        IOUtil.deleteDirectory(repoFile);
    }

    Git git = null;

    try {
        // initialize git repository
        Git.init().setDirectory(tmpFolder).call();
        git = Git.open(tmpFolder);
        git.add().addFilepattern(".").call();
        // perform initial commit
        git.commit().setMessage("initial commit").setAuthor("VRL-User", "").call();

        git.getRepository().close();

    } catch (NoHeadException ex) {
        throw new IOException("Git exception", ex);
    } catch (NoMessageException ex) {
        throw new IOException("Git exception", ex);
    } catch (UnmergedPathException ex) {
        throw new IOException("Git exception", ex);
    } catch (ConcurrentRefUpdateException ex) {
        throw new IOException("Git exception", ex);
    } catch (JGitInternalException ex) {
        throw new IOException("Git exception", ex);
    } catch (WrongRepositoryStateException ex) {
        throw new IOException("Git exception", ex);
    } catch (NoFilepatternException ex) {
        throw new IOException("Git exception", ex);
    } catch (IOException ex) {
        throw new IOException("Git exception", ex);
    } finally {
        if (git != null) {
            git.getRepository().close();
        }
    }
}

From source file:facade.GitFacade.java

public static void commitRepo(Repository repository, String message) throws GitAPIException {
    Git git = new Git(repository);
    git.add().addFilepattern(".").call();
    git.commit().setAll(true).setMessage(message).call();

}

From source file:fr.duminy.tools.jgit.JGitToolboxTest.java

License:Open Source License

private static String addAndCommitFile(Git git) throws IOException, GitAPIException {
    File gitDirectory = git.getRepository().getDirectory().getParentFile();
    String filename = "file" + COUNTER++;
    IOUtils.write(filename + " content", new FileOutputStream(new File(gitDirectory, filename)));
    git.add().addFilepattern(filename).call();
    RevCommit call = git.commit().setMessage("add " + filename).call();
    String sha1 = call.getName();
    LOGGER.info("{}: Added file {} (sha1: {})", gitDirectory.getName(), filename, sha1);
    return sha1;/*from w  w  w.  j a  va 2  s . co  m*/
}

From source file:fr.xebia.workshop.git.UpdatePomFileAndCommit.java

License:Apache License

@Override
public void updateGitRepository(Git git, GitRepositoryInfo repositoryInfo) throws GitAPIException {
    File pomFile = getPomFile(git);

    updatePomGroupId(pomFile, repositoryInfo);

    git.add().addFilepattern(POM_XML).call();
    try {/* ww  w.j ava 2 s .co  m*/
        git.commit().setCommitter("Team " + teamId, "").setMessage(COMMIT_MESSAGE).call();
    } catch (UnmergedPathException e) {
        throw new IllegalStateException("Cannot commit git repository", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws AuthenticationException /*from   w w  w . j a va 2  s . c  o m*/
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#addFiles(java.io.File, java.util.Set)
 *//*from w w w  .java 2s . c o m*/
@Override
public void addFiles(String... files) throws IllegalArgumentException, IOException {
    try {
        log.info("Add Files called {}", Arrays.toString(files));
        Git git = getGit();
        if (files.length == 0) {
            log.debug("No files to add");
        } else {
            AddCommand ac = git.add();
            for (String file : files) {
                ac.addFilepattern(file);
            }
            ac.call();
        }
        log.info("addFiles Complete.  Current status: " + statusToString(git.status().call()));
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

private Set<String> resolveMergeFailures(MergeFailType mergeFailType, String stashIDToApply,
        Map<String, MergeFailOption> resolutions) throws IllegalArgumentException, IOException, MergeFailure {
    log.debug("resolve merge failures called - mergeFailType: {} stashIDToApply: {} resolutions: {}",
            mergeFailType, stashIDToApply, resolutions);
    try {//from w ww . jav a2s  .c om
        Git git = getGit();

        //We unfortunately, must know the mergeFailType option, because the resolution mechanism here uses OURS and THEIRS - but the 
        //meaning of OURS and THEIRS reverse, depending on if you are recovering from a merge failure, or a stash apply failure.

        for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
            if (MergeFailOption.FAIL == r.getValue()) {
                throw new IllegalArgumentException("MergeFailOption.FAIL is not a valid option");
            } else if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                log.debug("Keeping our local file for conflict {}", r.getKey());
                git.checkout().addPath(r.getKey())
                        .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.OURS : Stage.THEIRS)
                        .call();
            } else if (MergeFailOption.KEEP_REMOTE == r.getValue()) {
                log.debug("Keeping remote file for conflict {}", r.getKey());
                git.checkout().addPath(r.getKey())
                        .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.THEIRS : Stage.OURS)
                        .call();
            } else {
                throw new IllegalArgumentException("MergeFailOption is required");
            }

            log.debug("calling add to mark merge resolved");
            git.add().addFilepattern(r.getKey()).call();
        }

        if (mergeFailType == MergeFailType.STASH_TO_LOCAL) {
            //clean up the stash
            log.debug("Dropping stash");
            git.stashDrop().call();
        }

        RevWalk walk = new RevWalk(git.getRepository());
        Ref head = git.getRepository().getRef("refs/heads/master");
        RevCommit commitWithPotentialNote = walk.parseCommit(head.getObjectId());

        log.info("resolve merge failures Complete.  Current status: " + statusToString(git.status().call()));

        RevCommit rc = git.commit().setMessage(
                "Merging with user specified merge failure resolution for files " + resolutions.keySet())
                .call();

        git.notesRemove().setObjectId(commitWithPotentialNote).call();
        Set<String> filesChangedInCommit = listFilesChangedInCommit(git.getRepository(),
                commitWithPotentialNote.getId(), rc);

        //When we auto resolve to KEEP_REMOTE - these will have changed - make sure they are in the list.
        //seems like this shouldn't really be necessary - need to look into the listFilesChangedInCommit algorithm closer.
        //this might already be fixed by the rework on 11/12/14, but no time to validate at the moment. - doesn't do any harm.
        for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
            if (MergeFailOption.KEEP_REMOTE == r.getValue()) {
                filesChangedInCommit.add(r.getKey());
            }
            if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                filesChangedInCommit.remove(r.getKey());
            }
        }

        if (!StringUtils.isEmptyOrNull(stashIDToApply)) {
            log.info("Replaying stash identified in note");
            try {
                git.stashApply().setStashRef(stashIDToApply).call();
                log.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (StashApplyFailureException e) {
                log.debug("Stash failed to merge");
                addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                throw new MergeFailure(git.status().call().getConflicting(), filesChangedInCommit);
            }
        }

        return filesChangedInCommit;
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}