private boolean sendWants(final Collection<Ref> want) throws IOException {
    final PacketLineOut p = statelessRPC ? pckState : pckOut;
    boolean first = true;
    for (final Ref r : want) {
      try {
        if (walk.parseAny(r.getObjectId()).has(REACHABLE)) {
          // We already have this object. Asking for it is
          // not a very good idea.
          //
          continue;
        }
      } catch (IOException err) {
        // Its OK, we don't have it, but we want to fix that
        // by fetching the object from the other side.
      }

      final StringBuilder line = new StringBuilder(46);
      line.append("want ");
      line.append(r.getObjectId().name());
      if (first) {
        line.append(enableCapabilities());
        first = false;
      }
      line.append('\n');
      p.writeString(line.toString());
    }
    if (first) return false;
    p.end();
    outNeedsEnd = false;
    return true;
  }
Example #2
0
  /**
   * Run consistency checks against the object database.
   *
   * <p>This method completes silently if the checks pass. A temporary revision pool is constructed
   * during the checking.
   *
   * @param tips the tips to start checking from; if not supplied the refs of the repository are
   *     used instead.
   * @throws MissingObjectException
   * @throws IncorrectObjectTypeException
   * @throws IOException
   */
  public void fsck(RevObject... tips)
      throws MissingObjectException, IncorrectObjectTypeException, IOException {
    ObjectWalk ow = new ObjectWalk(db);
    if (tips.length != 0) {
      for (RevObject o : tips) ow.markStart(ow.parseAny(o));
    } else {
      for (Ref r : db.getAllRefs().values()) ow.markStart(ow.parseAny(r.getObjectId()));
    }

    ObjectChecker oc = new ObjectChecker();
    for (; ; ) {
      final RevCommit o = ow.next();
      if (o == null) break;

      final byte[] bin = db.open(o, o.getType()).getCachedBytes();
      oc.checkCommit(bin);
      assertHash(o, bin);
    }

    for (; ; ) {
      final RevObject o = ow.nextObject();
      if (o == null) break;

      final byte[] bin = db.open(o, o.getType()).getCachedBytes();
      oc.check(o.getType(), bin);
      assertHash(o, bin);
    }
  }
  private Iterable<ChangeData> byCommitsOnBranchNotMergedFromDatabase(
      Repository repo, ReviewDb db, Branch.NameKey branch, List<String> hashes)
      throws OrmException, IOException {
    Set<Change.Id> changeIds = Sets.newHashSetWithExpectedSize(hashes.size());
    String lastPrefix = null;
    for (Ref ref : repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES).values()) {
      String r = ref.getName();
      if ((lastPrefix != null && r.startsWith(lastPrefix))
          || !hashes.contains(ref.getObjectId().name())) {
        continue;
      }
      Change.Id id = Change.Id.fromRef(r);
      if (id == null) {
        continue;
      }
      if (changeIds.add(id)) {
        lastPrefix = r.substring(0, r.lastIndexOf('/'));
      }
    }

    List<ChangeData> cds = new ArrayList<>(hashes.size());
    for (Change c : db.changes().get(changeIds)) {
      if (c.getDest().equals(branch) && c.getStatus() != Change.Status.MERGED) {
        cds.add(changeDataFactory.create(db, c));
      }
    }
    return cds;
  }
  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();
    }
  }
Example #5
0
  @Override
  public Map<String, Ref> getRefs(String prefix) throws IOException {
    final RefList<LooseRef> oldLoose = looseRefs.get();
    LooseScanner scan = new LooseScanner(oldLoose);
    scan.scan(prefix);
    final RefList<Ref> packed = getPackedRefs();

    RefList<LooseRef> loose;
    if (scan.newLoose != null) {
      scan.newLoose.sort();
      loose = scan.newLoose.toRefList();
      if (looseRefs.compareAndSet(oldLoose, loose)) modCnt.incrementAndGet();
    } else loose = oldLoose;
    fireRefsChanged();

    RefList.Builder<Ref> symbolic = scan.symbolic;
    for (int idx = 0; idx < symbolic.size(); ) {
      final Ref symbolicRef = symbolic.get(idx);
      final Ref resolvedRef = resolve(symbolicRef, 0, prefix, loose, packed);
      if (resolvedRef != null && resolvedRef.getObjectId() != null) {
        symbolic.set(idx, resolvedRef);
        idx++;
      } else {
        // A broken symbolic reference, we have to drop it from the
        // collections the client is about to receive. Should be a
        // rare occurrence so pay a copy penalty.
        symbolic.remove(idx);
        final int toRemove = loose.find(symbolicRef.getName());
        if (0 <= toRemove) loose = loose.remove(toRemove);
      }
    }
    symbolic.sort();

    return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList());
  }
Example #6
0
 private boolean isLocalBranch(Git git, String branch) throws GitAPIException {
   List<Ref> branches = git.branchList().call();
   for (Ref ref : branches) {
     if (Repository.shortenRefName(ref.getName()).equals(branch)) return true;
   }
   return false;
 }
Example #7
0
  @Test
  public void finishHotfixMasterIsTagged() throws Exception {
    Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir());
    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // Make sure we move away from master on a hotfix branch
    // This is important to validate JGITFFLOW-14

    // create a new commit
    File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    git.add().addFilepattern(junkFile.getName()).call();
    git.commit().setMessage("committing junk file").call();

    flow.hotfixFinish("1.1").setNoTag(false).call();

    // we should be on develop branch
    assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch());

    // There should be a tag reference
    Ref hotfixTagRef = git.getRepository().getTags().get(flow.getVersionTagPrefix() + "1.1");

    assertNotNull(hotfixTagRef);

    RevTag hotfixTag = new RevWalk(git.getRepository()).parseTag(hotfixTagRef.getObjectId());

    assertNotNull(hotfixTag);

    // Check that latest tag has moved
    assertFalse(getTaggedCommit(git, "1.1").equals(getTaggedCommit(git, "1.0")));
  }
Example #8
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();
      }
    }
  }
 /**
  * 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;
 }
 /**
  * Returns a RefModel for the refs/meta/gitblit/tickets branch in the repository. If the branch
  * can not be found, null is returned.
  *
  * @return a refmodel for the gitblit tickets branch or null
  */
 private RefModel getTicketsBranch(Repository db) {
   List<RefModel> refs = JGitUtils.getRefs(db, "refs/");
   Ref oldRef = null;
   for (RefModel ref : refs) {
     if (ref.reference.getName().equals(BRANCH)) {
       return ref;
     } else if (ref.reference.getName().equals("refs/gitblit/tickets")) {
       oldRef = ref.reference;
     }
   }
   if (oldRef != null) {
     // rename old ref to refs/meta/gitblit/tickets
     RefRename cmd;
     try {
       cmd = db.renameRef(oldRef.getName(), BRANCH);
       cmd.setRefLogIdent(new PersonIdent("Gitblit", "gitblit@localhost"));
       cmd.setRefLogMessage("renamed " + oldRef.getName() + " => " + BRANCH);
       Result res = cmd.rename();
       switch (res) {
         case RENAMED:
           log.info(db.getDirectory() + " " + cmd.getRefLogMessage());
           return getTicketsBranch(db);
         default:
           log.error(
               "failed to rename " + oldRef.getName() + " => " + BRANCH + " (" + res.name() + ")");
       }
     } catch (IOException e) {
       log.error("failed to rename tickets branch", e);
     }
   }
   return null;
 }
Example #11
0
  @Override
  public void create() {
    super.create();
    setTitle(UIText.BranchRenameDialog_Title);
    String oldName = branchToRename.getName();
    String prefix;
    if (oldName.startsWith(Constants.R_HEADS)) prefix = Constants.R_HEADS;
    else if (oldName.startsWith(Constants.R_REMOTES)) prefix = Constants.R_REMOTES;
    else prefix = null;
    String shortName = null;
    if (prefix != null) {
      shortName = Repository.shortenRefName(branchToRename.getName());
      setMessage(NLS.bind(UIText.BranchRenameDialog_Message, shortName));
    } else setErrorMessage(NLS.bind(UIText.BranchRenameDialog_WrongPrefixErrorMessage, oldName));

    if (shortName != null) {
      name.setText(shortName);
      name.setSelection(0, shortName.length());
    }

    final IInputValidator inputValidator =
        ValidationUtils.getRefNameInputValidator(repository, prefix, true);
    name.addModifyListener(
        new ModifyListener() {
          public void modifyText(ModifyEvent e) {
            String error = inputValidator.isValid(name.getText());
            setErrorMessage(error);
            getButton(OK).setEnabled(error == null);
          }
        });

    getButton(OK).setEnabled(false);
  }
  @Test
  public void testFilterHidesPrivate() throws Exception {
    Map<String, Ref> refs;
    TransportLocal t =
        new TransportLocal(src, uriOf(dst), dst.getDirectory()) {
          @Override
          ReceivePack createReceivePack(final Repository db) {
            db.close();
            dst.incrementOpen();

            final ReceivePack rp = super.createReceivePack(dst);
            rp.setAdvertiseRefsHook(new HidePrivateHook());
            return rp;
          }
        };
    try {
      PushConnection c = t.openPush();
      try {
        refs = c.getRefsMap();
      } finally {
        c.close();
      }
    } finally {
      t.close();
    }

    assertNotNull(refs);
    assertNull("no private", refs.get(R_PRIVATE));
    assertNull("no HEAD", refs.get(Constants.HEAD));
    assertEquals(1, refs.size());

    Ref master = refs.get(R_MASTER);
    assertNotNull("has master", master);
    assertEquals(B, master.getObjectId());
  }
Example #13
0
 private static Ref recreate(final Ref old, final ObjectIdRef leaf) {
   if (old.isSymbolic()) {
     Ref dst = recreate(old.getTarget(), leaf);
     return new SymbolicRef(old.getName(), dst);
   }
   return leaf;
 }
Example #14
0
  @Test
  public void logAllCommits() throws Exception {
    List<RevCommit> commits = new ArrayList<RevCommit>();
    Git git = Git.wrap(db);

    writeTrashFile("Test.txt", "Hello world");
    git.add().addFilepattern("Test.txt").call();
    commits.add(git.commit().setMessage("initial commit").call());

    git.branchCreate().setName("branch1").call();
    Ref checkedOut = git.checkout().setName("branch1").call();
    assertEquals("refs/heads/branch1", checkedOut.getName());
    writeTrashFile("Test1.txt", "Hello world!");
    git.add().addFilepattern("Test1.txt").call();
    commits.add(git.commit().setMessage("branch1 commit").call());

    checkedOut = git.checkout().setName("master").call();
    assertEquals("refs/heads/master", checkedOut.getName());
    writeTrashFile("Test2.txt", "Hello world!!");
    git.add().addFilepattern("Test2.txt").call();
    commits.add(git.commit().setMessage("branch1 commit").call());

    Iterator<RevCommit> log = git.log().all().call().iterator();
    assertTrue(log.hasNext());
    assertTrue(commits.contains(log.next()));
    assertTrue(log.hasNext());
    assertTrue(commits.contains(log.next()));
    assertTrue(log.hasNext());
    assertTrue(commits.contains(log.next()));
    assertFalse(log.hasNext());
  }
Example #15
0
  /**
   * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are added. If a ref with
   * the given name already existed in packed-refs it is updated with the new value. Each loose ref
   * which was added to the packed-ref file is deleted. If a given ref can't be locked it will not
   * be added to the pack file.
   *
   * @param refs the refs to be added. Must be fully qualified.
   * @throws IOException
   */
  public void pack(List<String> refs) throws IOException {
    if (refs.size() == 0) return;
    FS fs = parent.getFS();

    // Lock the packed refs file and read the content
    LockFile lck = new LockFile(packedRefsFile);
    if (!lck.lock())
      throw new IOException(MessageFormat.format(JGitText.get().cannotLock, packedRefsFile));

    try {
      final PackedRefList packed = getPackedRefs();
      RefList<Ref> cur = readPackedRefs();

      // Iterate over all refs to be packed
      for (String refName : refs) {
        Ref ref = readRef(refName, cur);
        if (ref.isSymbolic()) continue; // can't pack symbolic refs
        // Add/Update it to packed-refs
        int idx = cur.find(refName);
        if (idx >= 0) cur = cur.set(idx, peeledPackedRef(ref));
        else cur = cur.add(idx, peeledPackedRef(ref));
      }

      // The new content for packed-refs is collected. Persist it.
      commitPackedRefs(lck, cur, packed);

      // Now delete the loose refs which are now packed
      for (String refName : refs) {
        // Lock the loose ref
        File refFile = fileFor(refName);
        if (!fs.exists(refFile)) continue;
        LockFile rLck = new LockFile(refFile);
        if (!rLck.lock()) continue;
        try {
          LooseRef currentLooseRef = scanRef(null, refName);
          if (currentLooseRef == null || currentLooseRef.isSymbolic()) continue;
          Ref packedRef = cur.get(refName);
          ObjectId clr_oid = currentLooseRef.getObjectId();
          if (clr_oid != null && clr_oid.equals(packedRef.getObjectId())) {
            RefList<LooseRef> curLoose, newLoose;
            do {
              curLoose = looseRefs.get();
              int idx = curLoose.find(refName);
              if (idx < 0) break;
              newLoose = curLoose.remove(idx);
            } while (!looseRefs.compareAndSet(curLoose, newLoose));
            int levels = levelsIn(refName) - 2;
            delete(refFile, levels, rLck);
          }
        } finally {
          rLck.unlock();
        }
      }
      // Don't fire refsChanged. The refs have not change, only their
      // storage.
    } finally {
      lck.unlock();
    }
  }
Example #16
0
    CommitBuilder(BranchBuilder b) throws Exception {
      branch = b;

      Ref ref = db.getRef(branch.ref);
      if (ref != null) {
        parent(pool.parseCommit(ref.getObjectId()));
      }
    }
Example #17
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);
 }
Example #18
0
  boolean performClone() {
    final URIish uri = cloneSource.getSelection().getURI();
    setWindowTitle(NLS.bind(UIText.GitCloneWizard_jobName, uri.toString()));
    final boolean allSelected;
    final Collection<Ref> selectedBranches;
    if (validSource.isSourceRepoEmpty()) {
      // fetch all branches of empty repo
      allSelected = true;
      selectedBranches = Collections.emptyList();
    } else {
      allSelected = validSource.isAllSelected();
      selectedBranches = validSource.getSelectedBranches();
    }
    final File workdir = cloneDestination.getDestinationFile();
    final Ref ref = cloneDestination.getInitialBranch();
    final String remoteName = cloneDestination.getRemote();

    boolean created = workdir.exists();
    if (!created) created = workdir.mkdirs();

    if (!created || !workdir.isDirectory()) {
      final String errorMessage =
          NLS.bind(UIText.GitCloneWizard_errorCannotCreate, workdir.getPath());
      ErrorDialog.openError(
          getShell(),
          getWindowTitle(),
          UIText.GitCloneWizard_failed,
          new Status(IStatus.ERROR, Activator.getPluginId(), 0, errorMessage, null));
      // let's give user a chance to fix this minor problem
      return false;
    }

    int timeout =
        Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
    final CloneOperation op =
        new CloneOperation(
            uri,
            allSelected,
            selectedBranches,
            workdir,
            ref != null ? ref.getName() : null,
            remoteName,
            timeout);
    if (gerritConfiguration.configureGerrit()) doGerritConfiguration(remoteName, op);
    UserPasswordCredentials credentials = cloneSource.getCredentials();
    if (credentials != null)
      op.setCredentialsProvider(
          new UsernamePasswordCredentialsProvider(
              credentials.getUser(), credentials.getPassword()));

    alreadyClonedInto = workdir.getPath();

    cloneSource.saveUriInPrefs();
    if (!callerRunsCloneOperation) runAsJob(uri, op);
    else cloneOperation = op;
    return true;
  }
Example #19
0
 private List<String> getTags() {
   RevCommit commit = getCommit().getRevCommit();
   Repository repository = getCommit().getRepository();
   List<String> tags = new ArrayList<String>();
   for (Ref tag : repository.getTags().values())
     if (commit.equals(repository.peel(tag).getPeeledObjectId()))
       tags.add(Repository.shortenRefName(tag.getName()));
   Collections.sort(tags);
   return tags;
 }
Example #20
0
  @Override
  protected boolean tryLock(boolean deref) throws IOException {
    dstRef = getRef();
    if (deref) dstRef = dstRef.getLeaf();

    if (dstRef.isSymbolic()) setOldObjectId(null);
    else setOldObjectId(dstRef.getObjectId());

    return true;
  }
  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();
    }
  }
Example #22
0
 @Override
 protected Result doLink(String target) throws IOException {
   final SymbolicRef newRef =
       new SymbolicRef(dstRef.getName(), new ObjectIdRef.Unpeeled(Storage.NEW, target, null));
   if (getRefDatabase().compareAndPut(dstRef, newRef)) {
     getRefDatabase().stored(newRef);
     if (dstRef.getStorage() == Ref.Storage.NEW) return Result.NEW;
     return Result.FORCED;
   }
   return Result.LOCK_FAILURE;
 }
Example #23
0
 /**
  * Obtain a modified copy of the cache with a ref stored.
  *
  * <p>This cache instance is not modified by this method.
  *
  * @param ref reference to add or replace.
  * @return a copy of this cache, with the reference added or replaced.
  */
 public RefCache put(Ref ref) {
   RefList<Ref> newIds = this.ids.put(ref);
   RefList<Ref> newSym = this.sym;
   if (ref.isSymbolic()) {
     newSym = newSym.put(ref);
   } else {
     int p = newSym.find(ref.getName());
     if (0 <= p) newSym = newSym.remove(p);
   }
   return new RefCache(newIds, newSym);
 }
Example #24
0
 protected void assertCurrentRevision(String changeId, int expectedNum, ObjectId expectedId)
     throws Exception {
   ChangeInfo c = get(changeId, CURRENT_REVISION);
   assertThat(c.currentRevision).isEqualTo(expectedId.name());
   assertThat(c.revisions.get(expectedId.name())._number).isEqualTo(expectedNum);
   try (Repository repo = repoManager.openRepository(new Project.NameKey(c.project))) {
     Ref ref = repo.getRef(new PatchSet.Id(new Change.Id(c._number), expectedNum).toRefName());
     assertThat(ref).isNotNull();
     assertThat(ref.getObjectId()).isEqualTo(expectedId);
   }
 }
Example #25
0
 private static Ref guessHEAD(final FetchResult result) {
   final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
   Ref head = null;
   for (final Ref r : result.getAdvertisedRefs()) {
     final String n = r.getName();
     if (!n.startsWith(Constants.R_HEADS)) continue;
     if (idHEAD == null || head != null) continue;
     if (r.getObjectId().equals(idHEAD.getObjectId())) head = r;
   }
   if (idHEAD != null && head == null) head = idHEAD;
   return head;
 }
Example #26
0
  @Override
  public Response<List<BlameInfo>> apply(FileResource resource)
      throws RestApiException, OrmException, IOException, InvalidChangeOperationException {
    if (!allowBlame) {
      throw new BadRequestException("blame is disabled");
    }

    Project.NameKey project = resource.getRevision().getChange().getProject();
    try (Repository repository = repoManager.openRepository(project);
        ObjectInserter ins = repository.newObjectInserter();
        RevWalk revWalk = new RevWalk(ins.newReader())) {
      String refName =
          resource.getRevision().getEdit().isPresent()
              ? resource.getRevision().getEdit().get().getRefName()
              : resource.getRevision().getPatchSet().getRefName();

      Ref ref = repository.findRef(refName);
      if (ref == null) {
        throw new ResourceNotFoundException("unknown ref " + refName);
      }
      ObjectId objectId = ref.getObjectId();
      RevCommit revCommit = revWalk.parseCommit(objectId);
      RevCommit[] parents = revCommit.getParents();

      String path = resource.getPatchKey().getFileName();

      List<BlameInfo> result;
      if (!base) {
        result = blame(revCommit, path, repository, revWalk);

      } else if (parents.length == 0) {
        throw new ResourceNotFoundException("Initial commit doesn't have base");

      } else if (parents.length == 1) {
        result = blame(parents[0], path, repository, revWalk);

      } else if (parents.length == 2) {
        ObjectId automerge = autoMerger.merge(repository, revWalk, ins, revCommit, mergeStrategy);
        result = blame(automerge, path, repository, revWalk);

      } else {
        throw new ResourceNotFoundException(
            "Cannot generate blame for merge commit with more than 2 parents");
      }

      Response<List<BlameInfo>> r = Response.ok(result);
      if (resource.isCacheable()) {
        r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
      }
      return r;
    }
  }
Example #27
0
 public RefDirectoryUpdate newUpdate(String name, boolean detach) throws IOException {
   boolean detachingSymbolicRef = false;
   final RefList<Ref> packed = getPackedRefs();
   Ref ref = readRef(name, packed);
   if (ref != null) ref = resolve(ref, 0, null, null, packed);
   if (ref == null) ref = new ObjectIdRef.Unpeeled(NEW, name, null);
   else {
     detachingSymbolicRef = detach && ref.isSymbolic();
   }
   RefDirectoryUpdate refDirUpdate = new RefDirectoryUpdate(this, ref);
   if (detachingSymbolicRef) refDirUpdate.setDetachingSymbolicRef();
   return refDirUpdate;
 }
 /**
  * Constructs this page.
  *
  * <p>If a base branch is provided, the drop down will be selected accordingly
  *
  * @param repo the repository
  * @param baseRef the branch or tag to base the new branch on, may be null
  */
 public CreateBranchPage(Repository repo, Ref baseRef) {
   super(CreateBranchPage.class.getName());
   this.myRepository = repo;
   if (baseRef != null) this.myBaseRef = baseRef.getName();
   else this.myBaseRef = null;
   this.myBaseCommit = null;
   this.myValidator =
       ValidationUtils.getRefNameInputValidator(myRepository, Constants.R_HEADS, false);
   if (baseRef != null) this.upstreamConfig = UpstreamConfig.getDefault(repo, baseRef.getName());
   else this.upstreamConfig = UpstreamConfig.NONE;
   setTitle(UIText.CreateBranchPage_Title);
   setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage);
 }
Example #29
0
 private static boolean isReachable(Repository repo, AnyObjectId id) throws IOException {
   try (RevWalk rw = new RevWalk(repo)) {
     for (Ref ref : repo.getAllRefs().values()) {
       rw.markStart(rw.parseCommit(ref.getObjectId()));
     }
     for (RevCommit next; (next = rw.next()) != null; ) {
       if (AnyObjectId.equals(next, id)) {
         return true;
       }
     }
   }
   return false;
 }
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final Repository repository = getRepository(true, event);
    // assert all resources map to the same repository
    if (repository == null) return null;
    final IResource[] resources = getSelectedResources(event);

    if (resources.length == 1 && resources[0] instanceof IFile) {
      final IFile baseFile = (IFile) resources[0];
      final String gitPath =
          RepositoryMapping.getMapping(baseFile.getProject()).getRepoRelativePath(baseFile);
      final ITypedElement base = SaveableCompareEditorInput.createFileElement(baseFile);

      ITypedElement next;
      try {
        Ref head = repository.getRef(Constants.HEAD);
        RevWalk rw = new RevWalk(repository);
        RevCommit commit = rw.parseCommit(head.getObjectId());

        next = CompareUtils.getFileRevisionTypedElement(gitPath, commit, repository);
      } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
        return null;
      }

      final GitCompareFileRevisionEditorInput in =
          new GitCompareFileRevisionEditorInput(base, next, null);
      CompareUI.openCompareEditor(in);
      return null;

    } else {
      CompareTreeView view;
      try {
        view =
            (CompareTreeView)
                PlatformUI.getWorkbench()
                    .getActiveWorkbenchWindow()
                    .getActivePage()
                    .showView(CompareTreeView.ID);
        try {
          view.setInput(resources, repository.resolve(Constants.HEAD).name());
        } catch (IOException e) {
          Activator.handleError(e.getMessage(), e, true);
          return null;
        }
      } catch (PartInitException e) {
        Activator.handleError(e.getMessage(), e, true);
        return null;
      }
      return null;
    }
  }