private DhtRef doPeel(final Ref leaf) throws MissingObjectException, IOException {
    RevWalk rw = new RevWalk(getRepository());
    try {
      DhtReader ctx = (DhtReader) rw.getObjectReader();
      RevObject obj = rw.parseAny(leaf.getObjectId());
      RefData.Builder d = RefData.newBuilder(((DhtRef) leaf).getRefData());

      ChunkKey oKey = ctx.findChunk(leaf.getObjectId());
      if (oKey != null) d.getTargetBuilder().setChunkKey(oKey.asString());
      else d.getTargetBuilder().clearChunkKey();

      if (obj instanceof RevTag) {
        ObjectId pId = rw.peel(obj);
        d.getPeeledBuilder().setObjectName(pId.name());

        ChunkKey pKey = ctx.findChunk(pId);
        if (pKey != null) d.getPeeledBuilder().setChunkKey(pKey.asString());
        else d.getPeeledBuilder().clearChunkKey();
      } else {
        d.clearPeeled();
      }

      d.setIsPeeled(true);
      d.setSequence(d.getSequence() + 1);
      return new DhtObjectIdRef(leaf.getName(), d.build());
    } finally {
      rw.release();
    }
  }
Beispiel #2
0
  // ----------------------------------------------------------
  public GitRef createTagForObject(String name, ObjectId objectId) {
    TagCommand tag = new Git(repository).tag();
    tag.setName(name);

    if (objectId == null) {
      tag.setObjectId(null);
    } else {
      RevWalk revWalk = new RevWalk(repository);

      try {
        RevCommit commit = revWalk.parseCommit(objectId);
        tag.setObjectId(commit);
      } catch (Exception e) {
        return null;
      } finally {
        revWalk.release();
      }
    }

    try {
      tag.call();
      return refWithName(Constants.R_TAGS + name);
    } catch (Exception e) {
      return null;
    }
  }
Beispiel #3
0
  /**
   * Parses an array of Git commits and returns an array of commits that affected the specified
   * object.
   *
   * @param repository the Git repository
   * @param commitIds the Git commit IDs to parse
   * @param path the object affected
   * @return an array of {@link GitCommit} objects representing the commits
   */
  public NSArray<GitCommit> commitsWithIds(NSArray<ObjectId> commitIds, String path) {
    try {
      RevWalk rw = new RevWalk(repository);

      try {
        rw.sort(RevSort.COMMIT_TIME_DESC);

        if (path != null) {
          rw.setTreeFilter(
              AndTreeFilter.create(PathSuffixFilter.create(path), TreeFilter.ANY_DIFF));
        } else {
          rw.setTreeFilter(TreeFilter.ALL);
        }

        for (ObjectId commitId : commitIds) {
          rw.markStart(rw.parseCommit(commitId));
        }

        NSMutableArray<GitCommit> commits = new NSMutableArray<GitCommit>();

        for (RevCommit commit : rw) {
          commits.add(new GitCommit(commit));
        }

        return commits;
      } finally {
        rw.release();
      }
    } catch (Exception e) {
      log.error("An exception occurred while parsing the commit: ", e);
      return null;
    }
  }
Beispiel #4
0
  public void buildCompositeCommits() throws IOException {
    revWalk = new RevWalk(repository);
    ByteArrayOutputStream diffTexts = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(diffTexts);
    df.setRepository(repository);
    df.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    df.setContext(0);
    df.setDiffAlgorithm(DiffAlgorithm.getAlgorithm(SupportedAlgorithm.HISTOGRAM));
    df.setDetectRenames(true);
    for (int idx = 0; idx < _commits.size(); idx++) {
      RevCommit commit = revWalk.parseCommit(_commits.get(idx));
      int p_count = commit.getParentCount();
      if (p_count == 0) {
        throw new RuntimeException("commit with no parent ?!?!");
      }
      RevCommit p = revWalk.parseCommit(commit.getParent(0).getId());
      List<DiffEntry> diffs = df.scan(p.getTree(), commit.getTree());
      for (DiffEntry d : diffs) {
        CompositeDiff cd = new CompositeDiff(d, commit);

        if (ParsingUtils.isSourceFile(d.getOldPath())
            || ParsingUtils.isSourceFile(d.getNewPath())) {
          extractCodeEdits(diffTexts, df, d, cd);
        }
        _diffs.add(cd);
      }
    }
    revWalk.release();
  }
Beispiel #5
0
  @SuppressWarnings("unchecked")
  void analyzeForkTree(ForkEntry fe) throws Exception {

    RevWalk walk = null;

    String gitDirPath =
        GitWorks.gits_out_dir
            + GitWorks.getSafeName(fe)
            + ((GitWorks.bare == true) ? ".git" : "/.git");
    String treeDirPath = GitWorks.trees_out_dir + GitWorks.getSafeName(fe);

    try {
      // with git.init() it is not possible to specify a different tree path!!
      // git = Git.init().setBare(bare).setDirectory(new File(gitDirPath)).call();
      git = Git.wrap(createRepo(treeDirPath, gitDirPath));
      //    System.out.println(printRepoInfo());

      if (GitWorks.anew) {
        addRemotes(git, fe, Integer.MAX_VALUE);
      }

      name = GitWorks.getSafeName(fe);
      id = fe.getRetrievalTimestamp();
      if (allBranches == null) buildBranchesMap(fe.howManyForks());

      walk = new RevWalk(git.getRepository());

      if (allCommits == null) {
        init();
        getCommitsInB(walk, false);
        tailor();
      }
      getCommitsInB(walk, true);
      getCommitsInR(walk, false);
      getCommitsInR(walk, true);
      getCommitsNotInR(walk);

      authOfComInB = computePersonFreq(comInB);
      authOfComOnlyInB = computePersonFreq(comOnlyInB);
      authOfComInF = computePersonFreq(comInF);
      authOfComOnlyInF = computePersonFreq(comOnlyInF);
      authOfComNotInF = computePersonFreq(comNotInF);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (walk != null) {
        walk.dispose();
        walk.release();
        walk = null;
      }
      if (git != null) {
        git.getRepository().close();
        git = null;
      }
      System.gc();
    }
  }
 private ObjectId getCommitObjectId(Repository db, ObjectId oid)
     throws MissingObjectException, IncorrectObjectTypeException, IOException {
   RevWalk walk = new RevWalk(db);
   try {
     return walk.parseCommit(oid);
   } finally {
     walk.release();
   }
 }
  private boolean cherryPick(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitToCherryPick)
      throws ServletException, JSONException {
    RevWalk revWalk = new RevWalk(db);
    try {

      Ref headRef = db.getRef(Constants.HEAD);
      if (headRef == null)
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when cherry-picking.",
                null));
      RevCommit head = revWalk.parseCommit(headRef.getObjectId());

      ObjectId objectId = db.resolve(commitToCherryPick);
      Git git = new Git(db);
      CherryPickResult cherryPickResult = git.cherryPick().include(objectId).call();
      RevCommit newHead = cherryPickResult.getNewHead();

      JSONObject result = new JSONObject();
      result.put(GitConstants.KEY_RESULT, cherryPickResult.getStatus().name());
      result.put(GitConstants.KEY_HEAD_UPDATED, !head.equals(newHead));
      OrionServlet.writeJSONResponse(
          request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
      return true;
    } catch (IOException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when cherry-picking.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when cherry-picking.",
              e));
    } finally {
      revWalk.release();
    }
  }
  private void dispose() {
    walk.release();
    Display.getDefault()
        .asyncExec(
            new Runnable() {

              public void run() {
                loadedCommits.dispose();
              }
            });
  }
Beispiel #9
0
 private RevCommit parseCommit(final Ref branch)
     throws MissingObjectException, IncorrectObjectTypeException, IOException {
   final RevWalk rw = new RevWalk(db);
   final RevCommit commit;
   try {
     commit = rw.parseCommit(branch.getObjectId());
   } finally {
     rw.release();
   }
   return commit;
 }
Beispiel #10
0
 /**
  * Checks if a file with the given path exists in the HEAD tree
  *
  * @param path
  * @return true if the file exists
  * @throws IOException
  */
 private boolean inHead(String path) throws IOException {
   ObjectId headId = db.resolve(Constants.HEAD);
   RevWalk rw = new RevWalk(db);
   TreeWalk tw = null;
   try {
     tw = TreeWalk.forPath(db, path, rw.parseTree(headId));
     return tw != null;
   } finally {
     rw.release();
     rw.dispose();
     if (tw != null) tw.release();
   }
 }
Beispiel #11
0
  private void initRevPool(boolean reverse) {
    if (queue != null) throw new IllegalStateException();

    if (revPool != null) revPool.release();

    if (reverse) revPool = new ReverseWalk(getRepository());
    else revPool = new RevWalk(getRepository());

    revPool.setRetainBody(true);
    SEEN = revPool.newFlag("SEEN"); // $NON-NLS-1$
    reader = revPool.getObjectReader();
    treeWalk = new TreeWalk(reader);
    treeWalk.setRecursive(true);
  }
 private RevCommit findCommit(final String revstr, final Repository repository) {
   final RevWalk walk = new RevWalk(repository);
   RevCommit commit = null;
   try {
     commit = walk.parseCommit(repository.resolve(revstr));
   } catch (final MissingObjectException e1) {
     LOGGER.warning("Could not find commit with id: " + revstr);
   } catch (final IncorrectObjectTypeException e1) {
     LOGGER.warning("The provided rev is not a commit: " + revstr);
   } catch (final Exception ignore) {
   } finally {
     walk.release();
   }
   return commit;
 }
    @Override
    public ChangeKind load(Key key) throws IOException {
      if (Objects.equal(key.prior, key.next)) {
        return ChangeKind.NO_CODE_CHANGE;
      }

      RevWalk walk = new RevWalk(key.repo);
      try {
        RevCommit prior = walk.parseCommit(key.prior);
        walk.parseBody(prior);
        RevCommit next = walk.parseCommit(key.next);
        walk.parseBody(next);

        if (!next.getFullMessage().equals(prior.getFullMessage())) {
          if (next.getTree() == prior.getTree() && isSameParents(prior, next)) {
            return ChangeKind.NO_CODE_CHANGE;
          } else {
            return ChangeKind.REWORK;
          }
        }

        if (prior.getParentCount() != 1 || next.getParentCount() != 1) {
          // Trivial rebases done by machine only work well on 1 parent.
          return ChangeKind.REWORK;
        }

        if (next.getTree() == prior.getTree() && isSameParents(prior, next)) {
          return ChangeKind.TRIVIAL_REBASE;
        }

        // A trivial rebase can be detected by looking for the next commit
        // having the same tree as would exist when the prior commit is
        // cherry-picked onto the next commit's new first parent.
        ThreeWayMerger merger =
            MergeUtil.newThreeWayMerger(
                key.repo, MergeUtil.createDryRunInserter(), key.strategyName);
        merger.setBase(prior.getParent(0));
        if (merger.merge(next.getParent(0), prior)
            && merger.getResultTreeId().equals(next.getTree())) {
          return ChangeKind.TRIVIAL_REBASE;
        } else {
          return ChangeKind.REWORK;
        }
      } finally {
        key.repo = null;
        walk.release();
      }
    }
Beispiel #14
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    handleAuth(req);
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter out = resp.getWriter();
    try {
      String pathInfo = req.getPathInfo();
      Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
      Matcher matcher = pattern.matcher(pathInfo);
      matcher.matches();
      String projectName = null;
      String refName = null;
      String filePath = null;
      if (matcher.groupCount() > 0) {
        projectName = matcher.group(1);
        refName = matcher.group(2);
        filePath = matcher.group(3);
        if (projectName == null || projectName.equals("")) {
          projectName = null;
        } else {
          projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
        }
        if (refName == null || refName.equals("")) {
          refName = null;
        } else {
          refName = java.net.URLDecoder.decode(refName, "UTF-8");
        }
        if (filePath == null || filePath.equals("")) {
          filePath = null;
        } else {
          filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
        }
      }
      if (projectName != null) {
        if (filePath == null) filePath = "";
        NameKey projName = NameKey.parse(projectName);

        ProjectControl control;
        try {
          control = projControlFactory.controlFor(projName);
          if (!control.isVisible()) {
            log.debug("Project not visible!");
            resp.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "You need to be logged in to see private projects");
            return;
          }
        } catch (NoSuchProjectException e1) {
        }
        Repository repo = repoManager.openRepository(projName);
        if (refName == null) {
          JSONArray contents = new JSONArray();
          List<Ref> call;
          try {
            call = new Git(repo).branchList().call();
            Git git = new Git(repo);
            for (Ref ref : call) {
              JSONObject jsonObject = new JSONObject();
              try {
                jsonObject.put("name", ref.getName());
                jsonObject.put("type", "ref");
                jsonObject.put("size", "0");
                jsonObject.put("path", "");
                jsonObject.put("project", projectName);
                jsonObject.put("ref", ref.getName());
                lastCommit(git, null, ref.getObjectId(), jsonObject);
              } catch (JSONException e) {
              }
              contents.put(jsonObject);
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
          } catch (GitAPIException e) {
          }
        } else {
          Ref head = repo.getRef(refName);
          if (head == null) {
            JSONArray contents = new JSONArray();
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
            return;
          }
          RevWalk walk = new RevWalk(repo);
          // add try catch to catch failures
          Git git = new Git(repo);
          RevCommit commit = walk.parseCommit(head.getObjectId());
          RevTree tree = commit.getTree();
          TreeWalk treeWalk = new TreeWalk(repo);
          treeWalk.addTree(tree);
          treeWalk.setRecursive(false);
          if (!filePath.equals("")) {
            PathFilter pathFilter = PathFilter.create(filePath);
            treeWalk.setFilter(pathFilter);
          }
          if (!treeWalk.next()) {
            CanonicalTreeParser canonicalTreeParser =
                treeWalk.getTree(0, CanonicalTreeParser.class);
            JSONArray contents = new JSONArray();
            if (canonicalTreeParser != null) {
              while (!canonicalTreeParser.eof()) {
                String path = canonicalTreeParser.getEntryPathString();
                FileMode mode = canonicalTreeParser.getEntryFileMode();
                listEntry(
                    path,
                    mode.equals(FileMode.TREE) ? "dir" : "file",
                    "0",
                    path,
                    projectName,
                    head.getName(),
                    git,
                    contents);
                canonicalTreeParser.next();
              }
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          } else {
            // if (treeWalk.isSubtree()) {
            // treeWalk.enterSubtree();
            // }

            JSONArray contents = getListEntries(treeWalk, repo, git, head, filePath, projectName);
            String response = contents.toString();

            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          }
          walk.release();
          treeWalk.release();
        }
      }
    } catch (RepositoryNotFoundException e) {
      handleException(resp, e, 400);
    } catch (MissingObjectException e) {
      // example "Missing unknown 7035305927ca125757ecd8407e608f6dcf0bd8a5"
      // usually indicative of being unable to locate a commit from a submodule
      log.error(e.getMessage(), e);
      String msg =
          e.getMessage()
              + ".  This exception could have been caused by the use of a git submodule, "
              + "which is currently not supported by the repository browser.";
      handleException(resp, new Exception(msg), 501);
    } catch (IOException e) {
      handleException(resp, e, 500);
    } finally {
      out.close();
    }
  }
  private boolean revert(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitToRevert)
      throws ServletException, JSONException {
    RevWalk revWalk = new RevWalk(db);
    try {

      Ref headRef = db.getRef(Constants.HEAD);
      if (headRef == null)
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An error occured when reverting.",
                null));

      ObjectId objectId = db.resolve(commitToRevert);
      Git git = new Git(db);

      RevertCommand revertCommand = git.revert().include(objectId);
      RevCommit revertedCommit = revertCommand.call();

      if (revertedCommit == null) {
        JSONObject result = new JSONObject();
        result.put(GitConstants.KEY_RESULT, "FAILURE"); // $NON-NLS-1$
        OrionServlet.writeJSONResponse(
            request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;
      }

      JSONObject result = new JSONObject();
      result.put(GitConstants.KEY_RESULT, "OK"); // $NON-NLS-1$
      OrionServlet.writeJSONResponse(
          request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
      return true;
    } catch (IOException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when reverting.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when reverting.",
              e));
    } finally {
      revWalk.release();
    }
  }
Beispiel #16
0
  public static CherryPickResult cherryPickNoMerge(final Git git, Ref src)
      throws GitAPIException, CantMergeCommitWithZeroParentsException {
    // Does the same as the original git-cherryPick
    // except commiting after running merger
    Repository repo = git.getRepository();

    RevCommit newHead = null;
    List<Ref> cherryPickedRefs = new LinkedList<Ref>();

    RevWalk revWalk = new RevWalk(repo);
    try {
      // get the head commit
      Ref headRef = repo.getRef(Constants.HEAD);
      if (headRef == null)
        throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
      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().canOnlyCherryPickCommitsWithOneParent,
                srcCommit.name(),
                Integer.valueOf(srcCommit.getParentCount())));

      RevCommit srcParent = srcCommit.getParent(0);
      revWalk.parseHeaders(srcParent);

      ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE.newMerger(repo);
      merger.setWorkingTreeIterator(new FileTreeIterator(repo));
      merger.setBase(srcParent.getTree());
      if (merger.merge(headCommit, srcCommit)) {
        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 CherryPickResult.CONFLICT;
      }
    } catch (IOException e) {
      throw new JGitInternalException(
          MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e),
          e);
    } finally {
      revWalk.release();
    }

    return new CherryPickResult(newHead, cherryPickedRefs);
  }
Beispiel #17
0
  private void buildTrees(final boolean buildMaps) {
    final Object[] wsExpaneded = tree.getExpandedElements();
    final ISelection wsSel = tree.getSelection();

    tree.setInput(null);

    if (baseVersion == null) {
      tree.setContentProvider(new WorkbenchTreeContentProvider());
      tree.setComparator(new WorkbenchTreeComparator());
      tree.setLabelProvider(new WorkbenchTreeLabelProvider());
    } else {
      tree.setContentProvider(new PathNodeContentProvider());
      tree.setComparator(new PathNodeTreeComparator());
      tree.setLabelProvider(new PathNodeLabelProvider());
    }
    for (IWorkbenchAction action : actionsToDispose) action.setEnabled(false);

    showEquals =
        Activator.getDefault()
            .getPreferenceStore()
            .getBoolean(UIPreferences.TREE_COMPARE_SHOW_EQUALS);
    final Repository repo;
    if (input instanceof IResource[]) {
      repositoryMapping = RepositoryMapping.getMapping(((IResource[]) input)[0]);
      if (repositoryMapping == null || repositoryMapping.getRepository() == null) return;
      repo = repositoryMapping.getRepository();
    } else if (input instanceof Repository) {
      repo = (Repository) input;
    } else return;
    final RevCommit baseCommit;
    final RevCommit compareCommit;
    RevWalk rw = new RevWalk(repo);
    try {
      ObjectId commitId = repo.resolve(compareVersion);
      compareCommit = commitId != null ? rw.parseCommit(commitId) : null;
      if (baseVersion == null) baseCommit = null;
      else {
        commitId = repo.resolve(baseVersion);
        baseCommit = rw.parseCommit(commitId);
      }
    } catch (IOException e) {
      Activator.handleError(e.getMessage(), e, true);
      return;
    } finally {
      rw.release();
    }
    showBusy(true);
    try {
      // this does the hard work...
      new ProgressMonitorDialog(getViewSite().getShell())
          .run(
              true,
              true,
              new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  try {
                    if (buildMaps) buildMaps(repo, baseCommit, compareCommit, monitor);
                    PlatformUI.getWorkbench()
                        .getDisplay()
                        .asyncExec(
                            new Runnable() {
                              public void run() {
                                tree.setInput(input);
                                tree.setExpandedElements(wsExpaneded);
                                tree.setSelection(wsSel);
                                updateControls();
                              }
                            });
                  } catch (IOException e) {
                    throw new InvocationTargetException(e);
                  }
                }
              });
    } catch (InvocationTargetException e) {
      Activator.handleError(e.getTargetException().getMessage(), e.getTargetException(), true);
    } catch (InterruptedException e) {
      input = null;
    } finally {
      showBusy(false);
    }
  }
Beispiel #18
0
 /** Release the current blame session. */
 public void release() {
   revPool.release();
   queue = null;
   outCandidate = null;
   outRegion = null;
 }
Beispiel #19
0
  /**
   * Executes the {@code commit} command with all the options and parameters collected by the setter
   * methods of this class. Each instance of this class should only be used for one invocation of
   * the command (means: one call to {@link #call()})
   *
   * @return a {@link RevCommit} object representing the successful commit.
   * @throws NoHeadException when called on a git repo without a HEAD reference
   * @throws NoMessageException when called without specifying a commit message
   * @throws UnmergedPathsException when the current index contained unmerged paths (conflicts)
   * @throws ConcurrentRefUpdateException when HEAD or branch ref is updated concurrently by someone
   *     else
   * @throws WrongRepositoryStateException when repository is not in the right state for committing
   */
  public RevCommit call()
      throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
          ConcurrentRefUpdateException, WrongRepositoryStateException {
    checkCallable();

    RepositoryState state = repo.getRepositoryState();
    if (!state.canCommit())
      throw new WrongRepositoryStateException(
          MessageFormat.format(JGitText.get().cannotCommitOnARepoWithState, state.name()));
    processOptions(state);

    try {
      if (all && !repo.isBare() && repo.getWorkTree() != null) {
        Git git = new Git(repo);
        try {
          git.add().addFilepattern(".").setUpdate(true).call();
        } catch (NoFilepatternException e) {
          // should really not happen
          throw new JGitInternalException(e.getMessage(), e);
        }
      }

      Ref head = repo.getRef(Constants.HEAD);
      if (head == null)
        throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);

      // determine the current HEAD and the commit it is referring to
      ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
      if (headId == null && amend)
        throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible);

      if (headId != null)
        if (amend) {
          RevCommit previousCommit = new RevWalk(repo).parseCommit(headId);
          RevCommit[] p = previousCommit.getParents();
          for (int i = 0; i < p.length; i++) parents.add(0, p[i].getId());
          if (author == null) author = previousCommit.getAuthorIdent();
        } else {
          parents.add(0, headId);
        }

      // lock the index
      DirCache index = repo.lockDirCache();
      try {
        if (!only.isEmpty()) index = createTemporaryIndex(headId, index);

        ObjectInserter odi = repo.newObjectInserter();
        try {
          // Write the index as tree to the object database. This may
          // fail for example when the index contains unmerged paths
          // (unresolved conflicts)
          ObjectId indexTreeId = index.writeTree(odi);

          if (insertChangeId) insertChangeId(indexTreeId);

          // Create a Commit object, populate it and write it
          CommitBuilder commit = new CommitBuilder();
          commit.setCommitter(committer);
          commit.setAuthor(author);
          commit.setMessage(message);

          commit.setParentIds(parents);
          commit.setTreeId(indexTreeId);
          ObjectId commitId = odi.insert(commit);
          odi.flush();

          RevWalk revWalk = new RevWalk(repo);
          try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = repo.updateRef(Constants.HEAD);
            ru.setNewObjectId(commitId);
            if (reflogComment != null) {
              ru.setRefLogMessage(reflogComment, false);
            } else {
              String prefix = amend ? "commit (amend): " : "commit: ";
              ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false);
            }
            if (headId != null) ru.setExpectedOldObjectId(headId);
            else ru.setExpectedOldObjectId(ObjectId.zeroId());
            Result rc = ru.forceUpdate();
            switch (rc) {
              case NEW:
              case FORCED:
              case FAST_FORWARD:
                {
                  setCallable(false);
                  if (state == RepositoryState.MERGING_RESOLVED) {
                    // Commit was successful. Now delete the files
                    // used for merge commits
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                  } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeCherryPickHead(null);
                  }
                  return revCommit;
                }
              case REJECTED:
              case LOCK_FAILURE:
                throw new ConcurrentRefUpdateException(
                    JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
              default:
                throw new JGitInternalException(
                    MessageFormat.format(
                        JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc));
            }
          } finally {
            revWalk.release();
          }
        } finally {
          odi.release();
        }
      } finally {
        index.unlock();
      }
    } catch (UnmergedPathException e) {
      throw new UnmergedPathsException(e);
    } catch (IOException e) {
      throw new JGitInternalException(
          JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
    }
  }
Beispiel #20
0
  /**
   * Execute the receive task on the socket.
   *
   * @param input raw input to read client commands and pack data from. Caller must ensure the input
   *     is buffered, otherwise read performance may suffer.
   * @param output response back to the Git network client. Caller must ensure the output is
   *     buffered, otherwise write performance may suffer.
   * @param messages secondary "notice" channel to send additional messages out through. When run
   *     over SSH this should be tied back to the standard error channel of the command execution.
   *     For most other network connections this should be null.
   * @throws IOException
   */
  public void receive(
      final InputStream input, final OutputStream output, final OutputStream messages)
      throws IOException {
    try {
      rawIn = input;
      rawOut = output;
      msgOut = messages;

      if (timeout > 0) {
        final Thread caller = Thread.currentThread();
        timer = new InterruptTimer(caller.getName() + "-Timer");
        timeoutIn = new TimeoutInputStream(rawIn, timer);
        TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
        timeoutIn.setTimeout(timeout * 1000);
        o.setTimeout(timeout * 1000);
        rawIn = timeoutIn;
        rawOut = o;
      }

      pckIn = new PacketLineIn(rawIn);
      pckOut = new PacketLineOut(rawOut);
      pckOut.setFlushOnEnd(false);

      enabledCapablities = new HashSet<String>();
      commands = new ArrayList<ReceiveCommand>();

      service();
    } finally {
      walk.release();
      try {
        if (sideBand) {
          // If we are using side band, we need to send a final
          // flush-pkt to tell the remote peer the side band is
          // complete and it should stop decoding. We need to
          // use the original output stream as rawOut is now the
          // side band data channel.
          //
          ((SideBandOutputStream) msgOut).flushBuffer();
          ((SideBandOutputStream) rawOut).flushBuffer();

          PacketLineOut plo = new PacketLineOut(output);
          plo.setFlushOnEnd(false);
          plo.end();
        }

        if (biDirectionalPipe) {
          // If this was a native git connection, flush the pipe for
          // the caller. For smart HTTP we don't do this flush and
          // instead let the higher level HTTP servlet code do it.
          //
          if (!sideBand && msgOut != null) msgOut.flush();
          rawOut.flush();
        }
      } finally {
        unlockPack();
        timeoutIn = null;
        rawIn = null;
        rawOut = null;
        msgOut = null;
        pckIn = null;
        pckOut = null;
        refs = null;
        enabledCapablities = null;
        commands = null;
        if (timer != null) {
          try {
            timer.terminate();
          } finally {
            timer = null;
          }
        }
      }
    }
  }
 @Override
 public void close() {
   walk.release();
   super.close();
 }