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

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

Introduction

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

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

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

License:Open Source License

private static Ref getHead(Git targetGit) throws IOException {
    return targetGit.getRepository().getRef(Constants.HEAD);
}

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

License:Open Source License

private Git cloneRepository(Git sourceGit) throws GitAPIException, IOException {
    final String sourceURL = sourceGit.getRepository().getDirectory().getParentFile().toURI().toString();
    return Git.cloneRepository().setURI(sourceURL).setDirectory(folder.newFolder("target")).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;//w  ww .ja  v a2s  .c  o m
}

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

License:Open Source License

private static void log(Git git) throws GitAPIException {
    File gitDirectory = git.getRepository().getDirectory().getParentFile();
    LOGGER.info("Log for {}", gitDirectory.getName());
    for (RevCommit commit : git.log().call()) {
        LOGGER.info("{} {}", commit.getName(), commit.getFullMessage());
    }/*  w ww  .  j  a  v  a2  s. c o  m*/
}

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

License:Apache License

private File getPomFile(Git git) {
    return new File(git.getRepository().getWorkTree(), POM_XML);
}

From source file:getgitdata.JGitDiff.java

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:/Users/Masud/Documents/GitHub/tomcat");
    Git git = Git.open(gitWorkDir);

    String newHash = "278a36a";
    String oldHash = "1b46e37b92705159ddc22fd8a28ee1d2b7499072";

    //ObjectId headId = git.getRepository().resolve("HEAD^{tree}");
    // ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId oldId = git.getRepository().resolve(newHash + "^^{tree}");
    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset(reader, oldId);/*from   ww w  . jav a2  s .  co  m*/
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(reader, headId);

    List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(out);
    df.setRepository(git.getRepository());
    int count = 0;
    for (DiffEntry diff : diffs) {
        count++;
        System.out.println("DIff: " + diff.toString());
        df.format(diff);

        // diff.getOldId();
        String diffText = out.toString("UTF-8");
        System.out.println(diffText);
        out.reset();
    }
    System.out.println("Count: " + count);
}

From source file:GitBackend.GitAPI.java

License:Apache License

private static HashMap getRevisionsByLog(Repository repository, String filePath) {

    HashMap commitMap = new HashMap<String, DateTime>();

    Git git = new Git(repository);
    LogCommand logCommand = null;//from w w w  .ja v  a 2s.c  o m
    try {
        logCommand = git.log().add(git.getRepository().resolve(Constants.HEAD)).addPath(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        for (RevCommit revCommit : logCommand.call()) {
            DateTime commitDate = new DateTime(1000L * revCommit.getCommitTime());
            // Store commit hash and date
            commitMap.put(revCommit.getName(), commitDate);
        }
    } catch (GitAPIException e) {
        e.printStackTrace();
    }

    return commitMap;
}

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

License:Apache License

/**
 * @throws MergeFailure/*from  w ww . j  a v  a 2 s.  c  o  m*/
 * @throws AuthenticationException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateFromRemote(java.io.File, java.lang.String, java.lang.String,
 * gov.va.isaac.interfaces.sync.MergeFailOption)
 */
@Override
public Set<String> updateFromRemote(String username, String password, MergeFailOption mergeFailOption)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    Set<String> filesChangedDuringPull;
    try {
        log.info("update from remote called ");

        Git git = getGit();

        log.debug("Fetching from remote");

        if (git.status().call().getConflicting().size() > 0) {
            log.info("Previous merge failure not yet resolved");
            throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>());
        }

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));
        log.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages());

        ObjectId masterIdBeforeMerge = git.getRepository().getRef("master").getObjectId();
        if (git.getRepository().getRef("refs/remotes/origin/master").getObjectId().getName()
                .equals(masterIdBeforeMerge.getName())) {
            log.info("No changes to merge");
            return new HashSet<String>();
        }

        RevCommit stash = null;
        if (git.status().call().getUncommittedChanges().size() > 0) {
            log.info("Stashing uncommitted changes");
            stash = git.stashCreate().call();
        }

        {
            log.debug("Merging from remotes/origin/master");
            MergeResult mr = git.merge().include(git.getRepository().getRef("refs/remotes/origin/master"))
                    .call();
            AnyObjectId headAfterMergeID = mr.getNewHead();

            if (!mr.getMergeStatus().isSuccessful()) {
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE
                            + (stash == null ? ":NO_STASH" : STASH_MARKER + stash.getName()), git);
                    //We can use the status here - because we already stashed the stuff that they had uncommitted above.
                    throw new MergeFailure(mr.getConflicts().keySet(),
                            git.status().call().getUncommittedChanges());
                } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : mr.getConflicts().keySet()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving merge failures with option {}", mergeFailOption);
                    filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL,
                            (stash == null ? null : stash.getName()), resolutions);
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            } else {
                //Conflict free merge - or perhaps, no merge at all.
                if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) {
                    log.debug("Merge didn't result in a commit - no incoming changes");
                    filesChangedDuringPull = new HashSet<>();
                } else {
                    filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge,
                            headAfterMergeID);
                }
            }
        }

        if (stash != null) {
            log.info("Replaying stash");
            try {
                git.stashApply().setStashRef(stash.getName()).call();
                log.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (StashApplyFailureException e) {
                log.debug("Stash failed to merge");
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                    throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull);
                }

                else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : git.status().call().getConflicting()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving stash apply merge failures with option {}", mergeFailOption);
                    resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions);
                    //When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above.
                    for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
                        if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                            filesChangedDuringPull.remove(r.getKey());
                        }
                    }
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            }
        }
        log.info("Files changed during updateFromRemote: {}", filesChangedDuringPull);
        return filesChangedDuringPull;
    } catch (CheckoutConflictException e) {
        log.error("Unexpected", e);
        throw new IOException(
                "A local file exists (but is not yet added to source control) which conflicts with a file from the server."
                        + "  Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.",
                e);
    } 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

/**
 * @throws MergeFailure /* w w w .ja  va  2s  .c  o m*/
 * @throws NoWorkTreeException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#resolveMergeFailures(java.io.File, java.util.Map)
 */
@Override
public Set<String> resolveMergeFailures(Map<String, MergeFailOption> resolutions)
        throws IllegalArgumentException, IOException, NoWorkTreeException, MergeFailure {
    log.info("resolve merge failures called - resolutions: {}", resolutions);
    try {
        Git git = getGit();

        List<Note> notes = git.notesList().call();

        Set<String> conflicting = git.status().call().getConflicting();
        if (conflicting.size() == 0) {
            throw new IllegalArgumentException("You do not appear to have any conflicting files");
        }
        if (conflicting.size() != resolutions.size()) {
            throw new IllegalArgumentException(
                    "You must provide a resolution for each conflicting file.  Files in conflict: "
                            + conflicting);
        }
        for (String s : conflicting) {
            if (!resolutions.containsKey(s)) {
                throw new IllegalArgumentException("No conflit resolution specified for file " + s
                        + ".  Resolutions must be specified for all files");
            }
        }

        if (notes == null || notes.size() == 0) {
            throw new IllegalArgumentException(
                    "The 'note' that is required for tracking state is missing.  This merge failure must be resolved on the command line");
        }

        String noteValue = new String(git.getRepository().open(notes.get(0).getData()).getBytes());

        MergeFailType mergeFailType;
        if (noteValue.startsWith(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE)) {
            mergeFailType = MergeFailType.REMOTE_TO_LOCAL;
        } else if (noteValue.startsWith(NOTE_FAILED_MERGE_HAPPENED_ON_STASH)) {
            mergeFailType = MergeFailType.STASH_TO_LOCAL;
        } else {
            throw new IllegalArgumentException(
                    "The 'note' that is required for tracking state contains an unexpected value of '"
                            + noteValue + "'");
        }
        String stashIdToApply = null;
        if (noteValue.contains(STASH_MARKER)) {
            stashIdToApply = noteValue.substring(noteValue.indexOf(STASH_MARKER) + STASH_MARKER.length());
        }

        return resolveMergeFailures(mergeFailType, stashIdToApply, resolutions);
    } catch (GitAPIException | LargeObjectException 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  w  w  . j ava 2s .co m
        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);
    }
}