示例#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
  public CodeReviewCommit createCherryPickFromCommit(
      Repository repo,
      ObjectInserter inserter,
      RevCommit mergeTip,
      RevCommit originalCommit,
      PersonIdent cherryPickCommitterIdent,
      String commitMsg,
      CodeReviewRevWalk rw)
      throws MissingObjectException, IncorrectObjectTypeException, IOException,
          MergeIdenticalTreeException, MergeConflictException {

    final ThreeWayMerger m = newThreeWayMerger(repo, inserter);

    m.setBase(originalCommit.getParent(0));
    if (m.merge(mergeTip, originalCommit)) {
      ObjectId tree = m.getResultTreeId();
      if (tree.equals(mergeTip.getTree())) {
        throw new MergeIdenticalTreeException("identical tree");
      }

      CommitBuilder mergeCommit = new CommitBuilder();
      mergeCommit.setTreeId(tree);
      mergeCommit.setParentId(mergeTip);
      mergeCommit.setAuthor(originalCommit.getAuthorIdent());
      mergeCommit.setCommitter(cherryPickCommitterIdent);
      mergeCommit.setMessage(commitMsg);
      return rw.parseCommit(commit(inserter, mergeCommit));
    } else {
      throw new MergeConflictException("merge conflict");
    }
  }
示例#3
0
  @Test
  public void testAbbreviateOnEmptyRepository() throws IOException {
    ObjectId id = id("9d5b926ed164e8ee88d3b8b1e525d699adda01ba");

    assertEquals(id.abbreviate(2), reader.abbreviate(id, 2));
    assertEquals(id.abbreviate(7), reader.abbreviate(id, 7));
    assertEquals(id.abbreviate(8), reader.abbreviate(id, 8));
    assertEquals(id.abbreviate(10), reader.abbreviate(id, 10));
    assertEquals(id.abbreviate(16), reader.abbreviate(id, 16));

    assertEquals(
        AbbreviatedObjectId.fromObjectId(id), //
        reader.abbreviate(id, OBJECT_ID_STRING_LENGTH));

    Collection<ObjectId> matches;

    matches = reader.resolve(reader.abbreviate(id, 8));
    assertNotNull(matches);
    assertEquals(0, matches.size());

    matches = reader.resolve(AbbreviatedObjectId.fromObjectId(id));
    assertNotNull(matches);
    assertEquals(1, matches.size());
    assertEquals(id, matches.iterator().next());
  }
示例#4
0
 @NotNull
 private String createRemoteFile(
     @NotNull ObjectId id, @NotNull ObjectLoader loader, @NotNull Uploader uploader)
     throws IOException {
   // Create LFS stream.
   final String hash;
   final String cached = cacheSha256.get(id.name());
   long size = 0;
   if (cached == null) {
     final MessageDigest md = createSha256();
     try (InputStream istream = loader.openStream()) {
       byte[] buffer = new byte[0x10000];
       while (true) {
         int read = istream.read(buffer);
         if (read <= 0) break;
         md.update(buffer, 0, read);
         size += read;
       }
     }
     hash = new String(Hex.encodeHex(md.digest(), true));
     cacheSha256.put(id.name(), hash);
     cache.commit();
   } else {
     hash = cached;
   }
   uploader.upload(id, new Meta(hash, size));
   return hash;
 }
示例#5
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"));
  }
示例#6
0
  /**
   * Return a list of 'tip' branches (I.E. branches that aren't included entirely within another
   * branch).
   *
   * @param git
   * @return
   */
  public Collection<Revision> filterTipBranches(Collection<Revision> revisions) {
    // If we have 3 branches that we might want to build
    // ----A--.---.--- B
    //        \-----C

    // we only want (B) and (C), as (A) is an ancestor (old).

    List<Revision> l = new ArrayList<Revision>(revisions);

    OUTER:
    for (int i = 0; i < l.size(); i++) {
      for (int j = i + 1; j < l.size(); j++) {
        Revision ri = l.get(i);
        Revision rj = l.get(j);
        ObjectId commonAncestor = git.mergeBase(ri.getSha1(), rj.getSha1());
        if (commonAncestor == null) {
          continue;
        }

        if (commonAncestor.equals(ri.getSha1())) {
          LOGGER.fine("filterTipBranches: " + rj + " subsumes " + ri);
          l.remove(i);
          i--;
          continue OUTER;
        }
        if (commonAncestor.equals(rj.getSha1())) {
          LOGGER.fine("filterTipBranches: " + ri + " subsumes " + rj);
          l.remove(j);
          j--;
        }
      }
    }

    return l;
  }
示例#7
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();
    }
  }
示例#8
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();
    }
  }
  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;
  }
示例#10
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);
   }
 }
示例#11
0
  public List<Tag> getTagsOnCommit(final String revName) throws GitException, IOException {
    final Repository db = getRepository();
    final ObjectId commit = db.resolve(revName);
    final List<Tag> ret = new ArrayList<Tag>();

    for (final Map.Entry<String, Ref> tag : db.getTags().entrySet()) {
      final ObjectId tagId = tag.getValue().getObjectId();
      if (commit.equals(tagId)) ret.add(new Tag(tag.getKey(), tagId));
    }
    return ret;
  }
  private boolean commitIndex(Repository db, DirCache index, String author, String message)
      throws IOException, ConcurrentRefUpdateException {
    boolean success = false;

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

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

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

      try (RevWalk revWalk = new RevWalk(db)) {
        RevCommit revCommit = revWalk.parseCommit(commitId);
        RefUpdate ru = db.updateRef(BRANCH);
        ru.setNewObjectId(commitId);
        ru.setExpectedOldObjectId(headId);
        ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
        Result rc = ru.forceUpdate();
        switch (rc) {
          case NEW:
          case FORCED:
          case FAST_FORWARD:
            success = true;
            break;
          case REJECTED:
          case LOCK_FAILURE:
            throw new ConcurrentRefUpdateException(
                JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
          default:
            throw new JGitInternalException(
                MessageFormat.format(
                    JGitText.get().updatingRefFailed, BRANCH, commitId.toString(), rc));
        }
      }
    }
    return success;
  }
示例#13
0
 @Override
 public void commitAll(final String authorName, final String authorEmail, final String comment) {
   try {
     stageChanges(git);
     logStatus(git);
     final ObjectId commitId = commit(authorName, authorEmail, comment);
     LOG.info(
         "{} Committed all staged changes in repository '{}'", commitId.toString(), repository);
   } catch (GitAPIException e) {
     throw new SvcFailedException(e);
   }
 }
示例#14
0
  @Override
  public Revision decorateRevisionToBuild(
      GitSCM scm, AbstractBuild<?, ?> build, GitClient git, BuildListener listener, Revision rev)
      throws IOException, InterruptedException {
    String remoteBranchRef =
        GitSCM.getParameterString(options.getRef(), build.getEnvironment(listener));

    // if the branch we are merging is already at the commit being built, the entire merge becomes
    // no-op
    // so there's nothing to do
    if (rev.containsBranchName(remoteBranchRef)) return rev;

    // Only merge if there's a branch to merge that isn't us..
    listener
        .getLogger()
        .println(
            "Merging "
                + rev
                + " onto "
                + remoteBranchRef
                + " using "
                + scm.getUserMergeOptions().getMergeStrategy().toString()
                + " strategy");

    // checkout origin/blah
    ObjectId target = git.revParse(remoteBranchRef);

    String paramLocalBranch = scm.getParamLocalBranch(build);
    git.checkoutBranch(paramLocalBranch, remoteBranchRef);

    try {
      MergeCommand cmd = git.merge().setRevisionToMerge(rev.getSha1());
      for (GitSCMExtension ext : scm.getExtensions())
        ext.decorateMergeCommand(scm, build, git, listener, cmd);
      cmd.execute();
    } catch (GitException ex) {
      // merge conflict. First, avoid leaving any conflict markers in the working tree
      // by checking out some known clean state. We don't really mind what commit this is,
      // since the next build is going to pick its own commit to build, but 'rev' is as good any.
      git.checkoutBranch(paramLocalBranch, rev.getSha1String());

      // record the fact that we've tried building 'rev' and it failed, or else
      // BuildChooser in future builds will pick up this same 'rev' again and we'll see the exact
      // same merge failure
      // all over again.
      scm.getBuildData(build).saveBuild(new Build(rev, build.getNumber(), FAILURE));
      throw new AbortException("Branch not suitable for integration as it does not merge cleanly");
    }

    build.addAction(new MergeRecord(remoteBranchRef, target.getName()));

    return new GitUtils(listener, git).getRevisionForSHA1(git.revParse(HEAD));
  }
示例#15
0
 private void insertChangeId(ObjectId treeId) throws IOException {
   ObjectId firstParentId = null;
   if (!parents.isEmpty()) firstParentId = parents.get(0);
   ObjectId changeId =
       ChangeIdUtil.computeChangeId(treeId, firstParentId, author, committer, message);
   message = ChangeIdUtil.insertId(message, changeId);
   if (changeId != null)
     message =
         message.replaceAll(
             "\nChange-Id: I" + ObjectId.zeroId().getName() + "\n",
             "\nChange-Id: I" + changeId.getName() + "\n");
 }
示例#16
0
  /**
   * Format this builder's state as a commit object.
   *
   * <p>As a side effect, {@link #getCommitId()} will be populated with the proper ObjectId for the
   * formatted content.
   *
   * @param oi the inserter whose formatting support will be reused. The inserter itself is not
   *     affected, and the commit is not actually inserted into the repository.
   * @return this object in the canonical commit format, suitable for storage in a repository.
   * @throws UnsupportedEncodingException the encoding specified by {@link #getEncoding()} is not
   *     supported by this Java runtime.
   */
  public byte[] format(ObjectInserter oi) throws UnsupportedEncodingException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os, getEncoding());
    try {
      os.write(htree);
      os.write(' ');
      getTreeId().copyTo(os);
      os.write('\n');

      for (ObjectId p : getParentIds()) {
        os.write(hparent);
        os.write(' ');
        p.copyTo(os);
        os.write('\n');
      }

      os.write(hauthor);
      os.write(' ');
      w.write(getAuthor().toExternalString());
      w.flush();
      os.write('\n');

      os.write(hcommitter);
      os.write(' ');
      w.write(getCommitter().toExternalString());
      w.flush();
      os.write('\n');

      if (getEncoding() != Constants.CHARSET) {
        os.write(hencoding);
        os.write(' ');
        os.write(Constants.encodeASCII(getEncoding().name()));
        os.write('\n');
      }

      os.write('\n');

      if (getMessage() != null) {
        w.write(getMessage());
        w.flush();
      }
    } catch (IOException err) {
      // This should never occur, the only way to get it above is
      // for the ByteArrayOutputStream to throw, but it doesn't.
      //
      throw new RuntimeException(err);
    }

    byte[] content = os.toByteArray();
    setCommitId(oi.idFor(Constants.OBJ_COMMIT, content));
    return content;
  }
示例#17
0
 /**
  * Creates a new branch
  *
  * @param refName starting point for the new branch
  * @param newRefName
  * @throws IOException
  */
 public void createBranch(String refName, String newRefName) throws IOException {
   RefUpdate updateRef;
   updateRef = repository.updateRef(newRefName);
   Ref startRef = repository.getRef(refName);
   ObjectId startAt = repository.resolve(refName);
   String startBranch;
   if (startRef != null) startBranch = refName;
   else startBranch = startAt.name();
   startBranch = Repository.shortenRefName(startBranch);
   updateRef.setNewObjectId(startAt);
   updateRef.setRefLogMessage("branch: Created from " + startBranch, false); // $NON-NLS-1$
   updateRef.update();
 }
 private Git.Head getHead(final Repository repository) throws IOException {
   ObjectId revision = repository.resolve(Constants.HEAD);
   RevCommit commit = new RevWalk(repository).parseCommit(revision);
   Git.Head head =
       new Git.Head(
           revision.getName(),
           commit.getAuthorIdent().getName(),
           commit.getAuthorIdent().getEmailAddress(),
           commit.getCommitterIdent().getName(),
           commit.getCommitterIdent().getEmailAddress(),
           commit.getFullMessage());
   return head;
 }
 private Key(
     ProjectState project,
     Repository repo,
     ObjectId prior,
     ObjectId next,
     boolean useRecursiveMerge) {
   checkNotNull(next, "next");
   String strategyName =
       MergeUtil.mergeStrategyName(project.isUseContentMerge(), useRecursiveMerge);
   this.prior = prior.copy();
   this.next = next.copy();
   this.strategyName = strategyName;
   this.repo = repo;
 }
示例#20
0
  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());
  }
示例#21
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);
  }
示例#22
0
 @NotNull
 private String createLocalFile(@NotNull ObjectId id, @NotNull ObjectLoader loader)
     throws IOException {
   // Create LFS stream.
   final File tmpFile = new File(tempPath, UUID.randomUUID().toString());
   final MessageDigest md = createSha256();
   try (InputStream istream = loader.openStream();
       OutputStream ostream = new FileOutputStream(tmpFile)) {
     byte[] buffer = new byte[0x10000];
     while (true) {
       int size = istream.read(buffer);
       if (size <= 0) break;
       ostream.write(buffer, 0, size);
       md.update(buffer, 0, size);
     }
   }
   final String hash = new String(Hex.encodeHex(md.digest(), true));
   cacheSha256.putIfAbsent(id.name(), hash);
   cache.commit();
   // Rename file.
   final File lfsFile =
       new File(
           basePath,
           "lfs/objects/" + hash.substring(0, 2) + "/" + hash.substring(2, 4) + "/" + hash);
   makeParentDirs(lfsFile.getParentFile());
   if (lfsFile.exists()) {
     if (!tmpFile.delete()) {
       log.warn("Can't delete temporary file: {}", lfsFile.getAbsolutePath());
     }
   } else if (!tmpFile.renameTo(lfsFile)) {
     throw new IOException("Can't rename file: " + tmpFile + " -> " + lfsFile);
   }
   return hash;
 }
  @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());
    }
  }
示例#24
0
  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));
    }
  }
示例#25
0
/** @author taichi */
public class BlobModel extends BasicGitModel {

  ObjectId objectId = ObjectId.zeroId();

  String content;

  public BlobModel() {}

  public BlobModel(BlobModel src) {
    super(src);
    this.objectId = src.objectId;
    this.content = src.content;
  }

  public ObjectId getObjectId() {
    return this.objectId;
  }

  public void setObjectId(ObjectId objectid) {
    this.objectId = objectid;
  }

  public String getContent() {
    return this.content;
  }

  public void setContent(String content) {
    this.content = content;
  }
}
示例#26
0
 /**
  * The constructor
  *
  * @param base the base configuration file
  * @param cfgLocation the location of the configuration file on the file system
  * @param fs the file system abstraction which will be necessary to perform certain file system
  *     operations.
  */
 public FileBasedConfig(Config base, File cfgLocation, FS fs) {
   super(base);
   configFile = cfgLocation;
   this.fs = fs;
   this.snapshot = FileSnapshot.DIRTY;
   this.hash = ObjectId.zeroId();
 }
示例#27
0
  private void execute(final ReceiveCommand cmd) {
    try {
      final RefUpdate ru = db.updateRef(cmd.getRefName());
      ru.setRefLogIdent(getRefLogIdent());
      switch (cmd.getType()) {
        case DELETE:
          if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            // We can only do a CAS style delete if the client
            // didn't bork its delete request by sending the
            // wrong zero id rather than the advertised one.
            //
            ru.setExpectedOldObjectId(cmd.getOldId());
          }
          ru.setForceUpdate(true);
          status(cmd, ru.delete(walk));
          break;

        case CREATE:
        case UPDATE:
        case UPDATE_NONFASTFORWARD:
          ru.setForceUpdate(isAllowNonFastForwards());
          ru.setExpectedOldObjectId(cmd.getOldId());
          ru.setNewObjectId(cmd.getNewId());
          ru.setRefLogMessage("push", true);
          status(cmd, ru.update(walk));
          break;
      }
    } catch (IOException err) {
      cmd.setResult(
          Result.REJECTED_OTHER_REASON,
          MessageFormat.format(JGitText.get().lockError, err.getMessage()));
    }
  }
示例#28
0
  private RefUpdate getPendingRefUpdate(Branch.NameKey destBranch) throws IntegrationException {

    if (pendingRefUpdates.containsKey(destBranch)) {
      logDebug("Access cached open branch {}: {}", destBranch.get(), openBranches.get(destBranch));
      return pendingRefUpdates.get(destBranch);
    }

    try {
      RefUpdate branchUpdate = repo.updateRef(destBranch.get());
      CodeReviewCommit branchTip;
      if (branchUpdate.getOldObjectId() != null) {
        branchTip = rw.parseCommit(branchUpdate.getOldObjectId());
      } else if (Objects.equals(repo.getFullBranch(), destBranch.get())) {
        branchTip = null;
        branchUpdate.setExpectedOldObjectId(ObjectId.zeroId());
      } else {
        throw new IntegrationException(
            "The destination branch " + destBranch.get() + " does not exist anymore.");
      }

      logDebug("Opened branch {}: {}", destBranch.get(), branchTip);
      pendingRefUpdates.put(destBranch, branchUpdate);
      openBranches.put(destBranch, branchTip);
      return branchUpdate;
    } catch (IOException e) {
      throw new IntegrationException("Cannot open branch", e);
    }
  }
示例#29
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;
  }
  @Test(groups = {"UT"})
  public void insertTest() throws IOException {
    final String expectedId = "7fdc3a7439847844b4fccc4b9e4700ab72c7e11e";
    String strdata = "this is a blob !";
    byte[] rawdata = strdata.getBytes(Charset.defaultCharset());
    when(dbMock.has((AnyObjectId) Mockito.anyObject())).thenReturn(true);
    undertest.insert(Constants.OBJ_BLOB, rawdata);

    when(dbMock.has((AnyObjectId) Mockito.anyObject())).thenReturn(false);
    ObjectId id = undertest.insert(Constants.OBJ_BLOB, rawdata);
    assertNotNull(id);
    assertEquals(id.name(), expectedId);
    Objectify ofy = ObjectifyService.begin();
    AppengineObject obj = ofy.get(AppengineObject.class, expectedId);
    assertNotNull(obj);
    assertEquals(obj.getObjectId(), expectedId);
  }