List of usage examples for org.eclipse.jgit.lib Repository newObjectReader
@NonNull
public ObjectReader newObjectReader()
From source file:com.google.gerrit.server.git.VersionedMetaData.java
License:Apache License
/** * Load a specific version from the repository. * <p>//w w w .ja va 2s .c om * This method is primarily useful for applying updates to a specific revision * that was shown to an end-user in the user interface. If there are conflicts * with another user's concurrent changes, these will be automatically * detected at commit time. * <p> * The repository is not held after the call completes, allowing the * application to retain this object for long periods of time. * * @param db repository to access. * @param id revision to load. * @throws IOException * @throws ConfigInvalidException */ public void load(Repository db, ObjectId id) throws IOException, ConfigInvalidException { reader = db.newObjectReader(); try { revision = id != null ? new RevWalk(reader).parseCommit(id) : null; onLoad(); } finally { reader.close(); reader = null; } }
From source file:com.google.gerrit.server.git.VersionedMetaData.java
License:Apache License
/** * Open a batch of updates to the same metadata ref. * <p>//from ww w . ja v a2s. co m * This allows making multiple commits to a single metadata ref, at the end of * which is a single ref update. For batching together updates to multiple * refs (each consisting of one or more commits against their respective * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}. * <p> * A ref update produced by this {@link BatchMetaDataUpdate} is only committed * if there is no associated {@link BatchRefUpdate}. As a result, the * configured ref updated event is not fired if there is an associated batch. * * @param update helper info about the update. * @throws IOException if the update failed. */ public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException { final Repository db = update.getRepository(); reader = db.newObjectReader(); inserter = db.newObjectInserter(); final RevWalk rw = new RevWalk(reader); final RevTree tree = revision != null ? rw.parseTree(revision) : null; newTree = readTree(tree); return new BatchMetaDataUpdate() { AnyObjectId src = revision; AnyObjectId srcTree = tree; @Override public void write(CommitBuilder commit) throws IOException { write(VersionedMetaData.this, commit); } private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException { DirCache nt = config.newTree; ObjectReader r = config.reader; ObjectInserter i = config.inserter; try { config.newTree = newTree; config.reader = reader; config.inserter = inserter; return config.onSave(commit); } catch (ConfigInvalidException e) { throw new IOException( "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(), e); } finally { config.newTree = nt; config.reader = r; config.inserter = i; } } @Override public void write(VersionedMetaData config, CommitBuilder commit) throws IOException { if (!doSave(config, commit)) { return; } // Reuse tree from parent commit unless there are contents in newTree or // there is no tree for a parent commit. ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter) : srcTree.copy(); if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) { // If there are no changes to the content, don't create the commit. return; } // If changes are made to the DirCache and those changes are written as // a commit and then the tree ID is set for the CommitBuilder, then // those previous DirCache changes will be ignored and the commit's // tree will be replaced with the ID in the CommitBuilder. The same is // true if you explicitly set tree ID in a commit and then make changes // to the DirCache; that tree ID will be ignored and replaced by that of // the tree for the updated DirCache. if (commit.getTreeId() == null) { commit.setTreeId(res); } else { // In this case, the caller populated the tree without using DirCache. res = commit.getTreeId(); } if (src != null) { commit.addParentId(src); } if (update.insertChangeId()) { ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(), commit.getCommitter(), commit.getMessage()); commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id)); } src = inserter.insert(commit); srcTree = res; } @Override public RevCommit createRef(String refName) throws IOException { if (Objects.equals(src, revision)) { return revision; } return updateRef(ObjectId.zeroId(), src, refName); } @Override public void removeRef(String refName) throws IOException { RefUpdate ru = db.updateRef(refName); ru.setForceUpdate(true); if (revision != null) { ru.setExpectedOldObjectId(revision); } RefUpdate.Result result = ru.delete(); switch (result) { case FORCED: update.fireGitRefUpdatedEvent(ru); return; default: throw new IOException( "Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } @Override public RevCommit commit() throws IOException { return commitAt(revision); } @Override public RevCommit commitAt(ObjectId expected) throws IOException { if (Objects.equals(src, expected)) { return revision; } return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName()); } @Override public void close() { newTree = null; rw.close(); if (inserter != null) { inserter.close(); inserter = null; } if (reader != null) { reader.close(); reader = null; } } private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException { BatchRefUpdate bru = update.getBatch(); if (bru != null) { bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName)); inserter.flush(); revision = rw.parseCommit(newId); return revision; } RefUpdate ru = db.updateRef(refName); ru.setExpectedOldObjectId(oldId); ru.setNewObjectId(src); ru.setRefLogIdent(update.getCommitBuilder().getAuthor()); String message = update.getCommitBuilder().getMessage(); if (message == null) { message = "meta data update"; } try (BufferedReader reader = new BufferedReader(new StringReader(message))) { // read the subject line and use it as reflog message ru.setRefLogMessage("commit: " + reader.readLine(), true); } inserter.flush(); RefUpdate.Result result = ru.update(); switch (result) { case NEW: case FAST_FORWARD: revision = rw.parseCommit(ru.getNewObjectId()); update.fireGitRefUpdatedEvent(ru); return revision; default: throw new IOException( "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } }; }
From source file:com.google.gerrit.server.patch.PatchFile.java
License:Apache License
public PatchFile(final Repository repo, final PatchList patchList, final String fileName) throws MissingObjectException, IncorrectObjectTypeException, IOException { this.repo = repo; this.entry = patchList.get(fileName); try (ObjectReader reader = repo.newObjectReader(); RevWalk rw = new RevWalk(reader)) { final RevCommit bCommit = rw.parseCommit(patchList.getNewId()); if (Patch.COMMIT_MSG.equals(fileName)) { if (patchList.isAgainstParent()) { a = Text.EMPTY;/*from w w w .ja v a 2 s. c o m*/ } else { a = Text.forCommit(reader, patchList.getOldId()); } b = Text.forCommit(reader, bCommit); aTree = null; bTree = null; } else { if (patchList.getOldId() != null) { aTree = rw.parseTree(patchList.getOldId()); } else { final RevCommit p = bCommit.getParent(0); rw.parseHeaders(p); aTree = p.getTree(); } bTree = bCommit.getTree(); } } }
From source file:com.google.gerrit.server.patch.PatchListLoader.java
License:Apache License
private PatchList readPatchList(final PatchListKey key, final Repository repo) throws IOException, PatchListNotAvailableException { final RawTextComparator cmp = comparatorFor(key.getWhitespace()); try (ObjectReader reader = repo.newObjectReader(); RevWalk rw = new RevWalk(reader); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) { final RevCommit b = rw.parseCommit(key.getNewId()); final RevObject a = aFor(key, repo, rw, b); if (a == null) { // TODO(sop) Remove this case. // This is a merge commit, compared to its ancestor. ///* w w w.j av a 2s.c o m*/ final PatchListEntry[] entries = new PatchListEntry[1]; entries[0] = newCommitMessage(cmp, reader, null, b); return new PatchList(a, b, true, entries); } final boolean againstParent = b.getParentCount() > 0 && b.getParent(0) == a; RevCommit aCommit = a instanceof RevCommit ? (RevCommit) a : null; RevTree aTree = rw.parseTree(a); RevTree bTree = b.getTree(); df.setRepository(repo); df.setDiffComparator(cmp); df.setDetectRenames(true); List<DiffEntry> diffEntries = df.scan(aTree, bTree); Set<String> paths = null; if (key.getOldId() != null) { PatchListKey newKey = new PatchListKey(null, key.getNewId(), key.getWhitespace()); PatchListKey oldKey = new PatchListKey(null, key.getOldId(), key.getWhitespace()); paths = FluentIterable.from(patchListCache.get(newKey, project).getPatches()) .append(patchListCache.get(oldKey, project).getPatches()) .transform(new Function<PatchListEntry, String>() { @Override public String apply(PatchListEntry entry) { return entry.getNewName(); } }).toSet(); } int cnt = diffEntries.size(); List<PatchListEntry> entries = new ArrayList<>(); entries.add(newCommitMessage(cmp, reader, againstParent ? null : aCommit, b)); for (int i = 0; i < cnt; i++) { DiffEntry diffEntry = diffEntries.get(i); if (paths == null || paths.contains(diffEntry.getNewPath()) || paths.contains(diffEntry.getOldPath())) { FileHeader fh = toFileHeader(key, df, diffEntry); entries.add(newEntry(aTree, fh)); } } return new PatchList(a, b, againstParent, entries.toArray(new PatchListEntry[entries.size()])); } }
From source file:com.google.gerrit.server.StarredChangesUtil.java
License:Apache License
private static TreeSet<String> readLabels(Repository repo, ObjectId id) throws IOException { if (ObjectId.zeroId().equals(id)) { return new TreeSet<>(); }//from www . j ava 2s . com try (ObjectReader reader = repo.newObjectReader()) { ObjectLoader obj = reader.open(id, Constants.OBJ_BLOB); TreeSet<String> labels = new TreeSet<>(); Iterables.addAll(labels, Splitter.on(CharMatcher.whitespace()).omitEmptyStrings() .split(new String(obj.getCachedBytes(Integer.MAX_VALUE), UTF_8))); return labels; } }
From source file:com.googlesource.gerrit.plugins.supermanifest.Utils.java
License:Apache License
public static byte[] readBlob(Repository repo, String idStr) throws IOException { try (ObjectReader reader = repo.newObjectReader()) { ObjectId id = repo.resolve(idStr); if (id == null) { throw new RevisionSyntaxException(String.format("repo %s does not have %s", repo.toString(), idStr), idStr);/* w w w.j a v a 2s.c om*/ } return reader.open(id).getCachedBytes(Integer.MAX_VALUE); } }
From source file:com.googlesource.gerrit.plugins.xdocs.XDocLoader.java
License:Apache License
private static String getAbbrRevId(Repository repo, ObjectId revId) throws IOException { try (ObjectReader reader = repo.newObjectReader()) { return reader.abbreviate(revId).name(); }//from www . j ava 2s . c om }
From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java
License:Apache License
private AbstractTreeIterator prepareTreeParser(Repository repository, Ref ref) throws IOException { // from the commit we can build the tree which allows us to construct the TreeParser try (RevWalk walk = new RevWalk(repository)) { RevCommit commit = walk.parseCommit(ref.getObjectId()); RevTree tree = walk.parseTree(commit.getTree().getId()); CanonicalTreeParser treeParser = new CanonicalTreeParser(); try (ObjectReader reader = repository.newObjectReader()) { treeParser.reset(reader, tree.getId()); }/*from w w w . j a v a 2s .c o m*/ walk.dispose(); return treeParser; } }
From source file:com.microsoft.gittf.client.clc.commands.CheckinCommand.java
License:Open Source License
private AbbreviatedObjectId[] getSquashCommitIDs() throws Exception { Repository repository = getRepository(); ObjectReader objReader = null;//from w w w.j a v a 2 s . co m RevWalk revWalk = null; try { objReader = repository.newObjectReader(); revWalk = new RevWalk(repository); Argument[] squashPrefixArgs = getArguments().getArguments("squash"); //$NON-NLS-1$ if (squashPrefixArgs == null || squashPrefixArgs.length == 0) { return null; } AbbreviatedObjectId[] squashCommitIDs = new AbbreviatedObjectId[squashPrefixArgs.length]; for (int i = 0; i < squashPrefixArgs.length; i++) { squashCommitIDs[i] = AbbreviatedObjectId .fromString(((ValueArgument) squashPrefixArgs[i]).getValue()); Collection<ObjectId> candidateObjects = null; try { candidateObjects = objReader.resolve(squashCommitIDs[i]); } catch (Exception e) { /* * commit id could not be resolved by git */ } if (candidateObjects == null || candidateObjects.size() == 0) { throw new Exception(Messages.formatString("CheckinCommand.CommitIdAmbiguousFormat", //$NON-NLS-1$ squashCommitIDs[i].name())); } else if (candidateObjects.size() > 1) { throw new Exception(Messages.formatString("CheckinCommand.CommitIdAmbiguousFormat", //$NON-NLS-1$ squashCommitIDs[i].name())); } else { RevCommit revCommit = revWalk.parseCommit(candidateObjects.toArray(new ObjectId[1])[0]); if (revCommit == null) { throw new Exception(Messages.formatString("CheckinCommand.CommitIdDoesNotExistFormat", //$NON-NLS-1$ squashCommitIDs[i].name())); } } } return squashCommitIDs; } finally { if (objReader != null) { objReader.release(); } if (revWalk != null) { revWalk.release(); } } }
From source file:com.pramati.gerrit.plugin.helpers.GetFileFromRepo.java
License:Apache License
/** * returns the File Stream from the gerrit repository. returns "null" if the * given file not found in the repository.<br> * patchStr should like in given format::"changeid/patchsetID/filename" <br> * eg: 1/2/readme.md//from w w w . jav a 2 s .com * * @param patchStr * @return * @throws IOException */ public static BufferedInputStream doGetFile(String patchStr) throws IOException { final Patch.Key patchKey; final Change.Id changeId; final Project project; final PatchSet patchSet; final Repository repo; final ReviewDb db; final ChangeControl control; try { patchKey = Patch.Key.parse(patchStr); } catch (NumberFormatException e) { return null; } changeId = patchKey.getParentKey().getParentKey(); try { db = requestDb.get(); control = changeControl.validateFor(changeId); project = control.getProject(); patchSet = db.patchSets().get(patchKey.getParentKey()); if (patchSet == null) { return null; // rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (NoSuchChangeException e) { // rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (OrmException e) { // getServletContext().log("Cannot query database", e); // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { // getServletContext().log("Cannot open repository", e); // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } final ObjectLoader blobLoader; final RevCommit fromCommit; final String path = patchKey.getFileName(); try { final ObjectReader reader = repo.newObjectReader(); try { final RevWalk rw = new RevWalk(reader); final RevCommit c; final TreeWalk tw; c = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); fromCommit = c; tw = TreeWalk.forPath(reader, path, fromCommit.getTree()); if (tw == null) { // rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) { blobLoader = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB); } else { // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } finally { reader.release(); } } catch (IOException e) { // getServletContext().log("Cannot read repository", e); // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } catch (RuntimeException e) { // getServletContext().log("Cannot read repository", e); // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } finally { repo.close(); } ByteArrayOutputStream out = new ByteArrayOutputStream(); blobLoader.copyTo(out); byte[] b = out.toByteArray(); BufferedInputStream br = new BufferedInputStream(new ByteArrayInputStream(b)); return br; }