Search in sources :

Example 26 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter in project gerrit by GerritCodeReview.

the class UnfusedNoteDbBatchUpdate method executeChangeOps.

private Map<Change.Id, ChangeResult> executeChangeOps(boolean dryrun) throws Exception {
    logDebug("Executing change ops");
    Map<Change.Id, ChangeResult> result = Maps.newLinkedHashMapWithExpectedSize(ops.keySet().size());
    initRepository();
    Repository repo = repoView.getRepository();
    // update as in executeUpdateRepo.
    try (ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader);
        NoteDbUpdateManager updateManager = updateManagerFactory.create(project).setChangeRepo(repo, rw, ins, new ChainedReceiveCommands(repo))) {
        if (user.isIdentifiedUser()) {
            updateManager.setRefLogIdent(user.asIdentifiedUser().newRefLogIdent(when, tz));
        }
        for (Map.Entry<Change.Id, Collection<BatchUpdateOp>> e : ops.asMap().entrySet()) {
            Change.Id id = e.getKey();
            ChangeContextImpl ctx = newChangeContext(id);
            boolean dirty = false;
            logDebug("Applying {} ops for change {}", e.getValue().size(), id);
            for (BatchUpdateOp op : e.getValue()) {
                dirty |= op.updateChange(ctx);
            }
            if (!dirty) {
                logDebug("No ops reported dirty, short-circuiting");
                result.put(id, ChangeResult.SKIPPED);
                continue;
            }
            for (ChangeUpdate u : ctx.updates.values()) {
                updateManager.add(u);
            }
            if (ctx.deleted) {
                logDebug("Change {} was deleted", id);
                updateManager.deleteChange(id);
                result.put(id, ChangeResult.DELETED);
            } else {
                result.put(id, ChangeResult.UPSERTED);
            }
        }
        if (!dryrun) {
            logDebug("Executing NoteDb updates");
            updateManager.execute();
        }
    }
    return result;
}
Also used : NoteDbUpdateManager(com.google.gerrit.server.notedb.NoteDbUpdateManager) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) Collection(java.util.Collection) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RequestId(com.google.gerrit.server.util.RequestId) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 27 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter in project gerrit by GerritCodeReview.

the class Schema_148 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    try (Repository repo = repoManager.openRepository(allUsersName);
        RevWalk rw = new RevWalk(repo);
        ObjectInserter ins = repo.newObjectInserter()) {
        ObjectId rev = ExternalIdReader.readRevision(repo);
        NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
        boolean dirty = false;
        for (Note note : noteMap) {
            byte[] raw = rw.getObjectReader().open(note.getData(), OBJ_BLOB).getCachedBytes(ExternalIdReader.MAX_NOTE_SZ);
            try {
                ExternalId extId = ExternalId.parse(note.getName(), raw);
                if (needsUpdate(extId)) {
                    ExternalIdsUpdate.upsert(rw, ins, noteMap, extId);
                    dirty = true;
                }
            } catch (ConfigInvalidException e) {
                ui.message(String.format("Warning: Ignoring invalid external ID note %s", note.getName()));
            }
        }
        if (dirty) {
            ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, COMMIT_MSG, serverUser, serverUser);
        }
    } catch (IOException e) {
        throw new OrmException("Failed to update external IDs", e);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) OrmException(com.google.gwtorm.server.OrmException) Note(org.eclipse.jgit.notes.Note) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) NoteMap(org.eclipse.jgit.notes.NoteMap) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Example 28 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter in project gitblit by gitblit.

the class JGitUtils method commitIndex.

public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId, boolean forceCommit, String author, String authorEmail, String message) throws IOException, ConcurrentRefUpdateException {
    boolean success = false;
    ObjectId headId = db.resolve(branch + "^{commit}");
    ObjectId baseId = parentId;
    if (baseId == null || headId == null) {
        return false;
    }
    ObjectInserter odi = db.newObjectInserter();
    try {
        // Create the in-memory index of the new/updated ticket
        ObjectId indexTreeId = index.writeTree(odi);
        // Create a commit object
        PersonIdent ident = new PersonIdent(author, authorEmail);
        if (forceCommit == false) {
            ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
            merger.setObjectInserter(odi);
            merger.setBase(baseId);
            boolean mergeSuccess = merger.merge(indexTreeId, headId);
            if (mergeSuccess) {
                indexTreeId = merger.getResultTreeId();
            } else {
                //Manual merge required
                return false;
            }
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(ident);
        commit.setCommitter(ident);
        commit.setEncoding(com.gitblit.Constants.ENCODING);
        commit.setMessage(message);
        commit.setParentId(headId);
        commit.setTreeId(indexTreeId);
        // Insert the commit into the repository
        ObjectId commitId = odi.insert(commit);
        odi.flush();
        RevWalk revWalk = new RevWalk(db);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = db.updateRef(branch);
            ru.setForceUpdate(forceCommit);
            ru.setNewObjectId(commitId);
            ru.setExpectedOldObjectId(headId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result rc = ru.update();
            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));
            }
        } finally {
            revWalk.close();
        }
    } finally {
        odi.close();
    }
    return success;
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) PersonIdent(org.eclipse.jgit.lib.PersonIdent) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate) FetchResult(org.eclipse.jgit.transport.FetchResult) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 29 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter in project gitblit by gitblit.

the class RefLogUtils method createIndex.

/**
	 * Creates an in-memory index of the reflog entry.
	 *
	 * @param repo
	 * @param headId
	 * @param commands
	 * @return an in-memory index
	 * @throws IOException
	 */
private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands) throws IOException {
    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();
    long now = System.currentTimeMillis();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // add receive commands to the temporary index
        for (ReceiveCommand command : commands) {
            // use the ref names as the path names
            String path = command.getRefName();
            ignorePaths.add(path);
            StringBuilder change = new StringBuilder();
            change.append(command.getType().name()).append(' ');
            switch(command.getType()) {
                case CREATE:
                    change.append(ObjectId.zeroId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    change.append(command.getOldId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case DELETE:
                    change = null;
                    break;
            }
            if (change == null) {
                // ref deleted
                continue;
            }
            String content = change.toString();
            // create an index entry for this attachment
            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setLength(content.length());
            dcEntry.setLastModified(now);
            dcEntry.setFileMode(FileMode.REGULAR_FILE);
            // insert object
            dcEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));
            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }
        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1)
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            if (!ignorePaths.contains(path)) {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());
                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
        }
        // release the treewalk
        treeWalk.close();
        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.close();
    }
    return inCoreIndex;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCache(org.eclipse.jgit.dircache.DirCache) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) TreeSet(java.util.TreeSet) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

Example 30 with ObjectInserter

use of org.eclipse.jgit.lib.ObjectInserter in project gitblit by gitblit.

the class BranchTicketService method writeTicketsFile.

/**
	 * Writes a file to the tickets branch.
	 *
	 * @param db
	 * @param file
	 * @param content
	 * @param createdBy
	 * @param msg
	 */
private void writeTicketsFile(Repository db, String file, String content, String createdBy, String msg) {
    if (getTicketsBranch(db) == null) {
        createTicketsBranch(db);
    }
    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();
    try {
        // create an index entry for the revised index
        final DirCacheEntry idIndexEntry = new DirCacheEntry(file);
        idIndexEntry.setLength(content.length());
        idIndexEntry.setLastModified(System.currentTimeMillis());
        idIndexEntry.setFileMode(FileMode.REGULAR_FILE);
        // insert new ticket index
        idIndexEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes(Constants.ENCODING)));
        // add to temporary in-core index
        builder.add(idIndexEntry);
        Set<String> ignorePaths = new HashSet<String>();
        ignorePaths.add(file);
        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }
        // finish temporary in-core index used for this commit
        builder.finish();
        // commit the change
        commitIndex(db, newIndex, createdBy, msg);
    } catch (ConcurrentRefUpdateException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    } finally {
        inserter.close();
    }
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) IOException(java.io.IOException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) HashSet(java.util.HashSet)

Aggregations

ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)56 ObjectId (org.eclipse.jgit.lib.ObjectId)39 RevWalk (org.eclipse.jgit.revwalk.RevWalk)30 Repository (org.eclipse.jgit.lib.Repository)26 IOException (java.io.IOException)17 ObjectReader (org.eclipse.jgit.lib.ObjectReader)16 RevCommit (org.eclipse.jgit.revwalk.RevCommit)16 Change (com.google.gerrit.reviewdb.client.Change)13 PersonIdent (org.eclipse.jgit.lib.PersonIdent)12 NoteMap (org.eclipse.jgit.notes.NoteMap)12 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)11 RefUpdate (org.eclipse.jgit.lib.RefUpdate)11 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)10 OrmException (com.google.gwtorm.server.OrmException)8 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)7 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)6 Project (com.google.gerrit.reviewdb.client.Project)6 ChangeControl (com.google.gerrit.server.project.ChangeControl)6 DirCache (org.eclipse.jgit.dircache.DirCache)6 Ref (org.eclipse.jgit.lib.Ref)6