Here are the examples of the java api org.eclipse.jgit.lib.Repository.newObjectInserter() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
88 Examples
18
View Complete Implementation : ObjectSnapshot.java
Copyright Apache License 2.0
Author : beijunyi
Copyright Apache License 2.0
Author : beijunyi
@Nonnull
public ObjectId save(Repository repo) throws IOException {
try (ObjectInserter inserter = repo.newObjectInserter()) {
ObjectId ret = save(inserter);
inserter.flush();
return ret;
}
}
17
View Complete Implementation : PublicKeyStore.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
public void rebuildSubkeyMasterKeyMap() throws MissingObjectException, IncorrectObjectTypeException, IOException, PGPException {
if (reader == null) {
load();
}
if (notes != null) {
try (ObjectInserter ins = repo.newObjectInserter()) {
for (Note note : notes) {
for (PGPPublicKeyRing keyRing : new PGPPublicKeyRingCollection(readKeysFromNote(note, null))) {
long masterKeyId = keyRing.getPublicKey().getKeyID();
ObjectId masterKeyObjectId = keyObjectId(masterKeyId);
saveSubkeyMapping(ins, keyRing, masterKeyId, masterKeyObjectId);
}
}
}
}
}
17
View Complete Implementation : ExternalIdsOnInit.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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);
}
}
}
17
View Complete Implementation : TreeCreator.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private static ObjectId writeAndGetId(Repository repository, DirCache tree) throws IOException {
try (ObjectInserter objectInserter = repository.newObjectInserter()) {
ObjectId treeId = tree.writeTree(objectInserter);
objectInserter.flush();
return treeId;
}
}
17
View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private void replacedertIllegalArgument(GroupReference... groupRefs) throws Exception {
try (ObjectInserter inserter = repo.newObjectInserter()) {
BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate();
PersonIdent ident = newPersonIdent();
IllegalArgumentException thrown = replacedertThrows(IllegalArgumentException.clreplaced, () -> GroupNameNotes.updateAllGroups(repo, inserter, bru, Arrays.asList(groupRefs), ident));
replacedertThat(thrown).hasMessageThat().isEqualTo(GroupNameNotes.UNIQUE_REF_ERROR);
}
}
16
View Complete Implementation : Schema_146.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
try (Repository repo = repoManager.openRepository(allUsersName);
RevWalk rw = new RevWalk(repo);
ObjectInserter oi = repo.newObjectInserter()) {
ObjectId emptyTree = emptyTree(oi);
for (Map.Entry<Account.Id, Timestamp> e : scanAccounts(db).entrySet()) {
String refName = RefNames.refsUsers(e.getKey());
Ref ref = repo.exactRef(refName);
if (ref != null) {
rewriteUserBranch(repo, rw, oi, emptyTree, ref, e.getValue());
} else {
createUserBranch(repo, oi, emptyTree, e.getKey(), e.getValue());
}
}
} catch (IOException e) {
throw new OrmException("Failed to rewrite user branches.", e);
}
}
16
View Complete Implementation : StarredChangesUtil.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
public static ObjectId writeLabels(Repository repo, Collection<String> labels) throws IOException, InvalidLabelsException {
validateLabels(labels);
try (ObjectInserter oi = repo.newObjectInserter()) {
ObjectId id = oi.insert(Constants.OBJ_BLOB, labels.stream().sorted().distinct().collect(joining("\n")).getBytes(UTF_8));
oi.flush();
return id;
}
}
15
View Complete Implementation : GroupNameNotesTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private void updateAllGroups(PersonIdent ident, GroupReference... groupRefs) throws Exception {
try (ObjectInserter inserter = repo.newObjectInserter()) {
BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate();
GroupNameNotes.updateAllGroups(repo, inserter, bru, Arrays.asList(groupRefs), ident);
inserter.flush();
RefUpdateUtil.executeChecked(bru, repo);
}
}
15
View Complete Implementation : ExternalIdsBatchUpdate.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
/**
* Commits this batch.
*
* <p>This means external ID replacements which were prepared by invoking {@link
* #replace(ExternalId, ExternalId)} are now executed. Deletion of external IDs is done before
* adding the new external IDs. This means if an external ID is specified for deletion and an
* external ID with the same key is specified to be added, the old external ID with that key is
* deleted first and then the new external ID is added (so the external ID for that key is
* replaced).
*
* <p>For NoteDb a single commit is created that contains all the external ID updates.
*/
public void commit(String commitMessage) throws IOException, OrmException, ConfigInvalidException {
if (toDelete.isEmpty() && toAdd.isEmpty()) {
return;
}
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);
for (ExternalId extId : toDelete) {
ExternalIdsUpdate.remove(rw, noteMap, extId);
}
for (ExternalId extId : toAdd) {
ExternalIdsUpdate.insert(rw, ins, noteMap, extId);
}
ObjectId newRev = ExternalIdsUpdate.commit(allUsersName, repo, rw, ins, rev, noteMap, commitMessage, serverIdent, serverIdent, null, gitRefUpdated);
externalIdCache.onReplace(rev, newRev, toDelete, toAdd);
}
toAdd.clear();
toDelete.clear();
}
15
View Complete Implementation : JGitSubdirectoryCloneTest.java
Copyright Apache License 2.0
Author : kiegroup
Copyright Apache License 2.0
Author : kiegroup
/*
* Unfortunately there is no easier way to write a commit with multiple parents.
*/
private void mergeCommit(final Git origin, final String targetBranchName, final String sourceBranchName, final TestFile... testFiles) throws Exception {
final Repository repo = origin.getRepository();
final org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.wrap(repo);
final ObjectId targetId = repo.resolve(targetBranchName);
final ObjectId sourceId = repo.resolve(sourceBranchName);
final DirCache dc = DirCache.newInCore();
final DirCacheEditor editor = dc.editor();
try (ObjectInserter inserter = repo.newObjectInserter()) {
final ObjectId treeId = writeTestFilesToTree(dc, editor, inserter, testFiles);
final ObjectId commitId = writeCommit(inserter, treeId, targetId, sourceId);
updateBranch(targetBranchName, git, commitId);
}
}
15
View Complete Implementation : ExternalIdsUpdate.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private RefsMetaExternalIdsUpdate updateNoteMap(ExternalIdUpdater updater) throws IOException, ConfigInvalidException, OrmException {
try {
return retryer.call(() -> {
try (Repository repo = repoManager.openRepository(allUsersName);
ObjectInserter ins = repo.newObjectInserter()) {
ObjectId rev = readRevision(repo);
afterReadRevision.run();
try (RevWalk rw = new RevWalk(repo)) {
NoteMap noteMap = readNoteMap(rw, rev);
UpdatedExternalIds updatedExtIds = updater.update(OpenRepo.create(repo, rw, ins, noteMap));
return commit(repo, rw, ins, rev, noteMap, updatedExtIds);
}
}
});
} catch (ExecutionException | RetryException e) {
if (e.getCause() != null) {
Throwables.throwIfInstanceOf(e.getCause(), IOException.clreplaced);
Throwables.throwIfInstanceOf(e.getCause(), ConfigInvalidException.clreplaced);
Throwables.throwIfInstanceOf(e.getCause(), OrmException.clreplaced);
}
throw new OrmException(e);
}
}
15
View Complete Implementation : BranchTicketService.java
Copyright Apache License 2.0
Author : tomaswolf
Copyright Apache License 2.0
Author : tomaswolf
/**
* 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();
try (ObjectInserter inserter = db.newObjectInserter()) {
// 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 : getTreeEntries(db, 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);
}
}
15
View Complete Implementation : NoteDbUpdateManager.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private OpenRepo openRepo(Project.NameKey p) throws IOException {
// Closed by OpenRepo#close.
Repository repo = repoManager.openRepository(p);
// Closed by OpenRepo#close.
ObjectInserter ins = repo.newObjectInserter();
// Not closed by OpenRepo#close.
ObjectReader reader = ins.newReader();
try (RevWalk rw = new RevWalk(reader)) {
// Doesn't escape OpenRepo constructor.
return new OpenRepo(repo, rw, ins, new ChainedReceiveCommands(repo), true, saveObjects) {
@Override
public void close() {
reader.close();
super.close();
}
};
}
}
15
View Complete Implementation : AllProjectsCreator.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private void initSequences(Repository git, BatchRefUpdate bru, int firstChangeId) throws IOException {
if (git.exactRef(REFS_SEQUENCES + Sequences.NAME_CHANGES) == null) {
// Can't easily reuse the inserter from MetaDataUpdate, but this shouldn't slow down site
// initialization unduly.
try (ObjectInserter ins = git.newObjectInserter()) {
bru.addCommand(RepoSequence.storeNew(ins, Sequences.NAME_CHANGES, firstChangeId));
ins.flush();
}
}
}
15
View Complete Implementation : SubdirectoryClone.java
Copyright Apache License 2.0
Author : kiegroup
Copyright Apache License 2.0
Author : kiegroup
public Git execute() {
final Git git = new Clone(repoDir, origin, false, branches, credentialsProvider, leaders, hookDir, sslVerify).execute().get();
final Repository repository = git.getRepository();
try (final ObjectReader reader = repository.newObjectReader();
final ObjectInserter inserter = repository.newObjectInserter()) {
// Map all transformed commits that are non-empty so that we can properly map parents
final Map<ObjectId, ObjectId> commitMap = new HashMap<>();
final RevWalk revWalk = createRevWalk(repository, reader);
transformBranches(repository, reader, inserter, revWalk, commitMap);
overrideBranchNames(repository, revWalk, commitMap);
removeOriginRemote(repository);
return git;
} catch (Exception e) {
String message = String.format("Error cloning origin <%s> with subdirectory <%s>.", origin, subdirectory);
logger.error(message);
cleanupDir(git.getRepository().getDirectory());
throw new Clone.CloneException(message, e);
}
}
15
View Complete Implementation : BranchTicketService.java
Copyright Apache License 2.0
Author : tomaswolf
Copyright Apache License 2.0
Author : tomaswolf
/**
* Creates an in-memory index of the ticket change.
*
* @param changeId
* @param change
* @return an in-memory index
* @throws IOException
*/
private DirCache createIndex(Repository db, long ticketId, Change change) throws IOException, ClreplacedNotFoundException, NoSuchFieldException {
String ticketPath = toTicketPath(ticketId);
DirCache newIndex = DirCache.newInCore();
DirCacheBuilder builder = newIndex.builder();
Set<String> ignorePaths = new TreeSet<String>();
try (ObjectInserter inserter = db.newObjectInserter()) {
// create/update the journal
// exclude the attachment content
List<Change> changes = getJournal(db, ticketId);
changes.add(change);
String journal = TicketSerializer.serializeJournal(changes).trim();
byte[] journalBytes = journal.getBytes(Constants.ENCODING);
String journalPath = ticketPath + "/" + JOURNAL;
final DirCacheEntry journalEntry = new DirCacheEntry(journalPath);
journalEntry.setLength(journalBytes.length);
journalEntry.setLastModified(change.date.getTime());
journalEntry.setFileMode(FileMode.REGULAR_FILE);
journalEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, journalBytes));
// add journal to index
builder.add(journalEntry);
ignorePaths.add(journalEntry.getPathString());
// Add any attachments to the index
if (change.hasAttachments()) {
for (Attachment attachment : change.attachments) {
// build a path name for the attachment and mark as ignored
String path = toAttachmentPath(ticketId, attachment.name);
ignorePaths.add(path);
// create an index entry for this attachment
final DirCacheEntry entry = new DirCacheEntry(path);
entry.setLength(attachment.content.length);
entry.setLastModified(change.date.getTime());
entry.setFileMode(FileMode.REGULAR_FILE);
// insert object
entry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, attachment.content));
// add to temporary in-core index
builder.add(entry);
}
}
for (DirCacheEntry entry : getTreeEntries(db, ignorePaths)) {
builder.add(entry);
}
// finish the index
builder.finish();
}
return newIndex;
}
15
View Complete Implementation : AllProjectsCreator.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private void initSequences(Repository git, BatchRefUpdate bru) throws IOException {
if (notesMigration.readChangeSequence() && git.exactRef(REFS_SEQUENCES + Sequences.NAME_CHANGES) == null) {
// Can't easily reuse the inserter from MetaDataUpdate, but this shouldn't slow down site
// initialization unduly.
try (ObjectInserter ins = git.newObjectInserter()) {
bru.addCommand(RepoSequence.storeNew(ins, Sequences.NAME_CHANGES, firstChangeId));
ins.flush();
}
}
}
15
View Complete Implementation : ExternalIdIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private void insertExtIdBehindGerritsBack(ExternalId extId) throws Exception {
try (Repository repo = repoManager.openRepository(allUsers);
RevWalk rw = new RevWalk(repo);
ObjectInserter ins = repo.newObjectInserter()) {
ObjectId rev = ExternalIdReader.readRevision(repo);
NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
ExternalIdsUpdate.insert(rw, ins, noteMap, extId);
ExternalIdsUpdate.commit(allUsers, repo, rw, ins, rev, noteMap, "insert new ID", serverIdent.get(), serverIdent.get(), null, GitReferenceUpdated.DISABLED);
}
}
15
View Complete Implementation : AddTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private void replacedertDirCacheEntryModified(Collection<File> files) throws IOException {
DirCache cache = repository.lockDirCache();
for (File f : files) {
String relativePath = Utils.getRelativePath(workDir, f);
DirCacheEntry e = cache.getEntry(relativePath);
replacedertNotNull(e);
replacedertEquals(relativePath, e.getPathString());
try (InputStream in = new FileInputStream(f)) {
replacedertNotSame(e.getObjectId(), repository.newObjectInserter().idFor(Constants.OBJ_BLOB, f.length(), in));
}
}
cache.unlock();
}
15
View Complete Implementation : CommitUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
/**
* Wrapper function for creating a revert Commit.
*
* @param message Commit message for the revert commit.
* @param notes ChangeNotes of the change being reverted.
* @param user Current User performing the revert.
* @param ts Timestamp of creation for the commit.
* @return ObjectId that represents the newly created commit.
*/
public ObjectId createRevertCommit(String message, ChangeNotes notes, CurrentUser user, Timestamp ts) throws RestApiException, IOException {
try (Repository git = repoManager.openRepository(notes.getProjectName());
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk revWalk = new RevWalk(reader)) {
return createRevertCommit(message, notes, user, ts, oi, revWalk, null);
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(notes.getProjectName().toString(), e);
}
}
15
View Complete Implementation : OpenRepo.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
/**
* Returns a {@link OpenRepo} wrapping around an open {@link Repository}.
*/
static OpenRepo open(GitRepositoryManager repoManager, Project.NameKey project) throws IOException {
// Closed by OpenRepo#close.
Repository repo = repoManager.openRepository(project);
// Closed by OpenRepo#close.
ObjectInserter ins = repo.newObjectInserter();
// Not closed by OpenRepo#close.
ObjectReader reader = ins.newReader();
try (RevWalk rw = new RevWalk(reader)) {
// Doesn't escape OpenRepo constructor.
return new OpenRepo(repo, rw, ins, new ChainedReceiveCommands(repo), true) {
@Override
public void close() {
reader.close();
super.close();
}
};
}
}
14
View Complete Implementation : AbstractGitTestCase.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected static void replacedertDirCacheEntry(Repository repository, File workDir, Collection<File> files) throws IOException {
DirCache cache = repository.lockDirCache();
for (File f : files) {
String relativePath = Utils.getRelativePath(workDir, f);
DirCacheEntry e = cache.getEntry(relativePath);
replacedertNotNull(e);
replacedertEquals(relativePath, e.getPathString());
if (f.lastModified() != e.getLastModified()) {
replacedertEquals((f.lastModified() / 1000) * 1000, (e.getLastModified() / 1000) * 1000);
}
try (InputStream in = new FileInputStream(f)) {
replacedertEquals(e.getObjectId(), repository.newObjectInserter().idFor(Constants.OBJ_BLOB, f.length(), in));
}
if (e.getLength() == 0 && f.length() != 0) {
replacedertTrue(e.isSmudged());
} else {
replacedertEquals(f.length(), e.getLength());
}
}
cache.unlock();
}
14
View Complete Implementation : Schema_148.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
@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, note.getData());
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(allUsersName, repo, rw, ins, rev, noteMap, COMMIT_MSG, serverUser, serverUser, null, GitReferenceUpdated.DISABLED);
}
} catch (IOException e) {
throw new OrmException("Failed to update external IDs", e);
}
}
14
View Complete Implementation : ExternalIdIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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();
}
}
14
View Complete Implementation : ExternalIdIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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();
}
}
14
View Complete Implementation : CommitUtil.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
/**
* Allows creating a revert change.
*
* @param notes ChangeNotes of the change being reverted.
* @param user Current User performing the revert.
* @param input the RevertInput enreplacedy for conducting the revert.
* @param timestamp timestamp for the created change.
* @return ObjectId that represents the newly created commit.
*/
public Change.Id createRevertChange(ChangeNotes notes, CurrentUser user, RevertInput input, Timestamp timestamp) throws RestApiException, UpdateException, ConfigInvalidException, IOException {
String message = Strings.emptyToNull(input.message);
try (Repository git = repoManager.openRepository(notes.getProjectName());
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk revWalk = new RevWalk(reader)) {
ObjectId generatedChangeId = Change.generateChangeId();
ObjectId revCommit = createRevertCommit(message, notes, user, timestamp, oi, revWalk, generatedChangeId);
return createRevertChangeFromCommit(revCommit, input, notes, user, generatedChangeId, timestamp, oi, revWalk, git);
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(notes.getChangeId().toString(), e);
}
}
14
View Complete Implementation : BranchTicketService.java
Copyright Apache License 2.0
Author : gitblit
Copyright Apache License 2.0
Author : gitblit
/**
* Creates an in-memory index of the ticket change.
*
* @param changeId
* @param change
* @return an in-memory index
* @throws IOException
*/
private DirCache createIndex(Repository db, long ticketId, Change change) throws IOException, ClreplacedNotFoundException, NoSuchFieldException {
String ticketPath = toTicketPath(ticketId);
DirCache newIndex = DirCache.newInCore();
DirCacheBuilder builder = newIndex.builder();
ObjectInserter inserter = db.newObjectInserter();
Set<String> ignorePaths = new TreeSet<String>();
try {
// create/update the journal
// exclude the attachment content
List<Change> changes = getJournal(db, ticketId);
changes.add(change);
String journal = TicketSerializer.serializeJournal(changes).trim();
byte[] journalBytes = journal.getBytes(Constants.ENCODING);
String journalPath = ticketPath + "/" + JOURNAL;
final DirCacheEntry journalEntry = new DirCacheEntry(journalPath);
journalEntry.setLength(journalBytes.length);
journalEntry.setLastModified(change.date.getTime());
journalEntry.setFileMode(FileMode.REGULAR_FILE);
journalEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, journalBytes));
// add journal to index
builder.add(journalEntry);
ignorePaths.add(journalEntry.getPathString());
// Add any attachments to the index
if (change.hasAttachments()) {
for (Attachment attachment : change.attachments) {
// build a path name for the attachment and mark as ignored
String path = toAttachmentPath(ticketId, attachment.name);
ignorePaths.add(path);
// create an index entry for this attachment
final DirCacheEntry entry = new DirCacheEntry(path);
entry.setLength(attachment.content.length);
entry.setLastModified(change.date.getTime());
entry.setFileMode(FileMode.REGULAR_FILE);
// insert object
entry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, attachment.content));
// add to temporary in-core index
builder.add(entry);
}
}
for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
builder.add(entry);
}
// finish the index
builder.finish();
} finally {
inserter.close();
}
return newIndex;
}
14
View Complete Implementation : BranchTicketService.java
Copyright Apache License 2.0
Author : gitblit
Copyright Apache License 2.0
Author : gitblit
/**
* 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();
}
}
14
View Complete Implementation : GitUtils.java
Copyright MIT License
Author : jenkinsci
Copyright MIT License
Author : jenkinsci
/**
* Creates an in-memory index of the issue change.
*/
private static DirCache createTemporaryIndex(final Repository repo, final ObjectId headId, final String path, final byte[] contents) {
final DirCache inCoreIndex = DirCache.newInCore();
final DirCacheBuilder dcBuilder = inCoreIndex.builder();
try (final ObjectInserter inserter = repo.newObjectInserter()) {
long lastModified = System.currentTimeMillis();
try {
if (contents != null) {
final DirCacheEntry dcEntry = new DirCacheEntry(path);
dcEntry.setLength(contents.length);
dcEntry.setLastModified(lastModified);
dcEntry.setFileMode(FileMode.REGULAR_FILE);
try (InputStream inputStream = new ByteArrayInputStream(contents)) {
dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, contents.length, inputStream));
}
dcBuilder.add(dcEntry);
}
if (headId != null) {
final TreeWalk treeWalk = new TreeWalk(repo);
final int hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
treeWalk.setRecursive(true);
while (treeWalk.next()) {
final String walkPath = treeWalk.getPathString();
final CanonicalTreeParser hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.clreplaced);
if (!walkPath.equals(path)) {
// add entries from HEAD for all other paths
// create a new DirCacheEntry with data retrieved from HEAD
final DirCacheEntry dcEntry = new DirCacheEntry(walkPath);
dcEntry.setObjectId(hTree.getEntryObjectId());
dcEntry.setFileMode(hTree.getEntryFileMode());
// add to temporary in-core index
dcBuilder.add(dcEntry);
}
}
// treeWalk.release();
}
dcBuilder.finish();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (contents == null) {
final DirCacheEditor editor = inCoreIndex.editor();
editor.add(new DirCacheEditor.DeleteTree(path));
editor.finish();
}
return inCoreIndex;
}
13
View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private Ref createRef(Repository repo, String ref) throws IOException {
try (ObjectInserter oi = repo.newObjectInserter();
RevWalk rw = new RevWalk(repo)) {
ObjectId emptyCommit = createCommit(repo);
RefUpdate updateRef = repo.updateRef(ref);
updateRef.setExpectedOldObjectId(ObjectId.zeroId());
updateRef.setNewObjectId(emptyCommit);
replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
return repo.exactRef(ref);
}
}
13
View Complete Implementation : GitUtils.java
Copyright MIT License
Author : jenkinsci
Copyright MIT License
Author : jenkinsci
// TODO - remove once https://github.com/spotbugs/spotbugs/issues/756 is resolved
@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE" }, justification = "JDK11 produces different bytecode - https://github.com/spotbugs/spotbugs/issues/756")
public static void commit(final Repository repo, final String refName, final String path, final byte[] contents, final String name, final String email, final String message, final TimeZone timeZone, final Date when) {
final PersonIdent author = buildPersonIdent(repo, name, email, timeZone, when);
try (final ObjectInserter odi = repo.newObjectInserter()) {
// Create the in-memory index of the new/updated issue.
final ObjectId headId = repo.resolve(refName + "^{commit}");
final DirCache index = createTemporaryIndex(repo, headId, path, contents);
final ObjectId indexTreeId = index.writeTree(odi);
// Create a commit object
final CommitBuilder commit = new CommitBuilder();
commit.setAuthor(author);
commit.setCommitter(author);
commit.setEncoding(Constants.CHARACTER_ENCODING);
commit.setMessage(message);
// headId can be null if the repository has no commit yet
if (headId != null) {
commit.setParentId(headId);
}
commit.setTreeId(indexTreeId);
// Insert the commit into the repository
final ObjectId commitId = odi.insert(commit);
odi.flush();
try (RevWalk revWalk = new RevWalk(repo)) {
final RevCommit revCommit = revWalk.parseCommit(commitId);
final RefUpdate ru = repo.updateRef(refName);
if (headId == null) {
ru.setExpectedOldObjectId(ObjectId.zeroId());
} else {
ru.setExpectedOldObjectId(headId);
}
ru.setNewObjectId(commitId);
ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
final RefUpdate.Result rc = ru.forceUpdate();
switch(rc) {
case NEW:
case FORCED:
case FAST_FORWARD:
break;
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
default:
throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc));
}
}
} catch (ConcurrentRefUpdateException | IOException | JGitInternalException ex) {
throw new RuntimeException(ex);
}
}
13
View Complete Implementation : JobsServlet.java
Copyright Apache License 2.0
Author : palantir
Copyright Apache License 2.0
Author : palantir
// This parses the jobRequest and updates the config file for the project.
// It the creates job config files for new jobs
// and marks files of deleted jobs with "DELETED"
public Map<String, Map<String, String>> parseJobRequest(HttpServletRequest req, String projectName) throws JsonSyntaxException, IOException, NoSuchProjectException, NoFilepatternException, GitAPIException {
Map<String, Map<String, String>> jobToParams = new HashMap<String, Map<String, String>>();
File projectConfigDirectory = new File(sitePaths.etc_dir, projectName);
if (!projectConfigDirectory.exists())
projectConfigDirectory.mkdir();
File projectConfigFile = new File(projectConfigDirectory, "created_jobs");
if (!projectConfigFile.exists())
projectConfigFile.createNewFile();
JsonObject requestBody = (JsonObject) (new JsonParser()).parse(CharStreams.toString(req.getReader()));
// get number of jobs
// If all jobs are deleted, we must purge jobs
int numOfJobs = requestBody.get("items").getAsJsonArray().size();
ArrayList<String> receivedJobNames = new ArrayList<String>();
if (numOfJobs < 1) {
ArrayList<String> deletedJobs = updateProjectJobFiles(projectConfigFile, projectConfigDirectory, receivedJobNames);
for (String deleted : deletedJobs) {
jobToParams.put(deleted, null);
}
return jobToParams;
}
CurrentUser currentUser = this.projectControlFactory.controlFor(new NameKey(projectName)).getCurrentUser();
String gitPath = getGitPath(sitePaths);
File gitDir = new File(gitPath, projectName + ".git");
Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build();
ObjectInserter objectInserter = repository.newObjectInserter();
HashMap<String, ObjectId> jobsToIds = new HashMap<String, ObjectId>();
// replacedign file name and append to tree
TreeFormatter treeFormatter = new TreeFormatter();
// for each received job, create or rewrite its config file and add to
// jobToParams
for (int i = 0; i < numOfJobs; i++) {
JsonObject jobObject = requestBody.get("items").getAsJsonArray().get(i).getAsJsonObject();
String jobName = jobObject.get("jobName").toString();
// Remove leading and trailing quotations ex. "jobname" becomes jobname
jobName = jobName.substring(1, jobName.length() - 1);
receivedJobNames.add(jobName);
String type = jobObject.get("jobType").toString();
type = type.substring(1, type.length() - 1);
int numOfParams = jobObject.get("items").getAsJsonArray().size();
JsonArray paramsArray = jobObject.get("items").getAsJsonArray();
FileBasedConfig jobConfig = makeJobConfigFile(projectConfigDirectory, jobName, currentUser);
Map<String, String> parsedParams = new HashMap<String, String>();
parsedParams.put("projectName", projectName);
for (int j = 0; j < numOfParams; j++) {
String field = paramsArray.get(j).getAsJsonObject().get("field").toString();
field = field.substring(1, field.length() - 1);
String value = paramsArray.get(j).getAsJsonObject().get("value").toString();
value = value.substring(1, value.length() - 1);
parsedParams.put(field, value);
// update jobconfig files
jobConfig.setString("jobType", type, field, value);
}
jobConfig.save();
jobsToIds.put(jobName, createGitFileId(repository, jobConfig, objectInserter, jobName));
jobToParams.put(jobName, parsedParams);
}
for (String jobName : jobsToIds.keySet()) {
treeFormatter.append(jobName + ".config", FileMode.REGULAR_FILE, jobsToIds.get(jobName));
}
ObjectId treeId = objectInserter.insert(treeFormatter);
objectInserter.flush();
updateProjectRef(treeId, objectInserter, repository, currentUser);
// update or create project files for all jobs
ArrayList<String> deletedJobs = updateProjectJobFiles(projectConfigFile, projectConfigDirectory, receivedJobNames);
for (String deleted : deletedJobs) {
jobToParams.put(deleted, null);
}
// returns map of job name to params
return jobToParams;
}
13
View Complete Implementation : RepoSequenceTest.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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);
replacedertThat(ru.forceUpdate()).isAnyOf(RefUpdate.Result.NEW, RefUpdate.Result.FORCED);
return newId;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
13
View Complete Implementation : ProjectResetterTest.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private Ref updateRef(Repository repo, Ref ref) throws IOException {
try (ObjectInserter oi = repo.newObjectInserter();
RevWalk rw = new RevWalk(repo)) {
ObjectId emptyCommit = createCommit(repo);
RefUpdate updateRef = repo.updateRef(ref.getName());
updateRef.setExpectedOldObjectId(ref.getObjectId());
updateRef.setNewObjectId(emptyCommit);
updateRef.setForceUpdate(true);
replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.FORCED);
Ref updatedRef = repo.exactRef(ref.getName());
replacedertThat(updatedRef.getObjectId()).isNotEqualTo(ref.getObjectId());
return updatedRef;
}
}
12
View Complete Implementation : RepoSequence.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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);
// Required for non-commitish updates.
ru.setForceUpdate(true);
RefUpdate.Result result = ru.update(rw);
if (refUpdated(result)) {
gitRefUpdated.fire(projectName, ru, null);
}
return result;
}
12
View Complete Implementation : GroupsIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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);
replacedertThat(updateRef.update(rw)).isEqualTo(RefUpdate.Result.NEW);
}
}
12
View Complete Implementation : IntBlob.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
public static RefUpdate tryStore(Repository repo, RevWalk rw, Project.NameKey projectName, String refName, @Nullable ObjectId oldId, int val, GitReferenceUpdated gitRefUpdated) 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);
// Required for non-commitish updates.
ru.setForceUpdate(true);
RefUpdate.Result result = ru.update(rw);
if (refUpdated(result)) {
gitRefUpdated.fire(projectName, ru, null);
}
return ru;
}
12
View Complete Implementation : RevertSubmission.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
/**
* This function finds the base that the first revert in a project + branch should be based on. It
* searches using BFS for the first commit that is either: 1. Has 2 or more parents, and has as
* parents at least one commit that is part of the submission. 2. A commit that is part of the
* submission. If neither of those are true, it just continues the search by going to the parents.
*
* <p>If 1 is true, if all the parents are part of the submission, it just returns that commit. If
* only some of them are in the submission, the function changes and starts checking only the
* commits that are not part of the submission. If all of them are part of the submission (or they
* are also merge commits that have as parents only other merge commits, or other changes that are
* part of the submission), we will return possibleMergeCommitToReturn which is the original
* commit we started with when 1 was determined to be true.
*
* <p>If 2 is true, it will return the commit that WalkSorter has decided that it should be the
* first commit reverted (e.g changeNotes, which is also the commit that is the first in the
* topological sorting). Unless possibleMergeCommitToReturn is not null, which means we already
* encountered a merge commit with a part of the submission earlier, which means we should return
* that merge commit.
*
* <p>It doesn't run through the entire graph since it will stop once it finds at least one commit
* that is part of the submission.
*
* @param changeNotes changeNotes for the change that is found by WalkSorter to be the first one
* that should be reverted, the first in the topological sorting.
* @param commitIds The commitIds of this project and branch.
* @return the base of the first revert.
*/
private ObjectId getBase(ChangeNotes changeNotes, Set<ObjectId> commitIds) throws StorageException, IOException {
try (Repository git = repoManager.openRepository(changeNotes.getProjectName());
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk revWalk = new RevWalk(reader)) {
ObjectId startCommit = git.getRefDatabase().findRef(changeNotes.getChange().getDest().branch()).getObjectId();
Queue<ObjectId> commitsToSearch = new ArrayDeque<>();
commitsToSearch.add(startCommit);
while (!commitsToSearch.isEmpty()) {
RevCommit revCommit = revWalk.parseCommit(commitsToSearch.poll());
if (commitIds.contains(revCommit.getId())) {
return changeNotes.getCurrentPatchSet().commitId();
}
if (revCommit.getParentCount() > 1) {
List<RevCommit> parentsInSubmission = Arrays.stream(revCommit.getParents()).filter(parent -> commitIds.contains(parent.getId())).collect(Collectors.toList());
if (parentsInSubmission.size() > 1) {
// Found a merge commit that has multiple parent commits that are part of the
// submission.
return revCommit.getId();
}
if (!parentsInSubmission.isEmpty()) {
// Found a merge commit that has only one parent in this submission, but also other
// parents not in the submission. Now we need to check if the others are merge commits
// that have as parents only other merge commits, or other changes from the
// submission.
commitsToSearch.clear();
commitsToSearch.addAll(Arrays.stream(revCommit.getParents()).filter(parent -> !commitIds.contains(parent.getId())).collect(Collectors.toList()));
if (isMergeCommitDescendantOfAllChangesInTheProjectAndBranchOfTheSubmission(commitsToSearch, commitIds, revWalk, revCommit, changeNotes)) {
// Found a second commit of that submission that share the same merge commit.
return revCommit.getId();
}
// Couldn't find a second commit of that submission that share the same merge commit.
return changeNotes.getCurrentPatchSet().commitId();
}
}
commitsToSearch.addAll(Arrays.asList(revCommit.getParents()));
}
// This should never happen since it can only happen if we go through the entire repository
// without finding a single commit that matches any commit from the submission.
throw new StorageException(String.format("Couldn't find change %s in the repository %s", changeNotes.getChangeId(), changeNotes.getProjectName().get()));
}
}
12
View Complete Implementation : BlobEdits.java
Copyright MIT License
Author : theonedev
Copyright MIT License
Author : theonedev
/**
* Commit specified file into specified repository.
*
* @param repository
* repository to make the new commit
* @param refName
* ref name to replacedociate the new commit with
* @param expectedOldCommitId
* expected old commit id of above ref
* @param parentCommitId
* parent commit id of the new commit
* @param authorAndCommitter
* author and committer person ident for the new commit
* @param commitMessage
* commit message for the new commit
* @return
* id of new commit
* @throws ObsoleteCommitException
* if expected old commit id of the ref does not equal to
* expectedOldCommitId, or if expectedOldCommitId is specified as <tt>null</tt> and
* ref exists
* @throws ObjectNotFoundException
* if file to delete does not exist when oldPath!=null&&newFile==null
* @throws ObjectAlreadyExistsException
* if added/renamed file already exists when newFile!=null && (oldPath==null || !oldPath.equals(newFile.getPath()))
*/
public ObjectId commit(Repository repository, String refName, ObjectId expectedOldCommitId, ObjectId parentCommitId, PersonIdent authorAndCommitter, String commitMessage) {
try (RevWalk revWalk = new RevWalk(repository);
TreeWalk treeWalk = new TreeWalk(repository);
ObjectInserter inserter = repository.newObjectInserter()) {
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(authorAndCommitter);
commit.setCommitter(authorAndCommitter);
commit.setMessage(commitMessage);
RevTree revTree;
if (!parentCommitId.equals(ObjectId.zeroId())) {
commit.setParentId(parentCommitId);
revTree = revWalk.parseCommit(parentCommitId).getTree();
treeWalk.addTree(revTree);
} else {
revTree = null;
}
ObjectId treeId = insertTree(revTree, treeWalk, inserter, null, new HashSet<>(oldPaths), new HashMap<>(newBlobs));
if (treeId != null)
commit.setTreeId(treeId);
else
commit.setTreeId(inserter.insert(new TreeFormatter()));
ObjectId commitId = inserter.insert(commit);
inserter.flush();
RefUpdate ru = repository.updateRef(refName);
ru.setRefLogIdent(authorAndCommitter);
ru.setNewObjectId(commitId);
ru.setExpectedOldObjectId(expectedOldCommitId);
GitUtils.updateRef(ru);
return commitId;
} catch (RevisionSyntaxException | IOException e) {
throw new RuntimeException(e);
}
}
12
View Complete Implementation : BranchTicketService.java
Copyright Apache License 2.0
Author : tomaswolf
Copyright Apache License 2.0
Author : tomaswolf
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;
}
12
View Complete Implementation : RefLogUtils.java
Copyright Apache License 2.0
Author : tomaswolf
Copyright Apache License 2.0
Author : tomaswolf
/**
* 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();
long now = System.currentTimeMillis();
Set<String> ignorePaths = new TreeSet<String>();
try (ObjectInserter inserter = repo.newObjectInserter()) {
// 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
try (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.clreplaced);
}
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);
}
}
}
}
// finish temporary in-core index used for this commit
dcBuilder.finish();
}
return inCoreIndex;
}
11
View Complete Implementation : ChangeEditModifier.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
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;
}
}
11
View Complete Implementation : ExternalIdIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private String insertExternalIdWithoutAccountId(Repository repo, RevWalk rw, String externalId) throws IOException {
ObjectId rev = ExternalIdReader.readRevision(repo);
NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
ExternalId extId = ExternalId.create(ExternalId.Key.parse(externalId), admin.id);
try (ObjectInserter ins = repo.newObjectInserter()) {
ObjectId noteId = extId.key().sha1();
Config c = new Config();
extId.writeToConfig(c);
c.unset("externalId", extId.key().get(), "accountId");
byte[] raw = c.toText().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();
}
}
11
View Complete Implementation : ExternalIdIT.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private String insertExternalIdWithKeyThatDoesntMatchNoteId(Repository repo, RevWalk rw, String externalId) throws IOException {
ObjectId rev = ExternalIdReader.readRevision(repo);
NoteMap noteMap = ExternalIdReader.readNoteMap(rw, rev);
ExternalId extId = ExternalId.create(ExternalId.Key.parse(externalId), admin.id);
try (ObjectInserter ins = repo.newObjectInserter()) {
ObjectId noteId = ExternalId.Key.parse(externalId + "x").sha1();
Config c = new Config();
extId.writeToConfig(c);
byte[] raw = c.toText().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();
}
}
11
View Complete Implementation : RefLogUtils.java
Copyright Apache License 2.0
Author : gitblit
Copyright Apache License 2.0
Author : gitblit
/**
* 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.clreplaced);
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;
}
11
View Complete Implementation : Squash.java
Copyright Apache License 2.0
Author : kiegroup
Copyright Apache License 2.0
Author : kiegroup
public void execute() {
final Repository repo = this.git.getRepository();
final RevCommit latestCommit = git.getLastCommit(branch);
final RevCommit startCommit = checkIfCommitIsPresentAtBranch(this.git, this.branch, this.startCommitString);
RevCommit parent = startCommit;
if (startCommit.getParentCount() > 0) {
parent = startCommit.getParent(0);
}
final CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.setParentId(parent);
commitBuilder.setTreeId(latestCommit.getTree().getId());
commitBuilder.setMessage(squashedCommitMessage);
commitBuilder.setAuthor(startCommit.getAuthorIdent());
commitBuilder.setCommitter(startCommit.getAuthorIdent());
try (final ObjectInserter odi = repo.newObjectInserter()) {
final RevCommit squashedCommit = git.resolveRevCommit(odi.insert(commitBuilder));
git.refUpdate(branch, squashedCommit);
} catch (ConcurrentRefUpdateException | IOException e) {
throw new GitException("Error on executing squash.", e);
}
}
10
View Complete Implementation : VersionedMetaDataOnInit.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
protected void save(PersonIdent ident, String msg) throws IOException, ConfigInvalidException {
File path = getPath();
if (path == null) {
throw new IOException(project + " does not exist.");
}
try (Repository repo = new FileRepository(path);
ObjectInserter i = repo.newObjectInserter();
ObjectReader r = repo.newObjectReader();
RevWalk rw = new RevWalk(r)) {
inserter = i;
reader = r;
RevTree srcTree = revision != null ? rw.parseTree(revision) : null;
newTree = readTree(srcTree);
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(ident);
commit.setCommitter(ident);
commit.setMessage(msg);
onSave(commit);
ObjectId res = newTree.writeTree(inserter);
if (res.equals(srcTree)) {
return;
}
commit.setTreeId(res);
if (revision != null) {
commit.addParentId(revision);
}
ObjectId newRevision = inserter.insert(commit);
updateRef(repo, ident, newRevision, "commit: " + msg);
revision = rw.parseCommit(newRevision);
} finally {
inserter = null;
reader = null;
}
}
10
View Complete Implementation : Schema_144.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
Set<ExternalId> toAdd = new HashSet<>();
try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT " + "account_id, " + "email_address, " + "preplacedword, " + "external_id " + "FROM account_external_ids")) {
while (rs.next()) {
Account.Id accountId = new Account.Id(rs.getInt(1));
String email = rs.getString(2);
String preplacedword = rs.getString(3);
String externalId = rs.getString(4);
toAdd.add(ExternalId.create(ExternalId.Key.parse(externalId), accountId, email, preplacedword));
}
}
try {
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);
for (ExternalId extId : toAdd) {
ExternalIdsUpdate.upsert(rw, ins, noteMap, extId);
}
ExternalIdsUpdate.commit(allUsersName, repo, rw, ins, rev, noteMap, COMMIT_MSG, serverIdent, serverIdent, null, GitReferenceUpdated.DISABLED);
}
} catch (IOException | ConfigInvalidException e) {
throw new OrmException("Failed to migrate external IDs to NoteDb", e);
}
}
10
View Complete Implementation : ReviewDbBatchUpdate.java
Copyright Apache License 2.0
Author : gerrit-review
Copyright Apache License 2.0
Author : gerrit-review
private void executeNoteDbUpdates(List<ChangeTask> tasks) throws ResourceConflictException, IOException {
// Aggregate together all NoteDb ref updates from the ops we executed,
// possibly in parallel. Each task had its own NoteDbUpdateManager instance
// with its own thread-local copy of the repo(s), but each of those was just
// used for staging updates and was never executed.
//
// Use a new BatchRefUpdate as the original batchRefUpdate field is intended
// for use only by the updateRepo phase.
//
// See the comments in NoteDbUpdateManager#execute() for why we execute the
// updates on the change repo first.
logDebug("Executing NoteDb updates for {} changes", tasks.size());
try {
initRepository();
BatchRefUpdate changeRefUpdate = repoView.getRepository().getRefDatabase().newBatchUpdate();
boolean hasAllUsersCommands = false;
try (ObjectInserter ins = repoView.getRepository().newObjectInserter()) {
int objs = 0;
for (ChangeTask task : tasks) {
if (task.noteDbResult == null) {
logDebug("No-op update to {}", task.id);
continue;
}
for (ReceiveCommand cmd : task.noteDbResult.changeCommands()) {
changeRefUpdate.addCommand(cmd);
}
for (InsertedObject obj : task.noteDbResult.changeObjects()) {
objs++;
ins.insert(obj.type(), obj.data().toByteArray());
}
hasAllUsersCommands |= !task.noteDbResult.allUsersCommands().isEmpty();
}
logDebug("Collected {} objects and {} ref updates to change repo", objs, changeRefUpdate.getCommands().size());
executeNoteDbUpdate(getRevWalk(), ins, changeRefUpdate);
}
if (hasAllUsersCommands) {
try (Repository allUsersRepo = repoManager.openRepository(allUsers);
RevWalk allUsersRw = new RevWalk(allUsersRepo);
ObjectInserter allUsersIns = allUsersRepo.newObjectInserter()) {
int objs = 0;
BatchRefUpdate allUsersRefUpdate = allUsersRepo.getRefDatabase().newBatchUpdate();
for (ChangeTask task : tasks) {
for (ReceiveCommand cmd : task.noteDbResult.allUsersCommands()) {
allUsersRefUpdate.addCommand(cmd);
}
for (InsertedObject obj : task.noteDbResult.allUsersObjects()) {
allUsersIns.insert(obj.type(), obj.data().toByteArray());
}
}
logDebug("Collected {} objects and {} ref updates to All-Users", objs, allUsersRefUpdate.getCommands().size());
executeNoteDbUpdate(allUsersRw, allUsersIns, allUsersRefUpdate);
}
} else {
logDebug("No All-Users updates");
}
} catch (IOException e) {
if (tasks.stream().allMatch(t -> t.storage == PrimaryStorage.REVIEW_DB)) {
// Ignore all errors trying to update NoteDb at this point. We've already written the
// NoteDbChangeStates to ReviewDb, which means if any state is out of date it will be
// rebuilt the next time it is needed.
//
// Always log even without RequestId.
log.debug("Ignoring NoteDb update error after ReviewDb write", e);
// Otherwise, we can't prove it's safe to ignore the error, either because some change had
// NOTE_DB primary, or a task failed before determining the primary storage.
} else if (e instanceof LockFailureException) {
// LOCK_FAILURE is a special case indicating there was a conflicting write to a meta ref,
// although it happened too late for us to produce anything but a generic error message.
throw new ResourceConflictException("Updating change failed due to conflicting write", e);
}
throw e;
}
}
10
View Complete Implementation : CreateChange.java
Copyright Apache License 2.0
Author : GerritCodeReview
Copyright Apache License 2.0
Author : GerritCodeReview
private Change createNewChange(ChangeInput input, IdentifiedUser me, ProjectState projectState, BatchUpdate.Factory updateFactory) throws RestApiException, PermissionBackendException, IOException, ConfigInvalidException, UpdateException {
logger.atFine().log("Creating new change for target branch %s in project %s" + " (new branch = %s, base change = %s, base commit = %s)", input.branch, projectState.getName(), input.newBranch, input.baseChange, input.baseCommit);
try (Repository git = gitManager.openRepository(projectState.getNameKey());
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk rw = new RevWalk(reader)) {
PatchSet basePatchSet = null;
List<String> groups = Collections.emptyList();
if (input.baseChange != null) {
ChangeNotes baseChange = getBaseChange(input.baseChange);
basePatchSet = psUtil.current(baseChange);
groups = basePatchSet.groups();
logger.atFine().log("base patch set = %s (groups = %s)", basePatchSet.id(), groups);
}
ObjectId parentCommit = getParentCommit(git, rw, input.branch, input.newBranch, basePatchSet, input.baseCommit, input.merge);
logger.atFine().log("parent commit = %s", parentCommit != null ? parentCommit.name() : "NULL");
RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
Timestamp now = TimeUtil.nowTs();
PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
String commitMessage = getCommitMessage(input.subject, me);
RevCommit c;
if (input.merge != null) {
// create a merge commit
c = newMergeCommit(git, oi, rw, projectState, mergeTip, input.merge, author, commitMessage);
} else {
// create an empty commit
c = newCommit(oi, rw, author, mergeTip, commitMessage);
}
Change.Id changeId = Change.id(seq.nextChangeId());
ChangeInserter ins = changeInserterFactory.create(changeId, c, input.branch);
ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
ins.setTopic(input.topic);
ins.setPrivate(input.isPrivate);
ins.setWorkInProgress(input.workInProgress);
ins.setGroups(groups);
try (BatchUpdate bu = updateFactory.create(projectState.getNameKey(), me, now)) {
bu.setRepository(git, rw, oi);
bu.setNotify(notifyResolver.resolve(firstNonNull(input.notify, NotifyHandling.ALL), input.notifyDetails));
bu.insertChange(ins);
bu.execute();
}
return ins.getChange();
} catch (InvalidMergeStrategyException e) {
throw new BadRequestException(e.getMessage());
}
}