Java 类org.eclipse.jgit.lib.ObjectInserter 实例源码

项目:gmds    文件:Utils.java   
/**
     *
     * @param dbmdJson
     * @param repo
     * @param tree
     * @param conn
     * @param clmnTree
     * @return
     * @throws IOException
     * @throws SQLException
     */
    public static ObjectId metaTreeCommit(ObjectJson dbmdJson, Repository repo, TreeFormatter tree, 
            Connection conn, Boolean clmnTree) throws IOException, SQLException {

        DatabaseMetaData dbmd = conn.getMetaData();
//        ObjectJson dbmdJson = new ObjectJson();
        String mapString = metaDbInfo(dbmd);
        ObjectInserter objectInserter = repo.newObjectInserter();
        ObjectId blobId = objectInserter.insert(Constants.OBJ_BLOB, mapString.getBytes());
        objectInserter.flush();

        tree.append(Consts.DATABASE, FileMode.REGULAR_FILE, blobId);
        Utils.putTableMeta(repo, conn, dbmd, objectInserter, tree, clmnTree);

        ObjectId treeId = objectInserter.insert(tree);
        objectInserter.flush();

        System.out.println("Tree ID: " + treeId.getName());

        return treeId;
    }
项目:gmds    文件:Utils.java   
/**
     *
     * @param datarepo
     * @param tree
     * @param conn
     * @param clmnTree
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public static ObjectId dataTreeCommit(Repository datarepo, TreeFormatter tree, Connection conn, Boolean clmnTree) throws SQLException, IOException {
        DatabaseMetaData dbmd = conn.getMetaData();
//        ObjectJson dbmdJson = new ObjectJson();
        String mapString = metaDbInfo(dbmd);

        // Build Db_Info object, general info about Database
        ObjectInserter objectInserter = datarepo.newObjectInserter();
        ObjectId blobId = objectInserter.insert(Constants.OBJ_BLOB, mapString.getBytes());
        objectInserter.flush();

        tree.append("DATABASE", FileMode.REGULAR_FILE, blobId);

        // Continue building Database Tree
        Utils.putTableMeta(datarepo, conn, dbmd, objectInserter, tree, clmnTree);

        ObjectId treeId = objectInserter.insert(tree);
        objectInserter.flush();

        System.out.println("Tree ID: " + treeId.getName());

        return treeId;
    }
项目:gmds    文件:Utils.java   
/**
 * 
 * @param columns
 * @param objectInserter
 * @param tblTree
 * @param walkTbl
 * @return
 * @throws SQLException
 * @throws IOException 
 */
public static ObjectId putColumnMetaAsObject(ResultSet columns, 
        ObjectInserter objectInserter, TreeFormatter tblTree, RevWalk walkTbl) throws SQLException, IOException {

    // Build object for column attributs
    ObjectId objectId = buildMetaObject(columns, Consts.COLUMN_META_ATTRIBUTES, objectInserter);

    tblTree.append(Consts.COLUMN_META, FileMode.REGULAR_FILE, (AnyObjectId) objectId);

    // Add empty tree for the column content
    TreeFormatter clmnDataTree = new TreeFormatter();
    ObjectId clmnDataTreeId = objectInserter.insert(clmnDataTree);
    objectInserter.flush();

    tblTree.append(Consts.COLUMN_DATA, walkTbl.parseTree(clmnDataTreeId));

    return objectId;
}
项目:gmds    文件:Utils.java   
/**
 *
 * @param columns
 * @param objectInserter
 * @param tblTree
 * @param walkTbl
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static ObjectId putColumnMetaAsTree(ResultSet columns, 
        ObjectInserter objectInserter, TreeFormatter tblTree, RevWalk walkTbl) throws SQLException, IOException {

    // Add tree for the column Metadata
    TreeFormatter clmnMetaTree = new TreeFormatter();

    // Build tree for column attributs
    buildMetaTree(columns, Consts.COLUMN_META_ATTRIBUTES, objectInserter, clmnMetaTree);

    ObjectId clmnMetaTreeId = objectInserter.insert(clmnMetaTree);
    objectInserter.flush();

    tblTree.append(Consts.COLUMN_META, walkTbl.parseTree(clmnMetaTreeId));

    // Add empty tree for the column content
    TreeFormatter clmnDataTree = new TreeFormatter();
    ObjectId clmnDataTreeId = objectInserter.insert(clmnDataTree);
    objectInserter.flush();

    tblTree.append(Consts.COLUMN_DATA, walkTbl.parseTree(clmnDataTreeId));

    return clmnMetaTreeId;
}
项目:gmds    文件:Utils.java   
private static ObjectId buildMetaTree(ResultSet set, String[] attrs, ObjectInserter inserter, TreeFormatter tree) throws IOException, SQLException {

        for (String attr : attrs) {
            ObjectJson objectJson = new ObjectJson();
            objectJson.addDoc(attr, set.getString(attr));

            String attrJson = new Map2JsonString().convert(objectJson.getObjectAsMap());
            ObjectId objectId = inserter.insert(Constants.OBJ_BLOB, attrJson.getBytes());
            inserter.flush();

            System.out.println("MetaObject: " + attrJson);
//            commitJson.addDoc(Consts.OBJECT_ID, objectId);

            tree.append(attr, FileMode.REGULAR_FILE, objectId);
        }
        return tree.computeId(inserter);
    }
项目:GitDirStat    文件:CacheTreeUpdate.java   
/**
 * Apply the changes that this {@link TreeUpdate} represents to the given
 * {@link DirCache}. The {@link DirCache} will be unlocked if was modified.
 *
 * @param dirCache
 * @return true if updates are applied to the {@link DirCache}, false if the
 *         {@link DirCache} has not been modified.
 */
public ObjectId apply(ObjectInserter objectInserter) {
    ObjectId newTreeId = null;
    if (hasUpdates()) {
        DirCacheEditor editor = index.editor();

        for (PathEdit pathEdit : pathEdits) {
            editor.add(pathEdit);
        }

        editor.finish();

        try {
            // Write the index as tree to the object database. This may
            // fail for example when the index contains unmerged paths
            // (unresolved conflicts)
            newTreeId = index.writeTree(objectInserter);
        } catch (IOException e) {
            throw new GitRepositoryException(e);
        }
    }
    return newTreeId;
}
项目:gerrit    文件:PublicKeyStore.java   
private void saveToNotes(ObjectInserter ins, PGPPublicKeyRing keyRing)
    throws PGPException, IOException {
  long keyId = keyRing.getPublicKey().getKeyID();
  PGPPublicKeyRingCollection existing = get(keyId);
  List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size() + 1);
  boolean replaced = false;
  for (PGPPublicKeyRing kr : existing) {
    if (sameKey(keyRing, kr)) {
      toWrite.add(keyRing);
      replaced = true;
    } else {
      toWrite.add(kr);
    }
  }
  if (!replaced) {
    toWrite.add(keyRing);
  }
  notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite)));
}
项目:gerrit    文件:PublicKeyStore.java   
private void deleteFromNotes(ObjectInserter ins, Fingerprint fp)
    throws PGPException, IOException {
  long keyId = fp.getId();
  PGPPublicKeyRingCollection existing = get(keyId);
  List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size());
  for (PGPPublicKeyRing kr : existing) {
    if (!fp.equalsBytes(kr.getPublicKey().getFingerprint())) {
      toWrite.add(kr);
    }
  }
  if (toWrite.size() == existing.size()) {
    return;
  } else if (!toWrite.isEmpty()) {
    notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite)));
  } else {
    notes.remove(keyObjectId(keyId));
  }
}
项目:gerrit    文件:ChangeRebuilderIT.java   
@Test
public void rebuildDeletesOldDraftRefs() throws Exception {
  PushOneCommit.Result r = createChange();
  Change.Id id = r.getPatchSetId().getParentKey();
  putDraft(user, id, 1, "comment", null);

  Account.Id otherAccountId = new Account.Id(user.getId().get() + 1234);
  String otherDraftRef = refsDraftComments(id, otherAccountId);

  try (Repository repo = repoManager.openRepository(allUsers);
      ObjectInserter ins = repo.newObjectInserter()) {
    ObjectId sha = ins.insert(OBJ_BLOB, "garbage data".getBytes(UTF_8));
    ins.flush();
    RefUpdate ru = repo.updateRef(otherDraftRef);
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(sha);
    assertThat(ru.update()).isEqualTo(RefUpdate.Result.NEW);
  }

  checker.rebuildAndCheckChanges(id);

  try (Repository repo = repoManager.openRepository(allUsers)) {
    assertThat(repo.exactRef(otherDraftRef)).isNull();
  }
}
项目:gerrit    文件:ChangeEditModifier.java   
private ObjectId createCommit(
    Repository repository,
    RevCommit basePatchSetCommit,
    ObjectId tree,
    String commitMessage,
    Timestamp timestamp)
    throws IOException {
  try (ObjectInserter objectInserter = repository.newObjectInserter()) {
    CommitBuilder builder = new CommitBuilder();
    builder.setTreeId(tree);
    builder.setParentIds(basePatchSetCommit.getParents());
    builder.setAuthor(basePatchSetCommit.getAuthorIdent());
    builder.setCommitter(getCommitterIdent(timestamp));
    builder.setMessage(commitMessage);
    ObjectId newCommitId = objectInserter.insert(builder);
    objectInserter.flush();
    return newCommitId;
  }
}
项目:gerrit    文件:ReviewNoteMerger.java   
@Override
public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter)
    throws IOException {
  if (ours == null) {
    return theirs;
  }
  if (theirs == null) {
    return ours;
  }
  if (ours.getData().equals(theirs.getData())) {
    return ours;
  }

  ObjectLoader lo = reader.open(ours.getData());
  byte[] sep = new byte[] {'\n'};
  ObjectLoader lt = reader.open(theirs.getData());
  try (ObjectStream os = lo.openStream();
      ByteArrayInputStream b = new ByteArrayInputStream(sep);
      ObjectStream ts = lt.openStream();
      UnionInputStream union = new UnionInputStream(os, b, ts)) {
    ObjectId noteData =
        inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union);
    return new Note(ours, noteData);
  }
}
项目:gerrit    文件:CommitMsgHookTest.java   
private void setHEAD() throws Exception {
  try (ObjectInserter oi = repository.newObjectInserter()) {
    final CommitBuilder commit = new CommitBuilder();
    commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
    commit.setAuthor(author);
    commit.setCommitter(committer);
    commit.setMessage("test\n");
    ObjectId commitId = oi.insert(commit);

    final RefUpdate ref = repository.updateRef(Constants.HEAD);
    ref.setNewObjectId(commitId);
    Result result = ref.forceUpdate();
    assertWithMessage(Constants.HEAD + " did not change: " + ref.getResult())
        .that(result)
        .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE);
  }
}
项目:gerrit    文件:MergeUtil.java   
public static Merger newMerger(ObjectInserter inserter, Config repoConfig, String strategyName) {
  MergeStrategy strategy = MergeStrategy.get(strategyName);
  checkArgument(strategy != null, "invalid merge strategy: %s", strategyName);
  return strategy.newMerger(
      new ObjectInserter.Filter() {
        @Override
        protected ObjectInserter delegate() {
          return inserter;
        }

        @Override
        public void flush() {}

        @Override
        public void close() {}
      },
      repoConfig);
}
项目:gerrit    文件:ReviewDbBatchUpdate.java   
private void executeNoteDbUpdate(RevWalk rw, ObjectInserter ins, BatchRefUpdate bru)
    throws IOException {
  if (bru.getCommands().isEmpty()) {
    logDebug("No commands, skipping flush and ref update");
    return;
  }
  ins.flush();
  bru.setAllowNonFastForwards(true);
  bru.execute(rw, NullProgressMonitor.INSTANCE);
  for (ReceiveCommand cmd : bru.getCommands()) {
    // TODO(dborowitz): LOCK_FAILURE for NoteDb primary should be retried.
    if (cmd.getResult() != ReceiveCommand.Result.OK) {
      throw new IOException("Update failed: " + bru);
    }
  }
}
项目:gerrit    文件:RepoSequence.java   
private RefUpdate.Result store(Repository repo, RevWalk rw, @Nullable ObjectId oldId, int val)
    throws IOException {
  ObjectId newId;
  try (ObjectInserter ins = repo.newObjectInserter()) {
    newId = ins.insert(OBJ_BLOB, Integer.toString(val).getBytes(UTF_8));
    ins.flush();
  }
  RefUpdate ru = repo.updateRef(refName);
  if (oldId != null) {
    ru.setExpectedOldObjectId(oldId);
  }
  ru.disableRefLog();
  ru.setNewObjectId(newId);
  ru.setForceUpdate(true); // Required for non-commitish updates.
  RefUpdate.Result result = ru.update(rw);
  if (refUpdated(result)) {
    gitRefUpdated.fire(projectName, ru, null);
  }
  return result;
}
项目:gerrit    文件:AbstractQueryChangesTest.java   
protected Change newPatchSet(TestRepository<Repo> repo, Change c) throws Exception {
  // Add a new file so the patch set is not a trivial rebase, to avoid default
  // Code-Review label copying.
  int n = c.currentPatchSetId().get() + 1;
  RevCommit commit =
      repo.parseBody(repo.commit().message("message").add("file" + n, "contents " + n).create());

  PatchSetInserter inserter =
      patchSetFactory
          .create(changeNotesFactory.createChecked(db, c), new PatchSet.Id(c.getId(), n), commit)
          .setNotify(NotifyHandling.NONE)
          .setFireRevisionCreated(false)
          .setValidate(false);
  try (BatchUpdate bu = updateFactory.create(db, c.getProject(), user, TimeUtil.nowTs());
      ObjectInserter oi = repo.getRepository().newObjectInserter();
      ObjectReader reader = oi.newReader();
      RevWalk rw = new RevWalk(reader)) {
    bu.setRepository(repo.getRepository(), rw, oi);
    bu.addOp(c.getId(), inserter);
    bu.execute();
  }

  return inserter.getChange();
}
项目:gerrit    文件:ExternalIdsUpdate.java   
private RefsMetaExternalIdsUpdate commit(
    Repository repo,
    RevWalk rw,
    ObjectInserter ins,
    ObjectId rev,
    NoteMap noteMap,
    UpdatedExternalIds updatedExtIds)
    throws IOException {
  ObjectId newRev =
      commit(
          allUsersName,
          repo,
          rw,
          ins,
          rev,
          noteMap,
          COMMIT_MSG,
          committerIdent,
          authorIdent,
          currentUser,
          gitRefUpdated);
  updateCount.increment();
  return RefsMetaExternalIdsUpdate.create(rev, newRev, updatedExtIds);
}
项目:gerrit    文件:NoteDbOnlyIT.java   
@Override
public void afterUpdateRepos() throws Exception {
  // Reopen repo and update ref, to simulate a concurrent write in another
  // thread. Only do this the first time the listener is called.
  if (calledCount.getAndIncrement() > 0) {
    return;
  }
  try (Repository repo = repoManager.openRepository(project);
      RevWalk rw = new RevWalk(repo);
      ObjectInserter ins = repo.newObjectInserter()) {
    String master = "refs/heads/master";
    ObjectId oldId = repo.exactRef(master).getObjectId();
    ObjectId newId = newCommit(rw, ins, oldId, MSG_PREFIX + calledCount.get());
    ins.flush();
    RefUpdate ru = repo.updateRef(master);
    ru.setExpectedOldObjectId(oldId);
    ru.setNewObjectId(newId);
    assertThat(ru.update(rw)).isEqualTo(RefUpdate.Result.FAST_FORWARD);
  }
}
项目:gerrit    文件:CreateChange.java   
private static RevCommit newCommit(
    ObjectInserter oi,
    RevWalk rw,
    PersonIdent authorIdent,
    RevCommit mergeTip,
    String commitMessage)
    throws IOException {
  CommitBuilder commit = new CommitBuilder();
  if (mergeTip == null) {
    commit.setTreeId(emptyTreeId(oi));
  } else {
    commit.setTreeId(mergeTip.getTree().getId());
    commit.setParentId(mergeTip);
  }
  commit.setAuthor(authorIdent);
  commit.setCommitter(authorIdent);
  commit.setMessage(commitMessage);
  return rw.parseCommit(insert(oi, commit));
}
项目:gerrit    文件:ExternalIdIT.java   
private void addExtId(TestRepository<?> testRepo, ExternalId... extIds)
    throws IOException, OrmDuplicateKeyException, ConfigInvalidException {
  ObjectId rev = ExternalIdReader.readRevision(testRepo.getRepository());

  try (ObjectInserter ins = testRepo.getRepository().newObjectInserter()) {
    NoteMap noteMap = ExternalIdReader.readNoteMap(testRepo.getRevWalk(), rev);
    for (ExternalId extId : extIds) {
      ExternalIdsUpdate.insert(testRepo.getRevWalk(), ins, noteMap, extId);
    }

    ExternalIdsUpdate.commit(
        allUsers,
        testRepo.getRepository(),
        testRepo.getRevWalk(),
        ins,
        rev,
        noteMap,
        "Add external ID",
        admin.getIdent(),
        admin.getIdent(),
        null,
        GitReferenceUpdated.DISABLED);
  }
}
项目:gerrit    文件:PutMessage.java   
private ObjectId createCommit(
    ObjectInserter objectInserter,
    RevCommit basePatchSetCommit,
    String commitMessage,
    Timestamp timestamp)
    throws IOException {
  CommitBuilder builder = new CommitBuilder();
  builder.setTreeId(basePatchSetCommit.getTree());
  builder.setParentIds(basePatchSetCommit.getParents());
  builder.setAuthor(basePatchSetCommit.getAuthorIdent());
  builder.setCommitter(
      currentUserProvider.get().asIdentifiedUser().newCommitterIdent(timestamp, tz));
  builder.setMessage(commitMessage);
  ObjectId newCommitId = objectInserter.insert(builder);
  objectInserter.flush();
  return newCommitId;
}
项目:gerrit    文件:GroupsIT.java   
private void createGroupBranch(Project.NameKey project, String ref) throws IOException {
  try (Repository r = repoManager.openRepository(project);
      ObjectInserter oi = r.newObjectInserter();
      RevWalk rw = new RevWalk(r)) {
    ObjectId emptyTree = oi.insert(Constants.OBJ_TREE, new byte[] {});
    PersonIdent ident = new PersonIdent(serverIdent.get(), TimeUtil.nowTs());

    CommitBuilder cb = new CommitBuilder();
    cb.setTreeId(emptyTree);
    cb.setCommitter(ident);
    cb.setAuthor(ident);
    cb.setMessage("Create group");
    ObjectId emptyCommit = oi.insert(cb);

    oi.flush();

    RefUpdate updateRef = r.updateRef(ref);
    updateRef.setExpectedOldObjectId(ObjectId.zeroId());
    updateRef.setNewObjectId(emptyCommit);
    assertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
  }
}
项目:gerrit    文件:ExternalIdIT.java   
private String insertExternalIdWithInvalidConfig(Repository repo, RevWalk rw, String externalId)
    throws IOException {
  ObjectId rev = ExternalIdReader.readRevision(repo);
  NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);

  try (ObjectInserter ins = repo.newObjectInserter()) {
    ObjectId noteId = ExternalId.Key.parse(externalId).sha1();
    byte[] raw = "bad-config".getBytes(UTF_8);
    ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
    noteMap.set(noteId, dataBlob);

    ExternalIdsUpdate.commit(
        allUsers,
        repo,
        rw,
        ins,
        rev,
        noteMap,
        "Add external ID",
        admin.getIdent(),
        admin.getIdent(),
        null,
        GitReferenceUpdated.DISABLED);
    return noteId.getName();
  }
}
项目:gerrit    文件:ExternalIdIT.java   
private String insertExternalIdWithEmptyNote(Repository repo, RevWalk rw, String externalId)
    throws IOException {
  ObjectId rev = ExternalIdReader.readRevision(repo);
  NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);

  try (ObjectInserter ins = repo.newObjectInserter()) {
    ObjectId noteId = ExternalId.Key.parse(externalId).sha1();
    byte[] raw = "".getBytes(UTF_8);
    ObjectId dataBlob = ins.insert(OBJ_BLOB, raw);
    noteMap.set(noteId, dataBlob);

    ExternalIdsUpdate.commit(
        allUsers,
        repo,
        rw,
        ins,
        rev,
        noteMap,
        "Add external ID",
        admin.getIdent(),
        admin.getIdent(),
        null,
        GitReferenceUpdated.DISABLED);
    return noteId.getName();
  }
}
项目:incubator-netbeans    文件:CheckoutRevisionCommand.java   
private void cacheContents (List<String> conflicts) throws IOException {
    File workTree = getRepository().getWorkTree();
    ObjectInserter inserter = getRepository().newObjectInserter();
    WorkingTreeOptions opt = getRepository().getConfig().get(WorkingTreeOptions.KEY);
    boolean autocrlf = opt.getAutoCRLF() != CoreConfig.AutoCRLF.FALSE;
    try {
        for (String path : conflicts) {
            File f = new File(workTree, path);
            Path p = null;
            try {
                p = f.toPath();
            } catch (InvalidPathException ex) {
                Logger.getLogger(CheckoutRevisionCommand.class.getName()).log(Level.FINE, null, ex);
            }
            if (p != null && Files.isSymbolicLink(p)) {
                Path link = Utils.getLinkPath(p);                                
                cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, Constants.encode(link.toString())));
            } else if (f.isFile()) {
                long sz = f.length();
                try (FileInputStream in = new FileInputStream(f)) {
                    if (autocrlf) {
                        ByteBuffer buf = IO.readWholeStream(in, (int) sz);
                        cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, buf.array(), buf.position(), buf.limit() - buf.position()));
                    } else {
                        cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, sz, in));
                    }
                }
            }
        }
        inserter.flush();
    } finally {
        inserter.release();
    }
}
项目:centraldogma    文件:GitRepository.java   
private static ObjectId newBlob(ObjectInserter inserter, JsonNode content) {
    try {
        return newBlob(inserter, Jackson.writeValueAsBytes(content));
    } catch (IOException e) {
        throw new StorageException("failed to serialize a JSON value: " + content, e);
    }
}
项目:centraldogma    文件:GitRepository.java   
private static ObjectId newBlob(ObjectInserter inserter, byte[] content) {
    final ObjectId id;
    try {
        id = inserter.insert(Constants.OBJ_BLOB, content);
    } catch (IOException e) {
        throw new StorageException("failed to create a new blob", e);
    }
    return id;
}
项目:gitplex-mit    文件:GitUtils.java   
@Nullable
  public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
    try (   RevWalk revWalk = new RevWalk(repository);
            ObjectInserter inserter = repository.newObjectInserter();) {
        RevCommit sourceCommit = revWalk.parseCommit(source);
        RevCommit targetCommit = revWalk.parseCommit(target);
        revWalk.setRevFilter(RevFilter.NO_MERGES);
        List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
        Collections.reverse(commits);
        RevCommit headCommit = targetCommit;
        for (RevCommit commit: commits) {
            ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
            merger.setBase(commit.getParent(0));
            if (merger.merge(headCommit, commit)) {
            if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
                CommitBuilder newCommit = new CommitBuilder();
                newCommit.setAuthor(commit.getAuthorIdent());
                newCommit.setCommitter(committer);
                newCommit.setParentId(headCommit);
                newCommit.setMessage(commit.getFullMessage());
                newCommit.setTreeId(merger.getResultTreeId());
                headCommit = revWalk.parseCommit(inserter.insert(newCommit));
            }
            } else {
                return null;
            }
        }
        inserter.flush();
        return headCommit.copy();
    } catch (IOException e) {
        throw new RuntimeException(e);
}
  }
项目:gitplex-mit    文件:GitUtils.java   
@Nullable
  public static ObjectId merge(Repository repository, ObjectId source, ObjectId target, 
        boolean squash, PersonIdent committer, String commitMessage) {
    try (   RevWalk revWalk = new RevWalk(repository);
            ObjectInserter inserter = repository.newObjectInserter();) {
        RevCommit sourceCommit = revWalk.parseCommit(source);
        RevCommit targetCommit = revWalk.parseCommit(target);
        Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
        if (merger.merge(targetCommit, sourceCommit)) {
        CommitBuilder mergedCommit = new CommitBuilder();
        mergedCommit.setAuthor(sourceCommit.getAuthorIdent());
        mergedCommit.setCommitter(committer);
        if (squash)
            mergedCommit.setParentId(targetCommit);
        else
            mergedCommit.setParentIds(targetCommit, sourceCommit);
        mergedCommit.setMessage(commitMessage);
        mergedCommit.setTreeId(merger.getResultTreeId());
        ObjectId mergedCommitId = inserter.insert(mergedCommit);
        inserter.flush();
        return mergedCommitId;
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
}
  }
项目:gmds    文件:Utils.java   
/**
 *
 * @param repo
 * @param conn
 * @param dbmd
 * @param objectInserter
 * @param dbMetaTree
 * @param clmnTree
 * @return
 */
public static TreeFormatter putTableMeta(Repository repo, Connection conn,
        DatabaseMetaData dbmd, ObjectInserter objectInserter, TreeFormatter dbMetaTree, Boolean clmnTree) {

    String[] types = {"TABLE"};

    try {

        ResultSet tables = dbmd.getTables(null, null, null, types);
        RevWalk walkTbl = new RevWalk(repo);

        while (tables.next()) {
            System.out.println("***************************************");
            String tableName = tables.getString(Consts.TABLE_NAME);

            TreeFormatter tblMetaTree = new TreeFormatter();

            // Build tree for table attributs
            buildMetaTree(tables, Consts.TABLE_META_ATTRIBUTES, objectInserter, tblMetaTree);

            ResultSet columns = dbmd.getColumns(null, null, tableName, null);
            if (clmnTree) {
                addColumnsAsTrees(columns, objectInserter, tblMetaTree, walkTbl, dbMetaTree);
            } else {
                addColumnsAsObjects(columns, objectInserter, tblMetaTree, walkTbl, dbMetaTree);
            }

            TreeFormatter tblDataTree = new TreeFormatter();
            ObjectId tblDataTreeId = objectInserter.insert(tblDataTree);
            objectInserter.flush();

            dbMetaTree.append(Consts.TABLE_DATA, walkTbl.parseTree(tblDataTreeId));
        }
    } catch (SQLException | IOException ex) {
        System.out.println(ex.getMessage());
    }
    return dbMetaTree;
}
项目:gmds    文件:Utils.java   
/**
 * 
 * @param columns
 * @param objectInserter
 * @param tblMetaTree
 * @param walkTbl
 * @param dbMetaTree
 * @throws IOException
 * @throws SQLException 
 */
public static void addColumnsAsObjects(ResultSet columns, 
        ObjectInserter objectInserter, TreeFormatter tblMetaTree, RevWalk walkTbl, 
        TreeFormatter dbMetaTree) throws IOException, SQLException {

    while (columns.next()) {
        putColumnMetaAsObject(columns, objectInserter, tblMetaTree, walkTbl);
    }

    ObjectId tblMetaTreeId = objectInserter.insert(tblMetaTree);
    objectInserter.flush();

    dbMetaTree.append(Consts.TABLE_META, walkTbl.parseTree(tblMetaTreeId));
}
项目:gmds    文件:Utils.java   
/**
 * 
 * @param columns
 * @param objectInserter
 * @param tblMetaTree
 * @param walkTbl
 * @param dbMetaTree
 * @throws SQLException
 * @throws IOException 
 */
public static void addColumnsAsTrees(ResultSet columns, 
        ObjectInserter objectInserter, TreeFormatter tblMetaTree, RevWalk walkTbl, 
        TreeFormatter dbMetaTree) throws SQLException, IOException {

    while (columns.next()) {
        putColumnMetaAsTree(columns, objectInserter, tblMetaTree, walkTbl);
    }

    ObjectId tblMetaTreeId = objectInserter.insert(tblMetaTree);
    objectInserter.flush();

    dbMetaTree.append(Consts.TABLE_META, walkTbl.parseTree(tblMetaTreeId));
}
项目:ParallelGit    文件:ObjectSnapshot.java   
@Nonnull
public ObjectId save(Repository repo) throws IOException {
  try(ObjectInserter inserter = repo.newObjectInserter()) {
    ObjectId ret = save(inserter);
    inserter.flush();
    return ret;
  }
}
项目:gerrit-ci    文件:JobsServlet.java   
public static void updateProjectRef(ObjectId treeId, ObjectInserter objectInserter, Repository repository, CurrentUser currentUser)
        throws IOException, NoFilepatternException, GitAPIException {
    // Create a branch
    Ref gerritCiRef = repository.getRef("refs/meta/gerrit-ci");
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(treeId);
    logger.info("treeId: " + treeId);

    if (gerritCiRef != null) {
        ObjectId prevCommit = gerritCiRef.getObjectId();
        logger.info("prevCommit: " + prevCommit);
        commitBuilder.setParentId(prevCommit);
    }
    // build commit
    logger.info("Adding git tree : " + treeId);
    commitBuilder.setMessage("Modify project build rules.");
    final IdentifiedUser iUser = (IdentifiedUser) currentUser;
    PersonIdent user = new PersonIdent(currentUser.getUserName(), iUser.getEmailAddresses().iterator().next());
    commitBuilder.setAuthor(user);
    commitBuilder.setCommitter(user);
    ObjectId commitId = objectInserter.insert(commitBuilder);
    objectInserter.flush();
    logger.info(" Making new commit: " + commitId);
    RefUpdate newRef = repository.updateRef("refs/meta/gerrit-ci");
    newRef.setNewObjectId(commitId);
    newRef.update();
    repository.close();
}
项目:git-appraise-eclipse    文件:AppraiseGitReviewClient.java   
/**
 * Creates a merged notes commit.
 */
private RevCommit createNotesCommit(NoteMap map, ObjectInserter inserter, RevWalk revWalk,
    String message, RevCommit... parents) throws IOException {
  CommitBuilder commitBuilder = new CommitBuilder();
  commitBuilder.setTreeId(map.writeTree(inserter));
  commitBuilder.setAuthor(author);
  commitBuilder.setCommitter(author);
  if (parents.length > 0) {
    commitBuilder.setParentIds(parents);
  }
  commitBuilder.setMessage(message);
  ObjectId commitId = inserter.insert(commitBuilder);
  inserter.flush();
  return revWalk.parseCommit(commitId);
}
项目:appformer    文件:BaseCreateCommitTree.java   
BaseCreateCommitTree(final Git git,
                     final ObjectId headId,
                     final ObjectInserter inserter,
                     final T commitContent) {
    this.git = git;
    this.headId = headId;
    this.odi = inserter;
    this.commitContent = commitContent;
}
项目:gerrit    文件:ExternalIdsOnInit.java   
public synchronized void insert(String commitMessage, Collection<ExternalId> extIds)
    throws OrmException, IOException, ConfigInvalidException {

  File path = getPath();
  if (path != null) {
    try (Repository repo = new FileRepository(path);
        RevWalk rw = new RevWalk(repo);
        ObjectInserter ins = repo.newObjectInserter()) {
      ObjectId rev = ExternalIdReader.readRevision(repo);

      NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
      for (ExternalId extId : extIds) {
        ExternalIdsUpdate.insert(rw, ins, noteMap, extId);
      }

      PersonIdent serverIdent = new GerritPersonIdentProvider(flags.cfg).get();
      ExternalIdsUpdate.commit(
          new Project.NameKey(allUsers),
          repo,
          rw,
          ins,
          rev,
          noteMap,
          commitMessage,
          serverIdent,
          serverIdent,
          null,
          GitReferenceUpdated.DISABLED);
    }
  }
}
项目:gerrit    文件:RepoSequenceTest.java   
private ObjectId writeBlob(String sequenceName, String value) {
  String refName = RefNames.REFS_SEQUENCES + sequenceName;
  try (Repository repo = repoManager.openRepository(project);
      ObjectInserter ins = repo.newObjectInserter()) {
    ObjectId newId = ins.insert(OBJ_BLOB, value.getBytes(UTF_8));
    ins.flush();
    RefUpdate ru = repo.updateRef(refName);
    ru.setNewObjectId(newId);
    assertThat(ru.forceUpdate()).isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
    return newId;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:gerrit    文件:PatchListLoader.java   
@Override
public PatchList call() throws IOException, PatchListNotAvailableException {
  try (Repository repo = repoManager.openRepository(project);
      ObjectInserter ins = newInserter(repo);
      ObjectReader reader = ins.newReader();
      RevWalk rw = new RevWalk(reader)) {
    return readPatchList(repo, rw, ins);
  }
}