use of org.eclipse.jgit.dircache.DirCache in project gitblit by gitblit.
the class RefLogUtils method updateRefLog.
/**
* Updates the reflog with the received commands.
*
* @param user
* @param repository
* @param commands
* @return true, if the update was successful
*/
public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) {
// only track branches and tags
List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>();
for (ReceiveCommand cmd : commands) {
if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) {
continue;
}
filteredCommands.add(cmd);
}
if (filteredCommands.isEmpty()) {
// nothing to log
return true;
}
RefModel reflogBranch = getRefLogBranch(repository);
if (reflogBranch == null) {
JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
}
boolean success = false;
String message = "push";
try {
ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
ObjectInserter odi = repository.newObjectInserter();
try {
// Create the in-memory index of the reflog log entry
DirCache index = createIndex(repository, headId, commands);
ObjectId indexTreeId = index.writeTree(odi);
PersonIdent ident;
if (UserModel.ANONYMOUS.equals(user)) {
// anonymous push
ident = new PersonIdent(user.username + "/" + user.username, user.username);
} else {
// construct real pushing account
ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username), user.emailAddress == null ? user.username : user.emailAddress);
}
// Create a commit object
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();
RevWalk revWalk = new RevWalk(repository);
try {
RevCommit revCommit = revWalk.parseCommit(commitId);
RefUpdate ru = repository.updateRef(GB_REFLOG);
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, GB_REFLOG, commitId.toString(), rc));
}
} finally {
revWalk.close();
}
} finally {
odi.close();
}
} catch (Throwable t) {
error(t, repository, "Failed to commit reflog entry to {0}");
}
return success;
}
use of org.eclipse.jgit.dircache.DirCache in project gitblit by gitblit.
the class BranchTicketService method commitChangeImpl.
/**
* Commit a ticket change to the repository.
*
* @param repository
* @param ticketId
* @param change
* @return true, if the change was committed
*/
@Override
protected synchronized boolean commitChangeImpl(RepositoryModel repository, long ticketId, Change change) {
boolean success = false;
Repository db = repositoryManager.getRepository(repository.name);
try {
DirCache index = createIndex(db, ticketId, change);
success = commitIndex(db, index, change.author, "#" + ticketId);
} catch (Throwable t) {
log.error(MessageFormat.format("Failed to commit ticket {0,number,0} to {1}", ticketId, db.getDirectory()), t);
} finally {
db.close();
}
return success;
}
use of org.eclipse.jgit.dircache.DirCache in project gitblit by gitblit.
the class BranchTicketService method createIndex.
/**
* 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, ClassNotFoundException, 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;
}
use of org.eclipse.jgit.dircache.DirCache in project gitblit by gitblit.
the class NewRepositoryPage method initialCommit.
/**
* Prepare the initial commit for the repository.
*
* @param repository
* @param addReadme
* @param gitignore
* @param addGitFlow
* @return true if an initial commit was created
*/
protected boolean initialCommit(RepositoryModel repository, boolean addReadme, String gitignore, boolean addGitFlow) {
boolean initialCommit = addReadme || !StringUtils.isEmpty(gitignore) || addGitFlow;
if (!initialCommit) {
return false;
}
// build an initial commit
boolean success = false;
Repository db = app().repositories().getRepository(repositoryModel.name);
ObjectInserter odi = db.newObjectInserter();
try {
UserModel user = GitBlitWebSession.get().getUser();
String email = Optional.fromNullable(user.emailAddress).or(user.username + "@" + "gitblit");
PersonIdent author = new PersonIdent(user.getDisplayName(), email);
DirCache newIndex = DirCache.newInCore();
DirCacheBuilder indexBuilder = newIndex.builder();
if (addReadme) {
// insert a README
String title = StringUtils.stripDotGit(StringUtils.getLastPathElement(repositoryModel.name));
String description = repositoryModel.description == null ? "" : repositoryModel.description;
String readme = String.format("## %s\n\n%s\n\n", title, description);
byte[] bytes = readme.getBytes(Constants.ENCODING);
DirCacheEntry entry = new DirCacheEntry("README.md");
entry.setLength(bytes.length);
entry.setLastModified(System.currentTimeMillis());
entry.setFileMode(FileMode.REGULAR_FILE);
entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
indexBuilder.add(entry);
}
if (!StringUtils.isEmpty(gitignore)) {
// insert a .gitignore file
File dir = app().runtime().getFileOrFolder(Keys.git.gitignoreFolder, "${baseFolder}/gitignore");
File file = new File(dir, gitignore + ".gitignore");
if (file.exists() && file.length() > 0) {
byte[] bytes = FileUtils.readContent(file);
if (!ArrayUtils.isEmpty(bytes)) {
DirCacheEntry entry = new DirCacheEntry(".gitignore");
entry.setLength(bytes.length);
entry.setLastModified(System.currentTimeMillis());
entry.setFileMode(FileMode.REGULAR_FILE);
entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
indexBuilder.add(entry);
}
}
}
if (addGitFlow) {
// insert a .gitflow file
Config config = new Config();
config.setString("gitflow", null, "masterBranch", Constants.MASTER);
config.setString("gitflow", null, "developBranch", Constants.DEVELOP);
config.setString("gitflow", null, "featureBranchPrefix", "feature/");
config.setString("gitflow", null, "releaseBranchPrefix", "release/");
config.setString("gitflow", null, "hotfixBranchPrefix", "hotfix/");
config.setString("gitflow", null, "supportBranchPrefix", "support/");
config.setString("gitflow", null, "versionTagPrefix", "");
byte[] bytes = config.toText().getBytes(Constants.ENCODING);
DirCacheEntry entry = new DirCacheEntry(".gitflow");
entry.setLength(bytes.length);
entry.setLastModified(System.currentTimeMillis());
entry.setFileMode(FileMode.REGULAR_FILE);
entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
indexBuilder.add(entry);
}
indexBuilder.finish();
if (newIndex.getEntryCount() == 0) {
// nothing to commit
return false;
}
ObjectId treeId = newIndex.writeTree(odi);
// Create a commit object
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(author);
commit.setCommitter(author);
commit.setEncoding(Constants.ENCODING);
commit.setMessage("Initial commit");
commit.setTreeId(treeId);
// Insert the commit into the repository
ObjectId commitId = odi.insert(commit);
odi.flush();
// set the branch refs
RevWalk revWalk = new RevWalk(db);
try {
// set the master branch
RevCommit revCommit = revWalk.parseCommit(commitId);
RefUpdate masterRef = db.updateRef(Constants.R_MASTER);
masterRef.setNewObjectId(commitId);
masterRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
Result masterRC = masterRef.update();
switch(masterRC) {
case NEW:
success = true;
break;
default:
success = false;
}
if (addGitFlow) {
// set the develop branch for git-flow
RefUpdate developRef = db.updateRef(Constants.R_DEVELOP);
developRef.setNewObjectId(commitId);
developRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
Result developRC = developRef.update();
switch(developRC) {
case NEW:
success = true;
break;
default:
success = false;
}
}
} finally {
revWalk.close();
}
} catch (UnsupportedEncodingException e) {
logger().error(null, e);
} catch (IOException e) {
logger().error(null, e);
} finally {
odi.close();
db.close();
}
return success;
}
use of org.eclipse.jgit.dircache.DirCache in project gerrit by GerritCodeReview.
the class SubmoduleOp method readTree.
private static DirCache readTree(RevWalk rw, ObjectId base) throws IOException {
final DirCache dc = DirCache.newInCore();
final DirCacheBuilder b = dc.builder();
b.addTree(// no prefix path
new byte[0], // standard stage
DirCacheEntry.STAGE_0, rw.getObjectReader(), rw.parseTree(base));
b.finish();
return dc;
}
Aggregations