List of usage examples for org.eclipse.jgit.lib Repository newObjectInserter
@NonNull
public ObjectInserter newObjectInserter()
From source file:com.gitblit.utils.PushLogUtils.java
License:Apache License
/** * Updates a push log.//from w w w . java 2s.c o m * * @param user * @param repository * @param commands * @return true, if the update was successful */ public static boolean updatePushLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) { RefModel pushlogBranch = getPushLogBranch(repository); if (pushlogBranch == null) { JGitUtils.createOrphanBranch(repository, GB_PUSHES, null); } boolean success = false; String message = "push"; try { ObjectId headId = repository.resolve(GB_PUSHES + "^{commit}"); ObjectInserter odi = repository.newObjectInserter(); try { // Create the in-memory index of the push log entry DirCache index = createIndex(repository, headId, commands); ObjectId indexTreeId = index.writeTree(odi); PersonIdent ident = new PersonIdent(user.getDisplayName(), user.emailAddress == null ? user.username : user.emailAddress); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setEncoding(Constants.CHARACTER_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_PUSHES); 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_PUSHES, commitId.toString(), rc)); } } finally { revWalk.release(); } } finally { odi.release(); } } catch (Throwable t) { error(t, repository, "Failed to commit pushlog entry to {0}"); } return success; }
From source file:com.gitblit.utils.PushLogUtils.java
License:Apache License
/** * Creates an in-memory index of the push log entry. * /* ww w .j a v a 2s . 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
/** * Updates the reflog with the received commands. * * @param user/* w w w .j a v a 2 s .co m*/ * @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; }
From source file:com.gitblit.utils.RefLogUtils.java
License:Apache License
/** * Creates an in-memory index of the reflog entry. * * @param repo/*from www .j av a 2s.c om*/ * @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.EditFilePage.java
License:Apache License
public EditFilePage(final PageParameters params) { super(params); final UserModel currentUser = (GitBlitWebSession.get().getUser() != null) ? GitBlitWebSession.get().getUser() : UserModel.ANONYMOUS;/*from w w w . j a va 2 s.c o m*/ final String path = WicketUtils.getPath(params).replace("%2f", "/").replace("%2F", "/"); MarkupProcessor processor = new MarkupProcessor(app().settings(), app().xssFilter()); Repository r = getRepository(); RevCommit commit = JGitUtils.getCommit(r, objectId); String[] encodings = getEncodings(); // Read raw markup content and transform it to html String documentPath = path; String markupText = JGitUtils.getStringContent(r, commit.getTree(), path, encodings); // Hunt for document if (StringUtils.isEmpty(markupText)) { String name = StringUtils.stripFileExtension(path); List<String> docExtensions = processor.getAllExtensions(); for (String ext : docExtensions) { String checkName = name + "." + ext; markupText = JGitUtils.getStringContent(r, commit.getTree(), checkName, encodings); if (!StringUtils.isEmpty(markupText)) { // found it documentPath = path; break; } } } if (markupText == null) { markupText = ""; } BugtraqProcessor bugtraq = new BugtraqProcessor(app().settings()); markupText = bugtraq.processText(getRepository(), repositoryName, markupText); Fragment fragment; String displayedCommitId = commit.getId().getName(); if (currentUser.canEdit(getRepositoryModel()) && JGitUtils.isTip(getRepository(), objectId.toString())) { final Model<String> documentContent = new Model<String>(markupText); final Model<String> commitMessage = new Model<String>("Document update"); final Model<String> commitIdAtLoad = new Model<String>(displayedCommitId); fragment = new Fragment("doc", "markupContent", EditFilePage.this); Form<Void> form = new Form<Void>("documentEditor") { private static final long serialVersionUID = 1L; @Override protected void onSubmit() { final Repository repository = getRepository(); final String document = documentContent.getObject(); final String message = commitMessage.getObject(); final String branchName = JGitUtils.getBranch(getRepository(), objectId).getName(); final String authorEmail = StringUtils.isEmpty(currentUser.emailAddress) ? (currentUser.username + "@gitblit") : currentUser.emailAddress; boolean success = false; try { ObjectId docAtLoad = getRepository().resolve(commitIdAtLoad.getObject()); logger.trace("Commiting Edit File page: " + commitIdAtLoad.getObject()); DirCache index = DirCache.newInCore(); DirCacheBuilder builder = index.builder(); byte[] bytes = document.getBytes(Constants.ENCODING); final DirCacheEntry fileUpdate = new DirCacheEntry(path); fileUpdate.setLength(bytes.length); fileUpdate.setLastModified(System.currentTimeMillis()); fileUpdate.setFileMode(FileMode.REGULAR_FILE); fileUpdate.setObjectId(repository.newObjectInserter() .insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes)); builder.add(fileUpdate); Set<String> ignorePaths = new HashSet<String>(); ignorePaths.add(path); for (DirCacheEntry entry : JGitUtils.getTreeEntries(repository, branchName, ignorePaths)) { builder.add(entry); } builder.finish(); final boolean forceCommit = false; success = JGitUtils.commitIndex(repository, branchName, index, docAtLoad, forceCommit, currentUser.getDisplayName(), authorEmail, message); } catch (IOException | ConcurrentRefUpdateException e) { e.printStackTrace(); } if (success == false) { getSession().error(MessageFormat.format(getString("gb.fileNotMergeable"), path)); return; } getSession().info(MessageFormat.format(getString("gb.fileCommitted"), path)); setResponsePage(EditFilePage.class, params); } }; final TextArea<String> docIO = new TextArea<String>("content", documentContent); docIO.setOutputMarkupId(false); form.add(new Label("commitAuthor", String.format("%s <%s>", currentUser.getDisplayName(), currentUser.emailAddress))); form.add(new TextArea<String>("commitMessage", commitMessage)); form.setOutputMarkupId(false); form.add(docIO); addBottomScriptInline( "attachDocumentEditor(document.querySelector('textarea#editor'), $('#commitDialog'));"); fragment.add(form); } else { MarkupDocument markupDoc = processor.parse(repositoryName, displayedCommitId, documentPath, markupText); final Model<String> documentContent = new Model<String>(markupDoc.html); fragment = new Fragment("doc", "plainContent", EditFilePage.this); fragment.add(new Label("content", documentContent).setEscapeModelStrings(false)); } // document page links fragment.add(new BookmarkablePageLink<Void>("blameLink", BlamePage.class, WicketUtils.newPathParameter(repositoryName, objectId, documentPath))); fragment.add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, documentPath))); String rawUrl = RawServlet.asLink(getContextUrl(), repositoryName, objectId, documentPath); fragment.add(new ExternalLink("rawLink", rawUrl)); add(fragment); }
From source file:com.gitblit.wicket.pages.NewRepositoryPage.java
License:Apache License
/** * Prepare the initial commit for the repository. * * @param repository/*from w w w . ja va 2s .c om*/ * @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.appraise.eclipse.core.client.git.GitNoteWriter.java
License:Open Source License
/** * Private ctor. Use the static factory methods. */// w ww .j a va 2 s . co m private GitNoteWriter(String reviewHash, final Repository repo, String ref, PersonIdent author) { this.ref = ref; this.repo = repo; this.author = author; revWalk = new RevWalk(repo); inserter = repo.newObjectInserter(); reader = repo.newObjectReader(); try { ObjectId reviewRefObjId = repo.resolve(reviewHash); this.reviewCommit = revWalk.parseCommit(reviewRefObjId); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to init note writer for commit " + reviewHash, e); throw new RuntimeException(e); } }
From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java
License:Apache License
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);/*from www.jav a 2 s . co m*/ 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(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(), admin.getIdent()); return noteId.getName(); } }
From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java
License:Apache License
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);//w w w .j ava 2s .c o m byte[] raw = c.toText().getBytes(UTF_8); ObjectId dataBlob = ins.insert(OBJ_BLOB, raw); noteMap.set(noteId, dataBlob); ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(), admin.getIdent()); return noteId.getName(); } }
From source file:com.google.gerrit.acceptance.rest.account.ExternalIdIT.java
License:Apache License
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);/*w ww . ja v a2 s.c om*/ ExternalIdsUpdate.commit(repo, rw, ins, rev, noteMap, "Add external ID", admin.getIdent(), admin.getIdent()); return noteId.getName(); } }