/*
   * Use the binary git repo and/or the remote service to figure out
   * the new commits made since the last pull on source repository.
   */
  public void findNewCommits() throws GitException {

    // get the history from binary repository
    Git bingit = Git.wrap(binaryRepository);
    RevWalk binwalk = new RevWalk(binaryRepository);

    Iterable<RevCommit> logs;
    try {
      logs = bingit.log().call();
      Iterator<RevCommit> i = logs.iterator();

      while (i.hasNext()) {
        RevCommit commit = binwalk.parseCommit(i.next());
        System.out.println(commit.getFullMessage());
      }

    } catch (NoHeadException e) {
      // TODO Auto-generated catch block
      throw new GitException(e);
    } catch (GitAPIException e) {
      throw new GitException(e);
    } catch (MissingObjectException e) {
      throw new GitException(e);
    } catch (IncorrectObjectTypeException e) {
      throw new GitException(e);
    } catch (IOException e) {
      throw new GitException(e);
    }
  }
 /**
  * Returns a list of references in the repository matching "refs". If the repository is null or
  * empty, an empty list is returned.
  *
  * @param repository
  * @param refs if unspecified, all refs are returned
  * @param fullName if true, /refs/something/yadayadayada is returned. If false, yadayadayada is
  *     returned.
  * @param maxCount if < 0, all references are returned
  * @return list of references
  */
 private static List<RefModel> getRefs(
     Repository repository, String refs, boolean fullName, int maxCount) {
   List<RefModel> list = new ArrayList<RefModel>();
   if (maxCount == 0) {
     return list;
   }
   if (!hasCommits(repository)) {
     return list;
   }
   try {
     Map<String, Ref> map = repository.getRefDatabase().getRefs(refs);
     RevWalk rw = new RevWalk(repository);
     for (Entry<String, Ref> entry : map.entrySet()) {
       Ref ref = entry.getValue();
       RevObject object = rw.parseAny(ref.getObjectId());
       String name = entry.getKey();
       if (fullName && !(refs == null)) {
         name = refs + name;
       }
       list.add(new RefModel(name, ref, object));
     }
     rw.dispose();
     Collections.sort(list);
     Collections.reverse(list);
     if (maxCount > 0 && list.size() > maxCount) {
       list = new ArrayList<RefModel>(list.subList(0, maxCount));
     }
   } catch (IOException e) {
     // todo
     Logger.error(e, e.getMessage());
   }
   return list;
 }
  private void negotiateBegin() throws IOException {
    walk.resetRetain(REACHABLE, ADVERTISED);
    walk.markStart(reachableCommits);
    walk.sort(RevSort.COMMIT_TIME_DESC);
    walk.setRevFilter(
        new RevFilter() {
          @Override
          public RevFilter clone() {
            return this;
          }

          @Override
          public boolean include(final RevWalk walker, final RevCommit c) {
            final boolean remoteKnowsIsCommon = c.has(COMMON);
            if (c.has(ADVERTISED)) {
              // Remote advertised this, and we have it, hence common.
              // Whether or not the remote knows that fact is tested
              // before we added the flag. If the remote doesn't know
              // we have to still send them this object.
              //
              c.add(COMMON);
            }
            return !remoteKnowsIsCommon;
          }
        });
  }
  /**
   * Returns a list of commits since the minimum date starting from the specified object id.
   *
   * @param repository
   * @param objectId if unspecified, HEAD is assumed.
   * @param minimumDate
   * @return list of commits
   */
  public static List<RevCommit> getRevLog(
      Repository repository, String objectId, Date minimumDate) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (!hasCommits(repository)) {
      return list;
    }
    try {
      // resolve branch
      ObjectId branchObject;
      if (objectId == null) {
        branchObject = getDefaultBranch(repository);
      } else {
        branchObject = repository.resolve(objectId);
      }

      RevWalk rw = new RevWalk(repository);
      rw.markStart(rw.parseCommit(branchObject));
      rw.setRevFilter(CommitTimeRevFilter.after(minimumDate));
      Iterable<RevCommit> revlog = rw;
      for (RevCommit rev : revlog) {
        list.add(rev);
      }
      rw.dispose();
    } catch (Throwable t) {
      // todo
      Logger.error(t, t.getMessage());
    }
    return list;
  }
  // 2. Get branch/commit hash for the source repo - the actual source code
  @Test
  public void existsIn() throws IOException {
    // final String repo = "binrepo-devex";
    //  final String repo = "search_raptor_binary";
    // String githubUrl = "https://github.scm.corp.ebay.com/api/v3";
    // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc";

    final String path = "D:\\dev\\devex\\binrepo-devex\\.git";

    File gitDir = new File(path);
    org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(gitDir);
    String branch = repository.getBranch();
    System.out.println(branch);

    RevWalk revWalk = new RevWalk(repository);
    // Pop the most recent commit off from RevWalk
    // RevCommit commit = revWalk.next(); returns null :-(
    // System.out.println(commit);

    ObjectId resolve = repository.resolve(Constants.HEAD);
    RevCommit commit = revWalk.parseCommit(resolve);
    String commitHash = commit.getName();
    System.out.println(commitHash + "\t" + commit.getFullMessage());

    // RefDatabase refDatabase = repository.getRefDatabase();

  }
Exemple #6
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();
  }
Exemple #7
0
  @Override
  public void onContentChanged() {
    super.onContentChanged();
    Log.d(TAG, "updateUI called");
    tagRef = repo().getTags().get(tagName);
    if (objectSummaryView == null) {
      Log.d(TAG, "onContentChanged() : objectSummaryView is null");
      return;
    }

    if (tagRef == null) {
      getSupportActionBar().setTitle("unknown tag");
    } else {
      ObjectId peeledObjectId = repo().peel(tagRef).getPeeledObjectId();
      ObjectId taggedId = peeledObjectId == null ? tagRef.getObjectId() : peeledObjectId;
      RevWalk revWalk = new RevWalk(repo());

      ObjectId tagId = tagRef.getObjectId();
      try {
        final RevObject immediateTagRefObject = revWalk.parseAny(tagId);

        objectSummaryView.setObject(immediateTagRefObject, repo());

        if (immediateTagRefObject instanceof RevTag) {
          revTag = revWalk.parseTag(tagId);
          getSupportActionBar().setTitle(revTag.getTagName());
        }

      } catch (IOException e) {
        Log.e(TAG, "Couldn't get parse tag", e);
        Toast.makeText(this, "Couldn't get tag " + tagId, Toast.LENGTH_LONG).show();
      }
    }
  }
Exemple #8
0
 @Override
 public String apply(ProjectResource rsrc)
     throws AuthException, ResourceNotFoundException, IOException {
   try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
     Ref head = repo.getRefDatabase().exactRef(Constants.HEAD);
     if (head == null) {
       throw new ResourceNotFoundException(Constants.HEAD);
     } else if (head.isSymbolic()) {
       String n = head.getTarget().getName();
       if (rsrc.getControl().controlForRef(n).isVisible()) {
         return n;
       }
       throw new AuthException("not allowed to see HEAD");
     } else if (head.getObjectId() != null) {
       try (RevWalk rw = new RevWalk(repo)) {
         RevCommit commit = rw.parseCommit(head.getObjectId());
         if (rsrc.getControl().canReadCommit(db.get(), repo, commit)) {
           return head.getObjectId().name();
         }
         throw new AuthException("not allowed to see HEAD");
       } catch (MissingObjectException | IncorrectObjectTypeException e) {
         if (rsrc.getControl().isOwner()) {
           return head.getObjectId().name();
         }
         throw new AuthException("not allowed to see HEAD");
       }
     }
     throw new ResourceNotFoundException(Constants.HEAD);
   } catch (RepositoryNotFoundException e) {
     throw new ResourceNotFoundException(rsrc.getName());
   }
 }
Exemple #9
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;
    }
  }
  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();
    }
  }
  @Override
  public PageData getRevisionData(FileSystemPage page, String label) {
    // Workaround for CachingPage
    if (label == null) {
      return persistence.getRevisionData(page, null);
    }
    String content, propertiesXml;
    RevCommit revCommit;
    Repository repository = getRepository(page);

    try {
      String fileSystemPath = getPath(page, repository);
      ObjectId rev = repository.resolve(label);
      RevWalk walk = new RevWalk(repository);
      revCommit = walk.parseCommit(rev);

      content = getRepositoryContent(repository, revCommit, fileSystemPath + "/" + contentFilename);
      propertiesXml =
          getRepositoryContent(repository, revCommit, fileSystemPath + "/" + propertiesFilename);
    } catch (IOException e) {
      throw new RuntimeException("Unable to get data for revision " + label, e);
    }

    final PageData pageData = new PageData(page);
    pageData.setContent(content);
    pageData.setProperties(
        parsePropertiesXml(propertiesXml, revCommit.getAuthorIdent().getWhen().getTime()));
    return pageData;
  }
  @Override
  protected void doGetHtml(HttpServletRequest req, HttpServletResponse res) throws IOException {
    MarkdownConfig cfg = MarkdownConfig.get(getAccess(req).getConfig());
    if (!cfg.render) {
      res.setStatus(SC_NOT_FOUND);
      return;
    }

    GitilesView view = ViewFilter.getView(req);
    Repository repo = ServletUtils.getRepository(req);
    try (RevWalk rw = new RevWalk(repo)) {
      ObjectReader reader = rw.getObjectReader();
      String path = view.getPathPart();
      RevTree root;
      try {
        root = rw.parseTree(view.getRevision().getId());
      } catch (IncorrectObjectTypeException e) {
        res.setStatus(SC_NOT_FOUND);
        return;
      }

      MarkdownFile srcmd = findFile(rw, root, path);
      if (srcmd == null) {
        res.setStatus(SC_NOT_FOUND);
        return;
      }

      MarkdownFile navmd = findFile(rw, root, NAVBAR_MD);
      String curEtag = etag(srcmd, navmd);
      if (etagMatch(req, curEtag)) {
        res.setStatus(SC_NOT_MODIFIED);
        return;
      }

      view = view.toBuilder().setPathPart(srcmd.path).build();
      try {
        srcmd.read(reader, cfg);
        if (navmd != null) {
          navmd.read(reader, cfg);
        }
      } catch (LargeObjectException.ExceedsLimit errBig) {
        fileTooBig(res, view, errBig);
        return;
      } catch (IOException err) {
        readError(res, view, err);
        return;
      }

      MarkdownToHtml.Builder fmt =
          MarkdownToHtml.builder()
              .setConfig(cfg)
              .setGitilesView(view)
              .setRequestUri(req.getRequestURI())
              .setReader(reader)
              .setRootTree(root);
      res.setHeader(HttpHeaders.ETAG, curEtag);
      showDoc(req, res, view, cfg, fmt, navmd, srcmd);
    }
  }
 public static RevCommit getRevCommit(Repository repository, PatchSet target)
     throws AmbiguousObjectException, IOException, MissingObjectException,
         IncorrectObjectTypeException {
   ObjectId ref = repository.resolve(target.getRevision().get());
   RevWalk walker = new RevWalk(repository);
   RevCommit targetCommit = walker.parseCommit(ref);
   return targetCommit;
 }
Exemple #14
0
 protected List<RevCommit> getRemoteLog(Project.NameKey project, String branch)
     throws IOException {
   try (Repository repo = repoManager.openRepository(project);
       RevWalk rw = new RevWalk(repo)) {
     rw.markStart(rw.parseCommit(repo.getRef("refs/heads/" + branch).getObjectId()));
     return Lists.newArrayList(rw);
   }
 }
Exemple #15
0
 public RevCommit getCommit(Repository repo, String revstr)
     throws MissingObjectException, IncorrectObjectTypeException, AmbiguousObjectException,
         IOException {
   RevWalk walk = new RevWalk(repo);
   ObjectId ref = repo.resolve(revstr);
   if (ref == null) return null;
   return walk.parseCommit(ref);
 }
Exemple #16
0
 private boolean isMergedInto(Ref oldHead, AnyObjectId src) throws IOException {
   RevWalk revWalk = new RevWalk(db);
   ObjectId oldHeadObjectId = oldHead.getPeeledObjectId();
   if (oldHeadObjectId == null) oldHeadObjectId = oldHead.getObjectId();
   RevCommit oldHeadCommit = revWalk.lookupCommit(oldHeadObjectId);
   RevCommit srcCommit = revWalk.lookupCommit(src);
   return revWalk.isMergedInto(oldHeadCommit, srcCommit);
 }
Exemple #17
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();
   }
 }
Exemple #19
0
  // find commits that are (only?) in each remote
  private void getCommitsInR(RevWalk walk, boolean only)
      throws MissingObjectException, IncorrectObjectTypeException, IOException {

    Iterator<BranchRef> brIt;
    LinkedHashMap<String, ArrayList<Commit>> commits;
    ArrayList<RevCommit> comm;
    ArrayList<RevCommit> included = new ArrayList<RevCommit>();
    ArrayList<RevCommit> excluded = new ArrayList<RevCommit>();
    Entry<String, ArrayList<BranchRef>> er;
    String r;
    Commit c;
    ArrayList<Commit> newcos;
    Iterator<Entry<String, ArrayList<BranchRef>>> erit;
    Iterator<String> sit = branches.keySet().iterator();
    commits = new LinkedHashMap<String, ArrayList<Commit>>(branches.size() / 2, 1);
    if (only) excluded.ensureCapacity(allBranches.size() - 1);
    //  int j = 0;
    while (sit.hasNext()) {
        /**/
      // System.err.println("###### Iteration " + (++j));
      r = sit.next();
      erit = branches.entrySet().iterator();
      while (erit.hasNext()) {
        er = erit.next();
        brIt = er.getValue().iterator();
        if (er.getKey().equals(r)) {
          while (brIt.hasNext()) {
            GitWorks.addUnique(included, walk.parseCommit(brIt.next().id));
          }
        } else if (only) {
          while (brIt.hasNext()) {
            GitWorks.addUnique(excluded, walk.parseCommit(brIt.next().id));
          }
        }
      }
      comm = findCommits(walk, included, excluded, false, 0);
      if (comm != null) {
        newcos = new ArrayList<Commit>(comm.size());
        for (int i = 0; i < comm.size(); i++) {
          c = GitWorks.getElement(allCommits, comm.get(i));
          newcos.add(c);
        }
        commits.put(r, newcos);
      }
      included.clear();
      excluded.clear();
      walk.reset();
    }
    included.trimToSize();
    included.ensureCapacity(50);
    excluded.trimToSize();
    excluded.ensureCapacity(50);

    if (only) comOnlyInF = commits.isEmpty() ? null : commits;
    else comInF = commits.isEmpty() ? null : commits;
  }
  private boolean tag(
      HttpServletRequest request,
      HttpServletResponse response,
      Repository db,
      String commitId,
      String tagName,
      boolean isRoot)
      throws JSONException, URISyntaxException, ServletException {
    Git git = new Git(db);
    RevWalk walk = new RevWalk(db);
    try {
      ObjectId objectId = db.resolve(commitId);
      RevCommit revCommit = walk.lookupCommit(objectId);
      walk.parseBody(revCommit);

      GitTagHandlerV1.tag(git, revCommit, tagName);

      URI cloneLocation =
          BaseToCloneConverter.getCloneLocation(
              getURI(request), BaseToCloneConverter.COMMIT_REFRANGE);
      Commit commit = new Commit(cloneLocation, db, revCommit, null);
      JSONObject result = commit.toJSON();
      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 tagging.",
              e));
    } catch (GitAPIException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when tagging.",
              e));
    } catch (CoreException e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when tagging.",
              e));
    } finally {
      walk.dispose();
    }
  }
  @Test
  public void testDefaultMessage() throws Exception {
    testUtils.addFileToProject(project.getProject(), "foo/a.txt", "some text");
    StashCreateOperation stashCreateOperation = new StashCreateOperation(repository);
    stashCreateOperation.execute(null);

    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(repository.resolve("stash@{0}"));
    assertTrue(commit.getFullMessage().length() > 0);
  }
 protected RevCommit findHead(Repository repo) {
   try (RevWalk walk = new RevWalk(repo)) {
     try {
       ObjectId head = repo.resolve(HEAD);
       return walk.parseCommit(head);
     } catch (RevisionSyntaxException | IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
 private VersionInfo getCurrentVersion(Repository repository) {
   try {
     ObjectId head = repository.resolve("HEAD");
     RevWalk walk = new RevWalk(repository);
     RevCommit revCommit = walk.parseCommit(head);
     return makeVersionInfo(revCommit);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Exemple #24
0
 // the RevWalk must be reset by the caller upon return!
 private ArrayList<RevCommit> findCommits(
     RevWalk walk,
     ArrayList<RevCommit> included,
     ArrayList<RevCommit> excluded,
     boolean getBody,
     long after)
     throws MissingObjectException, IncorrectObjectTypeException, IOException {
   ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
   commits.ensureCapacity(allBranches.size()); // heuristic workaround
   walk.sort(RevSort.COMMIT_TIME_DESC, true);
   walk.sort(RevSort.TOPO, true);
   walk.setRetainBody(getBody);
   if (after > 0) walk.setRevFilter(CommitTimeRevFilter.after(after));
   else walk.setRevFilter(null);
   walk.markStart(included);
   RevCommit c;
   Iterator<RevCommit> it = excluded.iterator();
   while (it.hasNext()) {
     walk.markUninteresting(it.next());
   }
   it = walk.iterator();
   while (it.hasNext()) {
     c = it.next();
     if (getBody) walk.parseBody(c);
     // addUnique(commits, c); // commits are naturally ordered by SHA-1
     commits.add(c);
   }
   return commits.size() > 0 ? commits : null;
 }
Exemple #25
0
 private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException, IOException {
   try (RevWalk rw = new RevWalk(getRepository())) {
     RevObject obj = rw.parseAny(leaf.getObjectId());
     if (obj instanceof RevTag) {
       return new ObjectIdRef.PeeledTag(
           leaf.getStorage(), leaf.getName(), leaf.getObjectId(), rw.peel(obj).copy());
     } else {
       return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf.getName(), leaf.getObjectId());
     }
   }
 }
  private boolean commitIndex(Repository db, DirCache index, String author, String message)
      throws IOException, ConcurrentRefUpdateException {
    boolean success = false;

    ObjectId headId = db.resolve(BRANCH + "^{commit}");
    if (headId == null) {
      // create the branch
      createTicketsBranch(db);
      headId = db.resolve(BRANCH + "^{commit}");
    }
    try (ObjectInserter odi = db.newObjectInserter()) {
      // Create the in-memory index of the new/updated ticket
      ObjectId indexTreeId = index.writeTree(odi);

      // Create a commit object
      PersonIdent ident = new PersonIdent(author, "gitblit@localhost");
      CommitBuilder commit = new CommitBuilder();
      commit.setAuthor(ident);
      commit.setCommitter(ident);
      commit.setEncoding(Constants.ENCODING);
      commit.setMessage(message);
      commit.setParentId(headId);
      commit.setTreeId(indexTreeId);

      // Insert the commit into the repository
      ObjectId commitId = odi.insert(commit);
      odi.flush();

      try (RevWalk revWalk = new RevWalk(db)) {
        RevCommit revCommit = revWalk.parseCommit(commitId);
        RefUpdate ru = db.updateRef(BRANCH);
        ru.setNewObjectId(commitId);
        ru.setExpectedOldObjectId(headId);
        ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
        Result rc = ru.forceUpdate();
        switch (rc) {
          case NEW:
          case FORCED:
          case FAST_FORWARD:
            success = true;
            break;
          case REJECTED:
          case LOCK_FAILURE:
            throw new ConcurrentRefUpdateException(
                JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
          default:
            throw new JGitInternalException(
                MessageFormat.format(
                    JGitText.get().updatingRefFailed, BRANCH, commitId.toString(), rc));
        }
      }
    }
    return success;
  }
  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();
    }
  }
Exemple #28
0
  private static AnyObjectId asTree(ObjectReader or, AnyObjectId treeish)
      throws MissingObjectException, IncorrectObjectTypeException, IOException {
    if (treeish instanceof RevTree) return treeish;

    if (treeish instanceof RevCommit && ((RevCommit) treeish).getTree() != null)
      return ((RevCommit) treeish).getTree();

    try (RevWalk rw = new RevWalk(or)) {
      return rw.parseTree(treeish).getId();
    }
  }
Exemple #29
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;
 }
  /**
   * Returns a list of commits for the repository or a path within the repository. Caller may
   * specify ending revision with objectId. Caller may specify offset and maxCount to achieve
   * pagination of results. If the repository does not exist or is empty, an empty list is returned.
   *
   * @param repository
   * @param objectId if unspecified, HEAD is assumed.
   * @param path if unspecified, commits for repository are returned. If specified, commits for the
   *     path are returned.
   * @param offset
   * @param maxCount if < 0, all commits are returned.
   * @return a paged list of commits
   */
  public static List<RevCommit> getRevLog(
      Repository repository, String objectId, String path, int offset, int maxCount) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (maxCount == 0) {
      return list;
    }
    if (!hasCommits(repository)) {
      return list;
    }
    try {
      // resolve branch
      ObjectId branchObject;
      if (objectId == null) {
        branchObject = getDefaultBranch(repository);
      } else {
        branchObject = repository.resolve(objectId);
      }

      RevWalk rw = new RevWalk(repository);
      rw.markStart(rw.parseCommit(branchObject));
      if (!(path == null)) {
        TreeFilter filter =
            AndTreeFilter.create(
                PathFilterGroup.createFromStrings(Collections.singleton(path)),
                TreeFilter.ALL); // TreeFilter.ANY_DIFF
        rw.setTreeFilter(filter);
      }
      Iterable<RevCommit> revlog = rw;
      if (offset > 0) {
        int count = 0;
        for (RevCommit rev : revlog) {
          count++;
          if (count > offset) {
            list.add(rev);
            if (maxCount > 0 && list.size() == maxCount) {
              break;
            }
          }
        }
      } else {
        for (RevCommit rev : revlog) {
          list.add(rev);
          if (maxCount > 0 && list.size() == maxCount) {
            break;
          }
        }
      }
      rw.dispose();
    } catch (Throwable t) {
      // todo
      Logger.error(t, t.getMessage());
    }
    return list;
  }