Package org.eclipse.jgit.revwalk

Examples of org.eclipse.jgit.revwalk.RevWalk


    final FetchConfig cfg = local.getConfig().get(FetchConfig.KEY);
    includeTags = transport.getTagOpt() != TagOpt.NO_TAGS;
    thinPack = transport.isFetchThin();
    allowOfsDelta = cfg.allowOfsDelta;

    walk = new RevWalk(local);
    reachableCommits = new RevCommitList<RevCommit>();
    REACHABLE = walk.newFlag("REACHABLE");
    COMMON = walk.newFlag("COMMON");
    STATE = walk.newFlag("STATE");
    ADVERTISED = walk.newFlag("ADVERTISED");
View Full Code Here


  }

  private RevCommit parseCommit(final Repository clonedRepo, final Ref ref)
      throws MissingObjectException, IncorrectObjectTypeException,
      IOException {
    final RevWalk rw = new RevWalk(clonedRepo);
    final RevCommit commit;
    try {
      commit = rw.parseCommit(ref.getObjectId());
    } finally {
      rw.release();
    }
    return commit;
  }
View Full Code Here

   */
  public Ref call() throws JGitInternalException, RefAlreadyExistsException,
      RefNotFoundException, InvalidRefNameException {
    checkCallable();
    processOptions();
    RevWalk revWalk = new RevWalk(repo);
    try {
      Ref refToCheck = repo.getRef(name);
      boolean exists = refToCheck != null
          && refToCheck.getName().startsWith(Constants.R_HEADS);
      if (!force && exists)
        throw new RefAlreadyExistsException(MessageFormat.format(
            JGitText.get().refAlreadyExists, name));

      ObjectId startAt = getStartPoint();
      String startPointFullName = null;
      if (startPoint != null) {
        Ref baseRef = repo.getRef(startPoint);
        if (baseRef != null)
          startPointFullName = baseRef.getName();
      }

      // determine whether we are based on a commit,
      // a branch, or a tag and compose the reflog message
      String refLogMessage;
      String baseBranch = "";
      if (startPointFullName == null) {
        String baseCommit;
        if (startCommit != null)
          baseCommit = startCommit.getShortMessage();
        else {
          RevCommit commit = revWalk.parseCommit(repo
              .resolve(startPoint));
          baseCommit = commit.getShortMessage();
        }
        if (exists)
          refLogMessage = "branch: Reset start-point to commit "
              + baseCommit;
        else
          refLogMessage = "branch: Created from commit " + baseCommit;

      } else if (startPointFullName.startsWith(Constants.R_HEADS)
          || startPointFullName.startsWith(Constants.R_REMOTES)) {
        baseBranch = startPointFullName;
        if (exists)
          refLogMessage = "branch: Reset start-point to branch "
              + startPointFullName; // TODO
        else
          refLogMessage = "branch: Created from branch " + baseBranch;
      } else {
        startAt = revWalk.peel(revWalk.parseAny(startAt));
        if (exists)
          refLogMessage = "branch: Reset start-point to tag "
              + startPointFullName;
        else
          refLogMessage = "branch: Created from tag "
              + startPointFullName;
      }

      RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
      updateRef.setNewObjectId(startAt);
      updateRef.setRefLogMessage(refLogMessage, false);
      Result updateResult;
      if (exists && force)
        updateResult = updateRef.forceUpdate();
      else
        updateResult = updateRef.update();

      setCallable(false);

      boolean ok = false;
      switch (updateResult) {
      case NEW:
        ok = !exists;
        break;
      case NO_CHANGE:
      case FAST_FORWARD:
      case FORCED:
        ok = exists;
        break;
      default:
        break;
      }

      if (!ok)
        throw new JGitInternalException(MessageFormat.format(JGitText
            .get().createBranchUnexpectedResult, updateResult
            .name()));

      Ref result = repo.getRef(name);
      if (result == null)
        throw new JGitInternalException(
            JGitText.get().createBranchFailedUnknownReason);

      if (baseBranch.length() == 0) {
        return result;
      }

      // if we are based on another branch, see
      // if we need to configure upstream configuration: first check
      // whether the setting was done explicitly
      boolean doConfigure;
      if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
          || upstreamMode == SetupUpstreamMode.TRACK)
        // explicitly set to configure
        doConfigure = true;
      else if (upstreamMode == SetupUpstreamMode.NOTRACK)
        // explicitly set to not configure
        doConfigure = false;
      else {
        // if there was no explicit setting, check the configuration
        String autosetupflag = repo.getConfig().getString(
            ConfigConstants.CONFIG_BRANCH_SECTION, null,
            ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
        if ("false".equals(autosetupflag)) {
          doConfigure = false;
        } else if ("always".equals(autosetupflag)) {
          doConfigure = true;
        } else {
          // in this case, the default is to configure
          // only in case the base branch was a remote branch
          doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
        }
      }

      if (doConfigure) {
        StoredConfig config = repo.getConfig();
        String[] tokens = baseBranch.split("/", 4);
        boolean isRemote = tokens[1].equals("remotes");
        if (isRemote) {
          // refs/remotes/<remote name>/<branch>
          String remoteName = tokens[2];
          String branchName = tokens[3];
          config
              .setString(ConfigConstants.CONFIG_BRANCH_SECTION,
                  name, ConfigConstants.CONFIG_KEY_REMOTE,
                  remoteName);
          config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
              name, ConfigConstants.CONFIG_KEY_MERGE,
              Constants.R_HEADS + branchName);
        } else {
          // set "." as remote
          config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
              name, ConfigConstants.CONFIG_KEY_REMOTE, ".");
          config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
              name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
        }
        config.save();
      }
      return result;
    } catch (IOException ioe) {
      throw new JGitInternalException(ioe.getMessage(), ioe);
    } finally {
      revWalk.release();
    }
  }
View Full Code Here

              : MessageFormat.format(
                  JGitText.get().mergeStrategyDoesNotSupportHeads,
                  mergeStrategy.getName(),
                  Integer.valueOf(commits.size())));

    RevWalk revWalk = null;
    DirCacheCheckout dco = null;
    try {
      Ref head = repo.getRef(Constants.HEAD);
      if (head == null)
        throw new NoHeadException(
            JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
      StringBuilder refLogMessage = new StringBuilder("merge ");

      // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
      revWalk = new RevWalk(repo);

      // we know for now there is only one commit
      Ref ref = commits.get(0);

      refLogMessage.append(ref.getName());

      // handle annotated tags
      ObjectId objectId = ref.getPeeledObjectId();
      if (objectId == null)
        objectId = ref.getObjectId();

      RevCommit srcCommit = revWalk.lookupCommit(objectId);

      ObjectId headId = head.getObjectId();
      if (headId == null) {
        revWalk.parseHeaders(srcCommit);
        dco = new DirCacheCheckout(repo,
            repo.lockDirCache(), srcCommit.getTree());
        dco.setFailOnConflict(true);
        dco.checkout();
        RefUpdate refUpdate = repo
            .updateRef(head.getTarget().getName());
        refUpdate.setNewObjectId(objectId);
        refUpdate.setExpectedOldObjectId(null);
        refUpdate.setRefLogMessage("initial pull", false);
        if (refUpdate.update() != Result.NEW)
          throw new NoHeadException(
              JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        setCallable(false);
        return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
            null, srcCommit }, MergeStatus.FAST_FORWARD,
            mergeStrategy, null, null);
      }

      RevCommit headCommit = revWalk.lookupCommit(headId);

      if (revWalk.isMergedInto(srcCommit, headCommit)) {
        setCallable(false);
        return new MergeResult(headCommit, srcCommit, new ObjectId[] {
            headCommit, srcCommit },
            MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null);
      } else if (revWalk.isMergedInto(headCommit, srcCommit)) {
        // FAST_FORWARD detected: skip doing a real merge but only
        // update HEAD
        refLogMessage.append(": " + MergeStatus.FAST_FORWARD);
        dco = new DirCacheCheckout(repo,
            headCommit.getTree(), repo.lockDirCache(),
            srcCommit.getTree());
        dco.setFailOnConflict(true);
        dco.checkout();

        updateHead(refLogMessage, srcCommit, headId);
        setCallable(false);
        return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
            headCommit, srcCommit }, MergeStatus.FAST_FORWARD,
            mergeStrategy, null, null);
      } else {

        String mergeMessage = new MergeMessageFormatter().format(
            commits, head);
        repo.writeMergeCommitMsg(mergeMessage);
        repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
        Merger merger = mergeStrategy.newMerger(repo);
        boolean noProblems;
        Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults = null;
        Map<String, MergeFailureReason> failingPaths = null;
        List<String> unmergedPaths = null;
        if (merger instanceof ResolveMerger) {
          ResolveMerger resolveMerger = (ResolveMerger) merger;
          resolveMerger.setCommitNames(new String[] {
              "BASE", "HEAD", ref.getName() });
          resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo));
          noProblems = merger.merge(headCommit, srcCommit);
          lowLevelResults = resolveMerger
              .getMergeResults();
          failingPaths = resolveMerger.getFailingPaths();
          unmergedPaths = resolveMerger.getUnmergedPaths();
        } else
          noProblems = merger.merge(headCommit, srcCommit);
        refLogMessage.append(": Merge made by ");
        refLogMessage.append(mergeStrategy.getName());
        refLogMessage.append('.');
        if (noProblems) {
          dco = new DirCacheCheckout(repo,
              headCommit.getTree(), repo.lockDirCache(),
              merger.getResultTreeId());
          dco.setFailOnConflict(true);
          dco.checkout();

          RevCommit newHead = new Git(getRepository()).commit()
              .setReflogComment(refLogMessage.toString()).call();
          return new MergeResult(newHead.getId(),
              null, new ObjectId[] {
                  headCommit.getId(), srcCommit.getId() },
              MergeStatus.MERGED, mergeStrategy, null, null);
        } else {
          if (failingPaths != null) {
            repo.writeMergeCommitMsg(null);
            repo.writeMergeHeads(null);
            return new MergeResult(null,
                merger.getBaseCommit(0, 1),
                new ObjectId[] {
                    headCommit.getId(), srcCommit.getId() },
                MergeStatus.FAILED, mergeStrategy,
                lowLevelResults, failingPaths, null);
          } else {
            String mergeMessageWithConflicts = new MergeMessageFormatter()
                .formatWithConflicts(mergeMessage,
                    unmergedPaths);
            repo.writeMergeCommitMsg(mergeMessageWithConflicts);
            return new MergeResult(null,
                merger.getBaseCommit(0, 1),
                new ObjectId[] { headCommit.getId(),
                    srcCommit.getId() },
                MergeStatus.CONFLICTING, mergeStrategy,
                lowLevelResults, null);
          }
        }
      }
    } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
      List<String> conflicts = (dco == null) ? Collections
          .<String> emptyList() : dco.getConflicts();
      throw new CheckoutConflictException(conflicts, e);
    } catch (IOException e) {
      throw new JGitInternalException(
          MessageFormat.format(
              JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand,
              e), e);
    } finally {
      if (revWalk != null)
        revWalk.release();
    }
  }
View Full Code Here

      } catch (IOException e) {
        throw new JGitInternalException(
            MessageFormat.format(JGitText.get().cannotRead, ref),
            e);
      }
      RevWalk rw = new RevWalk(repo);
      try {
        commit = rw.parseCommit(commitId);
      } catch (IOException e) {
        throw new JGitInternalException(
            MessageFormat.format(
            JGitText.get().cannotReadCommit, commitId.toString()),
            e);
      } finally {
        rw.release();
      }

      if (!filepaths.isEmpty()) {
        // reset [commit] -- paths
        resetIndexForPaths(commit);
View Full Code Here

  /**
   * @param repo
   */
  protected LogCommand(Repository repo) {
    super(repo);
    walk = new RevWalk(repo);
  }
View Full Code Here

   * @param into
   *            the destination repository.
   */
  public ReceivePack(final Repository into) {
    db = into;
    walk = new RevWalk(db);

    final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY);
    checkReceivedObjects = cfg.checkReceivedObjects;
    allowCreates = cfg.allowCreates;
    allowDeletes = cfg.allowDeletes;
View Full Code Here

   * @param copyFrom
   *            the source repository.
   */
  public UploadPack(final Repository copyFrom) {
    db = copyFrom;
    walk = new RevWalk(db);
    walk.setRetainBody(false);

    WANT = walk.newFlag("WANT");
    PEER_HAS = walk.newFlag("PEER_HAS");
    COMMON = walk.newFlag("COMMON");
View Full Code Here

      }

      if (depth > 0)
        pw.setShallowPack(depth, unshallowCommits);

      RevWalk rw = walk;
      if (wantAll.isEmpty()) {
        pw.preparePack(pm, wantIds, commonBase);
      } else {
        walk.reset();

        ObjectWalk ow = walk.toObjectWalkWithSameObjects();
        pw.preparePack(pm, ow, wantAll, commonBase);
        rw = ow;
      }

      if (options.contains(OPTION_INCLUDE_TAG) && refs != null) {
        for (Ref ref : refs.values()) {
          ObjectId objectId = ref.getObjectId();

          // If the object was already requested, skip it.
          if (wantAll.isEmpty()) {
            if (wantIds.contains(objectId))
              continue;
          } else {
            RevObject obj = rw.lookupOrNull(objectId);
            if (obj != null && obj.has(WANT))
              continue;
          }

          if (!ref.isPeeled())
            ref = db.peel(ref);

          ObjectId peeledId = ref.getPeeledObjectId();
          if (peeledId == null)
            continue;

          objectId = ref.getObjectId();
          if (pw.willInclude(peeledId) && !pw.willInclude(objectId))
            pw.addObject(rw.parseAny(objectId));
        }
      }

      pw.writePack(pm, NullProgressMonitor.INSTANCE, packOut);
      statistics = pw.getStatistics();
View Full Code Here

      // determine the current HEAD and the commit it is referring to
      ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
      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());
        } 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 {
View Full Code Here

TOP

Related Classes of org.eclipse.jgit.revwalk.RevWalk

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.