Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2012 Red Hat, Inc. and/or its affiliates.
   *
   * Licensed under the Eclipse Public License version 1.0, available at
   * http://www.eclipse.org/legal/epl-v10.html
   */
  
  package org.jboss.forge.git;
  
 import java.util.List;
 
 import  org.jboss.forge.parser.java.util.Strings;
Convenience tools for interacting with the Git version control system.

Author(s):
Lincoln Baxter, III
Jevgeni Zelenkov
 
 public abstract class GitUtils
 {
    public static Git clone(final DirectoryResource dirfinal String repoUrithrows GitAPIException
    {
       CloneCommand clone = Git.cloneRepository().setURI(repoUri)
                .setDirectory(dir.getUnderlyingResourceObject());
       Git git = clone.call();
       return git;
    }
 
    public static Git git(final DirectoryResource dirthrows IOException
    {
       return new Git(db.build());
    }
 
    public static Ref checkout(final Git gitfinal String remotefinal boolean createBranch,
             final SetupUpstreamMode modefinal boolean force)
             throws GitAPIException
    {
       CheckoutCommand checkout = git.checkout();
       checkout.setCreateBranch(createBranch);
       checkout.setName(remote);
       checkout.setForce(force);
       checkout.setUpstreamMode(mode);
       return checkout.call();
    }
 
    public static Ref checkout(final Git gitfinal Ref localReffinal boolean createBranch,
             final SetupUpstreamMode modefinal boolean force)
             throws GitAPIException
    {
       CheckoutCommand checkout = git.checkout();
       checkout.setName(Repository.shortenRefName(localRef.getName()));
       checkout.setForce(force);
       checkout.setUpstreamMode(mode);
       return checkout.call();
    }
   public static FetchResult fetch(final Git gitfinal String remotefinal String refSpecfinal int timeout,
            final boolean fsckfinal boolean dryRun,
            final boolean thin,
            final boolean prunethrows GitAPIException
   {
      FetchCommand fetch = git.fetch();
      fetch.setCheckFetchedObjects(fsck);
      fetch.setRemoveDeletedRefs(prune);
      if (refSpec != null)
         fetch.setRefSpecs(new RefSpec(refSpec));
      if (timeout >= 0)
         fetch.setTimeout(timeout);
      fetch.setDryRun(dryRun);
      fetch.setRemote(remote);
      fetch.setThin(thin);
      fetch.setProgressMonitor(new TextProgressMonitor());
      FetchResult result = fetch.call();
      return result;
   }

   
Initialize a new git repository.

Parameters:
dir The directory in which to create a new .git/ folder and repository.
   public static Git init(final DirectoryResource dirthrows IOException
   {
      FileResource<?> gitDir = dir.getChildDirectory(".git").reify(FileResource.class);
      gitDir.mkdirs();
      Git git = new Git(db.build());
      git.getRepository().create();
      return git;
   }
   public static PullResult pull(final Git gitfinal int timeoutthrows GitAPIException
   {
      PullCommand pull = git.pull();
      if (timeout >= 0)
         pull.setTimeout(timeout);
      pull.setProgressMonitor(new TextProgressMonitor());
      PullResult result = pull.call();
      return result;
   }
   public static List<RefgetRemoteBranches(final Git repothrows GitAPIException
   {
      List<Refresults = new ArrayList<Ref>();
      try
      {
         FetchResult fetch = repo.fetch().setRemote("origin").call();
         Collection<Refrefs = fetch.getAdvertisedRefs();
         for (Ref ref : refs)
         {
            if (ref.getName().startsWith("refs/heads"))
            {
               results.add(ref);
            }
         }
      }
      catch (InvalidRemoteException e)
      {
         e.printStackTrace();
      }
      return results;
   }
   public static List<RefgetLocalBranches(final Git repothrows GitAPIException
   {
      // returns only local branches by default
      return repo.branchList().call();
   }
   public static String getCurrentBranchName(final Git repothrows IOException
   {
      return repo.getRepository().getBranch();
   }
   public static Ref switchBranch(final Git repofinal String branchName)
   {
      Ref switchedBranch = null;
      try
      {
         switchedBranch = repo.checkout().setName(branchName).call();
         if (switchedBranch == null)
            throw new RuntimeException("Couldn't switch to branch " + branchName);
      }
      catch (GitAPIException e)
      {
         e.printStackTrace();
      }
      return switchedBranch;
   }
   public static List<StringgetLogForCurrentBranch(final Git repothrows GitAPIException
   {
      List<Stringresults = new ArrayList<String>();
      Iterable<RevCommitcommits = repo.log().call();
      for (RevCommit commit : commits)
         results.add(commit.getFullMessage());
      return results;
   }
   public static Iterable<RevCommitgetLogForBranch(final Git repoString branchNamethrows GitAPIException,
            IOException
   {
      String oldBranch = repo.getRepository().getBranch();
      repo.checkout().setName(branchName).call();
      Iterable<RevCommitcommits = repo.log().call();
      repo.checkout().setName(oldBranch).call();
      return commits;
   }
   public static void add(final Git repoString filepatternthrows GitAPIException
   {
      repo.add().addFilepattern(filepattern).call();
   }
   public static void addAll(final Git repothrows GitAPIException
   {
      repo.add().addFilepattern(".").call();
   }
   public static void commit(final Git repoString messagethrows GitAPIException
   {
      repo.commit().setMessage(message).call();
   }
   public static void commitAll(final Git repoString messagethrows GitAPIException
   {
      repo.commit().setMessage(message).setAll(true).call();
   }
   public static void stashCreate(final Git repothrows GitAPIException
   {
      repo.stashCreate().call();
   }
   public static void stashApply(final Git repoString... stashRefthrows GitAPIException
   {
      if (stashRef.length >= 1 && !Strings.isNullOrEmpty(stashRef[0]))
      {
         repo.stashApply().setStashRef(stashRef[0]).call();
      }
      else
      {
         repo.stashApply().call();
      }
   }
   public static void stashDrop(final Git repothrows GitAPIException
   {
      repo.stashDrop().call();
   }
   public static void cherryPick(final Git repoRef committhrows GitAPIException
   {
      repo.cherryPick().include(commit).call();
   }
   public static CherryPickResult cherryPickNoMerge(final Git gitRef srcthrows GitAPIException,
   {
      // Does the same as the original git-cherryPick
      // except commiting after running merger
      Repository repo = git.getRepository();
      RevCommit newHead = null;
      List<RefcherryPickedRefs = new LinkedList<Ref>();
      RevWalk revWalk = new RevWalk(repo);
      try
      {
         // get the head commit
         Ref headRef = repo.getRef(.);
         if (headRef == null)
            throw new NoHeadException(
                     JGitText.get().);
         RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
         newHead = headCommit;
         // get the commit to be cherry-picked
         // handle annotated tags
         ObjectId srcObjectId = src.getPeeledObjectId();
         if (srcObjectId == null)
            srcObjectId = src.getObjectId();
         RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
         // get the parent of the commit to cherry-pick
         if (srcCommit.getParentCount() == 0)
            throw new CantMergeCommitWithZeroParentsException("Commit with zero parents cannot be merged");
         if (srcCommit.getParentCount() > 1)
            throw new MultipleParentsNotAllowedException(
                     MessageFormat.format(
                              JGitText.get().,
                              srcCommit.name(),
                              Integer.valueOf(srcCommit.getParentCount())));
         RevCommit srcParent = srcCommit.getParent(0);
         revWalk.parseHeaders(srcParent);
         ResolveMerger merger = (ResolveMerger.
                  .newMerger(repo);
         merger.setWorkingTreeIterator(new FileTreeIterator(repo));
         merger.setBase(srcParent.getTree());
         if (merger.merge(headCommitsrcCommit))
         {
            DirCacheCheckout dco = new DirCacheCheckout(repo,
                     headCommit.getTree(), repo.lockDirCache(),
                     merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout();
            cherryPickedRefs.add(src);
         }
         else
         {
            if (merger.failed())
               return new CherryPickResult(merger.getFailingPaths());
            // there are merge conflicts
            String message = new MergeMessageFormatter()
                     .formatWithConflicts(srcCommit.getFullMessage(),
                              merger.getUnmergedPaths());
            repo.writeCherryPickHead(srcCommit.getId());
            repo.writeMergeCommitMsg(message);
            return .;
         }
      }
      catch (IOException e)
      {
         throw new JGitInternalException(
                  MessageFormat.format(
                           JGitText.get().,
                           e), e);
      }
      finally
      {
         revWalk.release();
      }
      return new CherryPickResult(newHeadcherryPickedRefs);
   }
   public static void resetHard(final Git repoString newBasethrows GitAPIException
   {
      repo.reset().setMode(..).setRef(newBase).call();
   }
   public static Ref createBranch(Git gitString branchNamethrows RefAlreadyExistsExceptionRefNotFoundException,
   {
      Ref newBranch = git.branchCreate().setName(branchName).call();
      if (newBranch == null)
         throw new RuntimeException("Couldn't create new branch " + branchName);
      return newBranch;
   }

   
Closes a Git repository. Invoke this before deleting the Git repository on Windows to prevent errors due to unclosed file handles.

Parameters:
repo The repository to close.
   public static void close(final Git repo)
   {
      if (repo != null)
      {
         repo.getRepository().close();
      }
   }
New to GrepCode? Check out our FAQ X