List of usage examples for org.eclipse.jgit.lib ObjectInserter insert
public ObjectId insert(int type, byte[] data) throws IOException
From source file:com.gitblit.tickets.BranchTicketService.java
License:Apache License
/** * Writes a file to the tickets branch.// w w w . ja v a 2 s . c om * * @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(); } }
From source file:com.gitblit.tickets.BranchTicketService.java
License:Apache License
/** * Creates an in-memory index of the ticket change. * * @param changeId// ww w . java2 s . c o m * @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; }
From source file:com.gitblit.utils.IssueUtils.java
License:Apache License
/** * Creates an in-memory index of the issue change. * /*from w ww . j ava 2 s. c om*/ * @param repo * @param headId * @param change * @return an in-memory index * @throws IOException */ private static DirCache createIndex(Repository repo, ObjectId headId, String issuePath, Change change) throws IOException { DirCache inCoreIndex = DirCache.newInCore(); DirCacheBuilder dcBuilder = inCoreIndex.builder(); ObjectInserter inserter = repo.newObjectInserter(); Set<String> ignorePaths = new TreeSet<String>(); try { // Add any attachments to the temporary index if (change.hasAttachments()) { for (Attachment attachment : change.attachments) { // build a path name for the attachment and mark as ignored String path = issuePath + "/" + attachment.id; ignorePaths.add(path); // create an index entry for this attachment final DirCacheEntry dcEntry = new DirCacheEntry(path); dcEntry.setLength(attachment.content.length); dcEntry.setLastModified(change.created.getTime()); dcEntry.setFileMode(FileMode.REGULAR_FILE); // insert object dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, attachment.content)); // 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.release(); // finish temporary in-core index used for this commit dcBuilder.finish(); } finally { inserter.release(); } return inCoreIndex; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Create an orphaned branch in a repository. * * @param repository// ww w. j a v a 2 s .c o m * @param branchName * @param author * if unspecified, Gitblit will be the author of this new branch * @return true if successful */ public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) { boolean success = false; String message = "Created branch " + branchName; if (author == null) { author = new PersonIdent("Gitblit", "gitblit@localhost"); } try { ObjectInserter odi = repository.newObjectInserter(); try { // Create a blob object to insert into a tree ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING)); // Create a tree object to reference from a commit TreeFormatter tree = new TreeFormatter(); tree.append(".branch", FileMode.REGULAR_FILE, blobId); ObjectId treeId = odi.insert(tree); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setTreeId(treeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); if (!branchName.startsWith("refs/")) { branchName = "refs/heads/" + branchName; } RefUpdate ru = repository.updateRef(branchName); ru.setNewObjectId(commitId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; default: success = false; } } finally { revWalk.close(); } } finally { odi.close(); } } catch (Throwable t) { error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName); } return success; }
From source file:com.gitblit.utils.PushLogUtils.java
License:Apache License
/** * Creates an in-memory index of the push log entry. * /*from w w w .j a v a2 s . c o m*/ * @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(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.release(); // finish temporary in-core index used for this commit dcBuilder.finish(); } finally { inserter.release(); } return inCoreIndex; }
From source file:com.gitblit.utils.RefLogUtils.java
License:Apache License
/** * Creates an in-memory index of the reflog entry. * * @param repo// www. j a va 2s . co m * @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; }
From source file:com.gitblit.wicket.pages.NewRepositoryPage.java
License:Apache License
/** * Prepare the initial commit for the repository. * * @param repository/*from w ww . j a va 2 s . c o m*/ * @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; }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
private void saveToNotes(ObjectInserter ins, PGPPublicKeyRing keyRing) throws PGPException, IOException { long keyId = keyRing.getPublicKey().getKeyID(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size() + 1); boolean replaced = false; for (PGPPublicKeyRing kr : existing) { if (sameKey(keyRing, kr)) { toWrite.add(keyRing);//from w w w . j a va 2 s.c om replaced = true; } else { toWrite.add(kr); } } if (!replaced) { toWrite.add(keyRing); } notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite))); }
From source file:com.google.gerrit.gpg.PublicKeyStore.java
License:Apache License
private void deleteFromNotes(ObjectInserter ins, Fingerprint fp) throws PGPException, IOException { long keyId = fp.getId(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size()); for (PGPPublicKeyRing kr : existing) { if (!fp.equalsBytes(kr.getPublicKey().getFingerprint())) { toWrite.add(kr);/*from w w w .j av a2 s.c om*/ } } if (toWrite.size() == existing.size()) { return; } else if (!toWrite.isEmpty()) { notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite))); } else { notes.remove(keyObjectId(keyId)); } }
From source file:com.google.gerrit.server.account.AccountsUpdate.java
License:Apache License
private static ObjectId emptyTree(ObjectInserter oi) throws IOException { return oi.insert(Constants.OBJ_TREE, new byte[] {}); }