Ejemplo n.º 1
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();
      }
    }
  }
Ejemplo n.º 2
0
  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();
    }
  }
Ejemplo n.º 3
0
  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;
  }
Ejemplo n.º 4
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());
   }
 }
Ejemplo n.º 5
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());
     }
   }
 }
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
0
 public int compare(Ref o1, Ref o2) {
   try {
     RevObject obj1 = parseAny(o1.getObjectId());
     RevObject obj2 = parseAny(o2.getObjectId());
     long t1 = timeof(obj1);
     long t2 = timeof(obj2);
     if (t1 > t2) return -1;
     if (t1 < t2) return 1;
     return 0;
   } catch (IOException e) {
     // ignore
     return 0;
   }
 }
Ejemplo n.º 8
0
  /** @return all refs which were advertised to the client. */
  public final Map<String, Ref> getAdvertisedRefs() {
    if (refs == null) {
      refs = refFilter.filter(db.getAllRefs());

      Ref head = refs.get(Constants.HEAD);
      if (head != null && head.isSymbolic()) refs.remove(Constants.HEAD);

      for (Ref ref : refs.values()) {
        if (ref.getObjectId() != null) advertisedHaves.add(ref.getObjectId());
      }
      advertisedHaves.addAll(db.getAdditionalHaves());
    }
    return refs;
  }
Ejemplo n.º 9
0
 /**
  * Make sure a ref is peeled and has the Storage PACKED. If the given ref has this attributes
  * simply return it. Otherwise create a new peeled {@link ObjectIdRef} where Storage is set to
  * PACKED.
  *
  * @param f
  * @return a ref for Storage PACKED having the same name, id, peeledId as f
  * @throws MissingObjectException
  * @throws IOException
  */
 private Ref peeledPackedRef(Ref f) throws MissingObjectException, IOException {
   if (f.getStorage().isPacked() && f.isPeeled()) {
     return f;
   }
   if (!f.isPeeled()) {
     f = peel(f);
   }
   ObjectId peeledObjectId = f.getPeeledObjectId();
   if (peeledObjectId != null) {
     return new ObjectIdRef.PeeledTag(PACKED, f.getName(), f.getObjectId(), peeledObjectId);
   } else {
     return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(), f.getObjectId());
   }
 }
  @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());
  }
Ejemplo n.º 11
0
  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;
  }
Ejemplo n.º 12
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);
    }
  }
Ejemplo n.º 13
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")));
  }
Ejemplo n.º 14
0
 /**
  * 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;
 }
Ejemplo n.º 15
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());
  }
Ejemplo n.º 16
0
  private Iterable<RevCommit> getCommitsFromTag(String treeName) {

    try {

      List<Ref> call = git.tagList().call();
      Iterable<RevCommit> logs = null;

      for (Ref ref : call) {

        if (ref.getName().equals(treeName)) {

          LogCommand log = git.log();
          Ref peeledRef = repository.peel(ref);

          if (peeledRef.getPeeledObjectId() != null) {
            log.add(peeledRef.getPeeledObjectId());
          } else {
            log.add(ref.getObjectId());
          }

          logs = log.call();
          return logs;
        }
      }

      return null;

    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (MissingObjectException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (IncorrectObjectTypeException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
Ejemplo n.º 17
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();
    }
  }
Ejemplo n.º 18
0
 private RepositoryDescription buildDescription(Repository repo, Set<String> branches)
     throws IOException {
   RepositoryDescription desc = new RepositoryDescription();
   desc.name = getRepositoryName(repo);
   desc.cloneUrl = baseGitUrl + getRelativePath(repo);
   desc.description = loadDescriptionText(repo);
   if (!branches.isEmpty()) {
     desc.branches = Maps.newLinkedHashMap();
     for (String name : branches) {
       Ref ref = repo.exactRef(normalizeRefName(name));
       if ((ref != null) && (ref.getObjectId() != null)) {
         desc.branches.put(name, ref.getObjectId().name());
       }
     }
   }
   return desc;
 }
Ejemplo n.º 19
0
    CommitBuilder(BranchBuilder b) throws Exception {
      branch = b;

      Ref ref = db.getRef(branch.ref);
      if (ref != null) {
        parent(pool.parseCommit(ref.getObjectId()));
      }
    }
Ejemplo n.º 20
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);
 }
Ejemplo n.º 21
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;
  }
Ejemplo n.º 22
0
  public static void main(String[] args) throws IOException, GitAPIException {
    Repository repository = CookbookHelper.openJGitCookbookRepository();

    List<Ref> refs = new Git(repository).branchList().call();
    for (Ref ref : refs) {
      System.out.println(
          "Branch: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName());

      listReflog(repository, ref);
    }

    List<Ref> call = new Git(repository).tagList().call();
    for (Ref ref : call) {
      System.out.println("Tag: " + ref + " " + ref.getName() + " " + ref.getObjectId().getName());

      listReflog(repository, ref);
    }

    repository.close();
  }
Ejemplo n.º 23
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);
   }
 }
Ejemplo n.º 24
0
  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();
    }
  }
Ejemplo n.º 25
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;
 }
Ejemplo n.º 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;
    }
  }
Ejemplo n.º 27
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;
    }
  }
Ejemplo n.º 29
0
 private static DirCache readTree(final Repository pdb, final Ref branch)
     throws MissingObjectException, IncorrectObjectTypeException, IOException {
   try (RevWalk rw = new RevWalk(pdb)) {
     final DirCache dc = DirCache.newInCore();
     final DirCacheBuilder b = dc.builder();
     b.addTree(
         new byte[0], // no prefix path
         DirCacheEntry.STAGE_0, // standard stage
         pdb.newObjectReader(),
         rw.parseTree(branch.getObjectId()));
     b.finish();
     return dc;
   }
 }
Ejemplo n.º 30
0
  @Test
  public void test() throws Exception {

    GitService git = lookup(GitService.class);

    File gitDir = git.getWorkingDir();
    String tag = "mock-1.0" + System.currentTimeMillis();

    VersionContext context = new VersionContext(0, tag, "test", "test", "test");

    git.setup(context);
    git.pull(context);

    git.clearWorkingDir(context);

    downloadAndExtractTo(tag, gitDir);

    ObjectId objId = git.commit(context);
    git.push(context);

    Collection<Ref> refs = git.lsRemote();
    boolean tagExist = false;
    boolean commitSuccess = false;
    if (refs != null) {
      for (Ref ref : refs) {
        if (ref.getName().equals(REFS_TAGS + tag)) {
          tagExist = true;
        }
        if (ref.getObjectId().getName().equals(objId.getName())) {
          commitSuccess = true;
        }
      }
    }
    Assert.assertTrue(tagExist);
    Assert.assertTrue(commitSuccess);

    git.removeTag(context);

    refs = git.lsRemote();
    tagExist = false;
    if (refs != null) {
      for (Ref ref : refs) {
        if (ref.getName().equals(REFS_TAGS + tag)) {
          tagExist = true;
        }
      }
    }
    Assert.assertFalse(tagExist);
  }