示例#1
0
  @Test
  public void testRemoved() throws IOException {
    writeTrashFile("file2", "file2");
    writeTrashFile("dir/file3", "dir/file3");

    TreeFormatter dir = new TreeFormatter();
    dir.append(
        "file3",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("873fb8d667d05436d728c52b1d7a09528e6eb59b"));

    TreeFormatter tree = new TreeFormatter();
    tree.append(
        "file2",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("30d67d4672d5c05833b7192cc77a79eaafb5c7ad"));
    tree.append("dir", FileMode.TREE, insertTree(dir));
    ObjectId treeId = insertTree(tree);

    FileTreeIterator iterator = new FileTreeIterator(db);
    IndexDiff diff = new IndexDiff(db, treeId, iterator);
    diff.diff();
    assertEquals(2, diff.getRemoved().size());
    assertTrue(diff.getRemoved().contains("file2"));
    assertTrue(diff.getRemoved().contains("dir/file3"));
    assertEquals(0, diff.getChanged().size());
    assertEquals(0, diff.getModified().size());
    assertEquals(0, diff.getAdded().size());
    assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders());
  }
示例#2
0
  // Each of these rules are from the read-tree manpage
  // go there to see what they mean.
  // Rule 0 is left out for obvious reasons :)
  public void testRules1thru3_NoIndexEntry() throws IOException {
    GitIndex index = new GitIndex(db);

    Tree head = new Tree(db);
    FileTreeEntry headFile = head.addFile("foo");
    ObjectId objectId = ObjectId.fromString("ba78e065e2c261d4f7b8f42107588051e87e18e9");
    headFile.setId(objectId);
    Tree merge = new Tree(db);

    Checkout readTree = getCheckoutImpl(head, index, merge);
    readTree.prescanTwoTrees();

    assertTrue(readTree.removed().contains("foo"));

    readTree = getCheckoutImpl(merge, index, head);
    readTree.prescanTwoTrees();

    assertEquals(objectId, readTree.updated().get("foo"));

    ObjectId anotherId = ObjectId.fromString("ba78e065e2c261d4f7b8f42107588051e87e18ee");
    merge.addFile("foo").setId(anotherId);

    readTree = getCheckoutImpl(head, index, merge);
    readTree.prescanTwoTrees();

    assertEquals(anotherId, readTree.updated().get("foo"));
  }
  private static ChangeKind getChangeKindInternal(
      ChangeKindCache cache,
      ReviewDb db,
      Change change,
      PatchSet patch,
      ChangeData.Factory changeDataFactory,
      ProjectCache projectCache,
      GitRepositoryManager repoManager) {
    Repository repo = null;
    // TODO - dborowitz: add NEW_CHANGE type for default.
    ChangeKind kind = ChangeKind.REWORK;
    // Trivial case: if we're on the first patch, we don't need to open
    // the repository.
    if (patch.getId().get() > 1) {
      try {
        ProjectState projectState = projectCache.checkedGet(change.getProject());

        repo = repoManager.openRepository(change.getProject());

        ChangeData cd = changeDataFactory.create(db, change);
        Collection<PatchSet> patchSetCollection = cd.patches();
        PatchSet priorPs = patch;
        for (PatchSet ps : patchSetCollection) {
          if (ps.getId().get() < patch.getId().get()
              && (ps.getId().get() > priorPs.getId().get() || priorPs == patch)) {
            // We only want the previous patch set, so walk until the last one
            priorPs = ps;
          }
        }

        // If we still think the previous patch is the current patch,
        // we only have one patch set.  Return the default.
        // This can happen if a user creates a draft, uploads a second patch,
        // and deletes the draft.
        if (priorPs != patch) {
          kind =
              cache.getChangeKind(
                  projectState,
                  repo,
                  ObjectId.fromString(priorPs.getRevision().get()),
                  ObjectId.fromString(patch.getRevision().get()));
        }
      } catch (IOException | OrmException e) {
        // Do nothing; assume we have a complex change
        log.warn(
            "Unable to get change kind for patchSet "
                + patch.getPatchSetId()
                + "of change "
                + change.getChangeId(),
            e);
      } finally {
        if (repo != null) {
          repo.close();
        }
      }
    }
    return kind;
  }
  private void writeVerifyPack2(boolean deltaReuse) throws IOException {
    writer.setReuseDeltas(deltaReuse);
    final LinkedList<ObjectId> interestings = new LinkedList<ObjectId>();
    interestings.add(ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
    final LinkedList<ObjectId> uninterestings = new LinkedList<ObjectId>();
    uninterestings.add(ObjectId.fromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"));
    createVerifyOpenPack(interestings, uninterestings, false, false);

    final ObjectId expectedOrder[] =
        new ObjectId[] {
          ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
          ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
          ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
          ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
          ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259"),
          ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")
        };
    if (deltaReuse) {
      // objects order influenced (swapped) by delta-base first rule
      ObjectId temp = expectedOrder[4];
      expectedOrder[4] = expectedOrder[5];
      expectedOrder[5] = temp;
    }
    assertEquals(expectedOrder.length, writer.getObjectsNumber());
    verifyObjectsOrder(expectedOrder);
    assertEquals("ed3f96b8327c7c66b0f8f70056129f0769323d86", writer.computeName().name());
  }
  @Test
  public void testReadIndex_DirCacheTree() throws Exception {
    final Map<String, CGitIndexRecord> cList = readLsFiles();
    final Map<String, CGitLsTreeRecord> cTree = readLsTree();
    final DirCache dc = new DirCache(index, FS.DETECTED);
    assertEquals(0, dc.getEntryCount());
    dc.read();
    assertEquals(cList.size(), dc.getEntryCount());

    final DirCacheTree jTree = dc.getCacheTree(false);
    assertNotNull(jTree);
    assertEquals("", jTree.getNameString());
    assertEquals("", jTree.getPathString());
    assertTrue(jTree.isValid());
    assertEquals(
        ObjectId.fromString("698dd0b8d0c299f080559a1cffc7fe029479a408"), jTree.getObjectId());
    assertEquals(cList.size(), jTree.getEntrySpan());

    final ArrayList<CGitLsTreeRecord> subtrees = new ArrayList<CGitLsTreeRecord>();
    for (final CGitLsTreeRecord r : cTree.values()) {
      if (FileMode.TREE.equals(r.mode)) subtrees.add(r);
    }
    assertEquals(subtrees.size(), jTree.getChildCount());

    for (int i = 0; i < jTree.getChildCount(); i++) {
      final DirCacheTree sj = jTree.getChild(i);
      final CGitLsTreeRecord sc = subtrees.get(i);
      assertEquals(sc.path, sj.getNameString());
      assertEquals(sc.path + "/", sj.getPathString());
      assertTrue(sj.isValid());
      assertEquals(sc.id, sj.getObjectId());
    }
  }
  public void testWriteIndex() throws Exception {
    writer.setIndexVersion(2);
    writeVerifyPack4(false);

    // Validate that IndexPack came up with the right CRC32 value.
    final PackIndex idx1 = PackIndex.open(indexFile);
    assertTrue(idx1 instanceof PackIndexV2);
    assertEquals(
        0x4743F1E4L,
        idx1.findCRC32(ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7")));

    // Validate that an index written by PackWriter is the same.
    final File idx2File = new File(indexFile.getAbsolutePath() + ".2");
    final FileOutputStream is = new FileOutputStream(idx2File);
    try {
      writer.writeIndex(is);
    } finally {
      is.close();
    }
    final PackIndex idx2 = PackIndex.open(idx2File);
    assertTrue(idx2 instanceof PackIndexV2);
    assertEquals(idx1.getObjectCount(), idx2.getObjectCount());
    assertEquals(idx1.getOffset64Count(), idx2.getOffset64Count());

    for (int i = 0; i < idx1.getObjectCount(); i++) {
      final ObjectId id = idx1.getObjectId(i);
      assertEquals(id, idx2.getObjectId(i));
      assertEquals(idx1.findOffset(id), idx2.findOffset(id));
      assertEquals(idx1.findCRC32(id), idx2.findCRC32(id));
    }
  }
示例#7
0
  /**
   * @param project
   * @param commitSHA1
   * @return
   */
  private Run getBuildBySHA1(Job project, String commitSHA1, boolean triggeredByMergeRequest) {
    List<Run> builds = project.getBuilds();
    for (Run build : builds) {
      BuildData data = build.getAction(BuildData.class);
      MergeRecord mergeRecord = build.getAction(MergeRecord.class);
      if (mergeRecord == null) {
        // Determine if build was triggered by a Merge Request event
        ParametersAction params = build.getAction(ParametersAction.class);

        if (params == null) continue;

        StringParameterValue sourceBranch =
            (StringParameterValue) params.getParameter("gitlabSourceBranch");
        StringParameterValue targetBranch =
            (StringParameterValue) params.getParameter("gitlabTargetBranch");
        boolean isMergeRequestBuild =
            (sourceBranch != null && !sourceBranch.value.equals(targetBranch.value));

        if (!triggeredByMergeRequest) {
          if (isMergeRequestBuild)
            // skip Merge Request builds
            continue;

          if (data.getLastBuiltRevision().getSha1String().contains(commitSHA1)) {
            return build;
          }
        } else {
          if (!isMergeRequestBuild)
            // skip Push builds
            continue;

          if (hasBeenBuilt(data, ObjectId.fromString(commitSHA1), build)) {
            return build;
          }
        }

      } else {
        Build b = data.lastBuild;
        boolean isMergeBuild =
            mergeRecord != null && !mergeRecord.getSha1().equals(b.getMarked().getSha1String());
        if (b != null
            && b.getMarked() != null
            && b.getMarked().getSha1String().equals(commitSHA1)) {
          if (triggeredByMergeRequest == isMergeBuild) {
            LOGGER.log(
                Level.FINE,
                build.getNumber()
                    + " Build found matching "
                    + commitSHA1
                    + " "
                    + (isMergeBuild ? "merge" : "normal")
                    + " build");
            return build;
          }
        }
      }
    }
    return null;
  }
 CGitLsTreeRecord(final String line) {
   final int tab = line.indexOf('\t');
   final int sp1 = line.indexOf(' ');
   final int sp2 = line.indexOf(' ', sp1 + 1);
   mode = Integer.parseInt(line.substring(0, sp1), 8);
   id = ObjectId.fromString(line.substring(sp2 + 1, tab));
   path = line.substring(tab + 1);
 }
 /**
  * Try to pass non-existing object as uninteresting, with non-ignoring setting.
  *
  * @throws IOException
  */
 public void testNotIgnoreNonExistingObjects() throws IOException {
   final ObjectId nonExisting = ObjectId.fromString("0000000000000000000000000000000000000001");
   try {
     createVerifyOpenPack(EMPTY_LIST_OBJECT, Collections.nCopies(1, nonExisting), false, false);
     fail("Should have thrown MissingObjectException");
   } catch (MissingObjectException x) {
     // expected
   }
 }
示例#10
0
  private RefList<Ref> parsePackedRefs(final BufferedReader br) throws IOException {
    RefList.Builder<Ref> all = new RefList.Builder<Ref>();
    Ref last = null;
    boolean peeled = false;
    boolean needSort = false;

    String p;
    while ((p = br.readLine()) != null) {
      if (p.charAt(0) == '#') {
        if (p.startsWith(PACKED_REFS_HEADER)) {
          p = p.substring(PACKED_REFS_HEADER.length());
          peeled = p.contains(PACKED_REFS_PEELED);
        }
        continue;
      }

      if (p.charAt(0) == '^') {
        if (last == null) throw new IOException(JGitText.get().peeledLineBeforeRef);

        ObjectId id = ObjectId.fromString(p.substring(1));
        last = new ObjectIdRef.PeeledTag(PACKED, last.getName(), last.getObjectId(), id);
        all.set(all.size() - 1, last);
        continue;
      }

      int sp = p.indexOf(' ');
      if (sp < 0) {
        throw new IOException(
            MessageFormat.format(
                JGitText.get().packedRefsCorruptionDetected, packedRefsFile.getAbsolutePath()));
      }
      ObjectId id = ObjectId.fromString(p.substring(0, sp));
      String name = copy(p, sp + 1, p.length());
      ObjectIdRef cur;
      if (peeled) cur = new ObjectIdRef.PeeledNonTag(PACKED, name, id);
      else cur = new ObjectIdRef.Unpeeled(PACKED, name, id);
      if (last != null && RefComparator.compareTo(last, cur) > 0) needSort = true;
      all.add(cur);
      last = cur;
    }

    if (needSort) all.sort();
    return all.toRefList();
  }
示例#11
0
  @Test
  public void testUnchangedSimple() throws IOException, GitAPIException {
    writeTrashFile("a.b", "a.b");
    writeTrashFile("a.c", "a.c");
    writeTrashFile("a=c", "a=c");
    writeTrashFile("a=d", "a=d");
    try (Git git = new Git(db)) {
      git.add().addFilepattern("a.b").call();
      git.add().addFilepattern("a.c").call();
      git.add().addFilepattern("a=c").call();
      git.add().addFilepattern("a=d").call();
    }

    TreeFormatter tree = new TreeFormatter();
    // got the hash id'd from the data using echo -n a.b|git hash-object -t blob --stdin
    tree.append(
        "a.b",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("f6f28df96c2b40c951164286e08be7c38ec74851"));
    tree.append(
        "a.c",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("6bc0e647512d2a0bef4f26111e484dc87df7f5ca"));
    tree.append(
        "a=c",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("06022365ddbd7fb126761319633bf73517770714"));
    tree.append(
        "a=d",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("fa6414df3da87840700e9eeb7fc261dd77ccd5c2"));
    ObjectId treeId = insertTree(tree);

    FileTreeIterator iterator = new FileTreeIterator(db);
    IndexDiff diff = new IndexDiff(db, treeId, iterator);
    diff.diff();
    assertEquals(0, diff.getChanged().size());
    assertEquals(0, diff.getAdded().size());
    assertEquals(0, diff.getRemoved().size());
    assertEquals(0, diff.getMissing().size());
    assertEquals(0, diff.getModified().size());
    assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders());
  }
 public PatchSetInfo get(Project.NameKey project, PatchSet patchSet)
     throws PatchSetInfoNotAvailableException {
   try (Repository repo = repoManager.openRepository(project);
       RevWalk rw = new RevWalk(repo)) {
     final RevCommit src = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
     PatchSetInfo info = get(rw, src, patchSet.getId());
     info.setParents(toParentInfos(src.getParents(), rw));
     return info;
   } catch (IOException e) {
     throw new PatchSetInfoNotAvailableException(e);
   }
 }
 /**
  * @param repository
  * @return state
  */
 public static CommitMessageComponentState loadState(Repository repository) {
   IDialogSettings dialogSettings = getDialogSettings();
   String[] values = dialogSettings.getArray(repository.getDirectory().getAbsolutePath());
   if (values == null || values.length < MEMBER_COUNT) return null;
   CommitMessageComponentState state = new CommitMessageComponentState();
   state.setAmend(Boolean.parseBoolean(values[0]));
   state.setAuthor(values[1]);
   state.setCommitMessage(values[2]);
   state.setCommitter(values[3]);
   state.setHeadCommit(ObjectId.fromString(values[4]));
   return state;
 }
示例#14
0
  private void writeVerifyPack4(final boolean thin) throws IOException {
    final LinkedList<ObjectId> interestings = new LinkedList<ObjectId>();
    interestings.add(ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
    final LinkedList<ObjectId> uninterestings = new LinkedList<ObjectId>();
    uninterestings.add(ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"));
    createVerifyOpenPack(interestings, uninterestings, thin, false);

    final ObjectId writtenObjects[] =
        new ObjectId[] {
          ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
          ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
          ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259")
        };
    assertEquals(writtenObjects.length, writer.getObjectsNumber());
    ObjectId expectedObjects[];
    if (thin) {
      expectedObjects = new ObjectId[4];
      System.arraycopy(writtenObjects, 0, expectedObjects, 0, writtenObjects.length);
      expectedObjects[3] = ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3");

    } else {
      expectedObjects = writtenObjects;
    }
    verifyObjectsOrder(expectedObjects);
    assertEquals("cded4b74176b4456afa456768b2b5aafb41c44fc", writer.computeName().name());
  }
示例#15
0
 private RevCommit getCommit(Repository repository, String objectId) {
   RevWalk revWalk = null;
   try {
     revWalk = new RevWalk(repository);
     return revWalk.parseCommit(ObjectId.fromString(objectId));
   } catch (Exception e) {
     return null;
   } finally {
     if (revWalk != null) {
       release(revWalk);
     }
   }
 }
示例#16
0
  @Test
  public void testModified() throws IOException, GitAPIException {

    writeTrashFile("file2", "file2");
    writeTrashFile("dir/file3", "dir/file3");

    try (Git git = new Git(db)) {
      git.add().addFilepattern("file2").addFilepattern("dir/file3").call();
    }

    writeTrashFile("dir/file3", "changed");

    TreeFormatter dir = new TreeFormatter();
    dir.append(
        "file3",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("0123456789012345678901234567890123456789"));

    TreeFormatter tree = new TreeFormatter();
    tree.append("dir", FileMode.TREE, insertTree(dir));
    tree.append(
        "file2",
        FileMode.REGULAR_FILE,
        ObjectId.fromString("0123456789012345678901234567890123456789"));
    ObjectId treeId = insertTree(tree);

    FileTreeIterator iterator = new FileTreeIterator(db);
    IndexDiff diff = new IndexDiff(db, treeId, iterator);
    diff.diff();
    assertEquals(2, diff.getChanged().size());
    assertTrue(diff.getChanged().contains("file2"));
    assertTrue(diff.getChanged().contains("dir/file3"));
    assertEquals(1, diff.getModified().size());
    assertTrue(diff.getModified().contains("dir/file3"));
    assertEquals(0, diff.getAdded().size());
    assertEquals(0, diff.getRemoved().size());
    assertEquals(0, diff.getMissing().size());
    assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders());
  }
示例#17
0
 public List<String> readElementsAt(Repository repository, String commit) throws IOException {
   RevWalk revWalk = new RevWalk(repository);
   RevCommit revCommit = revWalk.parseCommit(ObjectId.fromString(commit));
   RevTree tree = revCommit.getTree();
   List<String> items = new ArrayList<>();
   TreeWalk treeWalk = new TreeWalk(repository);
   treeWalk.addTree(tree);
   treeWalk.setRecursive(true);
   treeWalk.setPostOrderTraversal(true);
   while (treeWalk.next()) {
     items.add(treeWalk.getPathString());
   }
   return items;
 }
示例#18
0
  private void recvCommands() throws IOException {
    for (; ; ) {
      String line;
      try {
        line = pckIn.readStringRaw();
      } catch (EOFException eof) {
        if (commands.isEmpty()) return;
        throw eof;
      }
      if (line == PacketLineIn.END) break;

      if (commands.isEmpty()) {
        final int nul = line.indexOf('\0');
        if (nul >= 0) {
          for (String c : line.substring(nul + 1).split(" ")) enabledCapablities.add(c);
          line = line.substring(0, nul);
        }
      }

      if (line.length() < 83) {
        final String m = JGitText.get().errorInvalidProtocolWantedOldNewRef;
        sendError(m);
        throw new PackProtocolException(m);
      }

      final ObjectId oldId = ObjectId.fromString(line.substring(0, 40));
      final ObjectId newId = ObjectId.fromString(line.substring(41, 81));
      final String name = line.substring(82);
      final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name);
      if (name.equals(Constants.HEAD)) {
        cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
      } else {
        cmd.setRef(refs.get(cmd.getRefName()));
      }
      commands.add(cmd);
    }
  }
 private void saveOriginalChangeId() {
   int changeIdOffset = findOffsetOfChangeIdLine(previousCommitMessage);
   if (changeIdOffset > 0) {
     int endOfChangeId = findNextEOL(changeIdOffset, previousCommitMessage);
     if (endOfChangeId < 0) endOfChangeId = previousCommitMessage.length();
     int sha1Offset =
         changeIdOffset + Text.DELIMITER.length() + "Change-Id: I".length(); // $NON-NLS-1$
     try {
       originalChangeId =
           ObjectId.fromString(previousCommitMessage.substring(sha1Offset, endOfChangeId));
     } catch (IllegalArgumentException e) {
       originalChangeId = null;
     }
   } else originalChangeId = null;
 }
示例#20
0
  private void writeVerifyPack1() throws IOException {
    final LinkedList<ObjectId> interestings = new LinkedList<ObjectId>();
    interestings.add(ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
    createVerifyOpenPack(interestings, EMPTY_LIST_OBJECT, false, false);

    final ObjectId expectedOrder[] =
        new ObjectId[] {
          ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
          ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
          ObjectId.fromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"),
          ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
          ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
          ObjectId.fromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"),
          ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259"),
          ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")
        };

    assertEquals(expectedOrder.length, writer.getObjectsNumber());
    verifyObjectsOrder(expectedOrder);
    assertEquals("34be9032ac282b11fa9babdc2b2a93ca996c9c2f", writer.computeName().name());
  }
示例#21
0
  @Override
  public byte[] getData(String commitName, String filePath) {

    try {

      RevCommit revCommit = revWalk.parseCommit(ObjectId.fromString(commitName));
      RevTree tree = revCommit.getTree();
      TreeWalk treeWalk = TreeWalk.forPath(reader, filePath, tree);

      if (treeWalk == null) return null;
      else return reader.open(treeWalk.getObjectId(0)).getBytes();

    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
示例#22
0
  public List<ObjectId> revList(String... extraArgs) throws GitException {
    List<ObjectId> entries = new ArrayList<ObjectId>();
    ArgumentListBuilder args = new ArgumentListBuilder("rev-list");
    args.add(extraArgs);
    String result = launchCommand(args);
    BufferedReader rdr = new BufferedReader(new StringReader(result));
    String line;

    try {
      while ((line = rdr.readLine()) != null) {
        // Add the SHA1
        entries.add(ObjectId.fromString(line));
      }
    } catch (IOException e) {
      throw new GitException("Error parsing rev list", e);
    }

    return entries;
  }
示例#23
0
  public ObjectId mergeBase(ObjectId id1, ObjectId id2) {
    try {
      String result;
      try {
        result = launchCommand("merge-base", id1.name(), id2.name());
      } catch (GitException ge) {
        return null;
      }

      BufferedReader rdr = new BufferedReader(new StringReader(result));
      String line;

      while ((line = rdr.readLine()) != null) {
        // Add the SHA1
        return ObjectId.fromString(line);
      }
    } catch (Exception e) {
      throw new GitException("Error parsing merge base", e);
    }

    return null;
  }
    private Ref readRef(final TreeMap<String, Ref> avail, final String rn)
        throws TransportException {
      final String s;
      String ref = ROOT_DIR + rn;
      try {
        final BufferedReader br = openReader(ref);
        try {
          s = br.readLine();
        } finally {
          br.close();
        }
      } catch (FileNotFoundException noRef) {
        return null;
      } catch (IOException err) {
        throw new TransportException(getURI(), "read " + ref, err);
      }

      if (s == null) throw new TransportException(getURI(), "Empty ref: " + rn);

      if (s.startsWith("ref: ")) {
        final String target = s.substring("ref: ".length());
        Ref r = avail.get(target);
        if (r == null) r = readRef(avail, target);
        if (r == null) return null;
        r = new Ref(r.getStorage(), rn, r.getObjectId(), r.getPeeledObjectId(), r.isPeeled());
        avail.put(r.getName(), r);
        return r;
      }

      if (ObjectId.isId(s)) {
        final Ref r = new Ref(loose(avail.get(rn)), rn, ObjectId.fromString(s));
        avail.put(r.getName(), r);
        return r;
      }

      throw new TransportException(getURI(), "Bad ref: " + rn + ": " + s);
    }
示例#25
0
  /**
   * Create pack basing on fixed objects list, then precisely verify content. No delta reuse here.
   *
   * @throws IOException
   * @throws MissingObjectException
   */
  public void testWritePack3() throws MissingObjectException, IOException {
    writer.setReuseDeltas(false);
    final ObjectId forcedOrder[] =
        new ObjectId[] {
          ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
          ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
          ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
          ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
          ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259"),
          ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")
        };
    final RevWalk parser = new RevWalk(db);
    final RevObject forcedOrderRevs[] = new RevObject[forcedOrder.length];
    for (int i = 0; i < forcedOrder.length; i++)
      forcedOrderRevs[i] = parser.parseAny(forcedOrder[i]);

    createVerifyOpenPack(Arrays.asList(forcedOrderRevs).iterator());

    assertEquals(forcedOrder.length, writer.getObjectsNumber());
    verifyObjectsOrder(forcedOrder);
    assertEquals("ed3f96b8327c7c66b0f8f70056129f0769323d86", writer.computeName().name());
  }
示例#26
0
 private ObjectId getCurrentRevisionId(String changeId) throws RestApiException {
   return ObjectId.fromString(gApi.changes().id(changeId).get().currentRevision);
 }
示例#27
0
  LooseRef scanRef(LooseRef ref, String name) throws IOException {
    final File path = fileFor(name);
    FileSnapshot currentSnapshot = null;

    if (ref != null) {
      currentSnapshot = ref.getSnapShot();
      if (!currentSnapshot.isModified(path)) return ref;
      name = ref.getName();
    }

    final int limit = 4096;
    final byte[] buf;
    FileSnapshot otherSnapshot = FileSnapshot.save(path);
    try {
      buf = IO.readSome(path, limit);
    } catch (FileNotFoundException noFile) {
      if (path.exists() && path.isFile()) {
        throw noFile;
      }
      return null; // doesn't exist or no file; not a reference.
    }

    int n = buf.length;
    if (n == 0) return null; // empty file; not a reference.

    if (isSymRef(buf, n)) {
      if (n == limit) return null; // possibly truncated ref

      // trim trailing whitespace
      while (0 < n && Character.isWhitespace(buf[n - 1])) n--;
      if (n < 6) {
        String content = RawParseUtils.decode(buf, 0, n);
        throw new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
      }
      final String target = RawParseUtils.decode(buf, 5, n);
      if (ref != null && ref.isSymbolic() && ref.getTarget().getName().equals(target)) {
        assert (currentSnapshot != null);
        currentSnapshot.setClean(otherSnapshot);
        return ref;
      }
      return newSymbolicRef(otherSnapshot, name, target);
    }

    if (n < OBJECT_ID_STRING_LENGTH)
      return null; // impossibly short object identifier; not a reference.

    final ObjectId id;
    try {
      id = ObjectId.fromString(buf, 0);
      if (ref != null && !ref.isSymbolic() && id.equals(ref.getTarget().getObjectId())) {
        assert (currentSnapshot != null);
        currentSnapshot.setClean(otherSnapshot);
        return ref;
      }

    } catch (IllegalArgumentException notRef) {
      while (0 < n && Character.isWhitespace(buf[n - 1])) n--;
      String content = RawParseUtils.decode(buf, 0, n);

      IOException ioException =
          new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
      ioException.initCause(notRef);
      throw ioException;
    }
    return new LooseUnpeeled(otherSnapshot, name, id);
  }
示例#28
0
 public ObjectId validateRevision(String revName) throws GitException {
   String result = launchCommand("rev-parse", "--verify", revName);
   return ObjectId.fromString(firstLine(result).trim());
 }
示例#29
0
 private static ObjectId id(String name) {
   return ObjectId.fromString(name);
 }
示例#30
0
 /**
  * Try to pass non-existing object as uninteresting, with ignoring setting.
  *
  * @throws IOException
  */
 public void testIgnoreNonExistingObjects() throws IOException {
   final ObjectId nonExisting = ObjectId.fromString("0000000000000000000000000000000000000001");
   createVerifyOpenPack(EMPTY_LIST_OBJECT, Collections.nCopies(1, nonExisting), false, true);
   // shouldn't throw anything
 }