List of usage examples for org.eclipse.jgit.dircache DirCache getEntry
public DirCacheEntry getEntry(String path)
From source file:com.chungkwong.jgitgui.StageTreeItem.java
License:Open Source License
@Override public Node getContentPage() { Git git = (Git) getValue();//from w ww. j a v a 2s .c om GridPane page = new GridPane(); ListView<String> list = new ListView<String>(); GridPane.setHgrow(list, Priority.ALWAYS); GridPane.setVgrow(list, Priority.ALWAYS); list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); try { DirCache cache = ((Git) getValue()).getRepository().readDirCache(); for (int i = 0; i < cache.getEntryCount(); i++) list.getItems().add(cache.getEntry(i).getPathString()); } catch (Exception ex) { Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } Button remove = new Button( java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("REMOVE")); remove.setOnAction((e) -> { RmCommand command = git.rm().setCached(true); list.getSelectionModel().getSelectedItems().stream().forEach((path) -> { command.addFilepattern(path); }); list.getItems().removeAll(list.getSelectionModel().getSelectedItems()); try { command.call(); } catch (Exception ex) { Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } }); Button blame = new Button( java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME")); blame.setOnAction((e) -> { Stage dialog = new Stage(); dialog.setTitle(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME")); StringBuilder buf = new StringBuilder(); list.getSelectionModel().getSelectedItems().stream().forEach((path) -> { try { BlameResult command = git.blame().setFilePath(path).call(); RawText contents = command.getResultContents(); for (int i = 0; i < contents.size(); i++) { buf.append(command.getSourcePath(i)).append(':'); buf.append(command.getSourceLine(i)).append(':'); buf.append(command.getSourceCommit(i)).append(':'); buf.append(command.getSourceAuthor(i)).append(':'); buf.append(contents.getString(i)).append('\n'); } } catch (Exception ex) { Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex); Util.informUser(ex); } }); dialog.setScene(new Scene(new TextArea(buf.toString()))); dialog.setMaximized(true); dialog.show(); }); page.addColumn(0, list, remove, blame); return page; }
From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryDaoImpl.java
License:Open Source License
@Override public Index getIndex(String token) { try {//from w w w. ja v a 2 s .c o m DirCache index = resolver.getRepository(token).readDirCache(); int numEntries = index.getEntryCount(); List<IndexEntry> entries = new ArrayList<>(numEntries); for (int i = 0; i < numEntries; i++) { DirCacheEntry dce = index.getEntry(i); ByteArrayOutputStream baos = new ByteArrayOutputStream(); dce.getFileMode().copyTo(baos); entries.add(new IndexEntry(dce.getObjectId().getName(), dce.getPathString(), baos.toString(), dce.getStage())); } return new Index(entries.toArray(new IndexEntry[numEntries])); } catch (NoWorkTreeException e) { String message = new StringBuilder().append("The repository ").append(token) .append(" is bare and so doesn't have index.").toString(); LOG.error(message, e); throw new DaoException(message, e); } catch (CorruptObjectException e) { String message = new StringBuilder().append("Filed to get index of the repository ").append(token) .append(" due to an internal error.").toString(); LOG.error(message, e); throw new DaoException(message, e); } catch (IOException e) { String message = new StringBuilder().append("Filed to get index of the repository ").append(token) .append(" due to an I/O error.").toString(); LOG.error(message, e); throw new DaoException(message, e); } }
From source file:com.google.gerrit.server.git.SubmoduleOp.java
License:Apache License
/** * Update the submodules in one branch of one repository. * * @param subscriber the branch of the repository which should be changed. * @param updates submodule updates which should be updated to. * @throws SubmoduleException//from www .j a v a2s . c o m */ private void updateGitlinks(ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates) throws SubmoduleException { PersonIdent author = null; StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n"); boolean sameAuthorForAll = true; try (Repository pdb = repoManager.openRepository(subscriber.getParentKey())) { if (pdb.getRef(subscriber.get()) == null) { throw new SubmoduleException("The branch was probably deleted from the subscriber repository"); } DirCache dc = readTree(pdb, pdb.getRef(subscriber.get())); DirCacheEditor ed = dc.editor(); for (SubmoduleSubscription s : updates) { try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey()); RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) { Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get()); if (ref == null) { ed.add(new DeletePath(s.getPath())); continue; } final ObjectId updateTo = ref.getObjectId(); RevCommit newCommit = rw.parseCommit(updateTo); if (author == null) { author = newCommit.getAuthorIdent(); } else if (!author.equals(newCommit.getAuthorIdent())) { sameAuthorForAll = false; } DirCacheEntry dce = dc.getEntry(s.getPath()); ObjectId oldId; if (dce != null) { if (!dce.getFileMode().equals(FileMode.GITLINK)) { log.error("Requested to update gitlink " + s.getPath() + " in " + s.getSubmodule().getParentKey().get() + " but entry " + "doesn't have gitlink file mode."); continue; } oldId = dce.getObjectId(); } else { // This submodule did not exist before. We do not want to add // the full submodule history to the commit message, so omit it. oldId = updateTo; } ed.add(new PathEdit(s.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(updateTo); } }); if (verboseSuperProject) { msgbuf.append("Project: " + s.getSubmodule().getParentKey().get()); msgbuf.append(" " + s.getSubmodule().getShortName()); msgbuf.append(" " + updateTo.getName()); msgbuf.append("\n\n"); try { rw.markStart(newCommit); rw.markUninteresting(rw.parseCommit(oldId)); for (RevCommit c : rw) { msgbuf.append(c.getFullMessage() + "\n\n"); } } catch (IOException e) { logAndThrowSubmoduleException( "Could not perform a revwalk to " + "create superproject commit message", e); } } } } ed.finish(); if (!sameAuthorForAll || author == null) { author = myIdent; } ObjectInserter oi = pdb.newObjectInserter(); ObjectId tree = dc.writeTree(oi); ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId(); CommitBuilder commit = new CommitBuilder(); commit.setTreeId(tree); commit.setParentIds(new ObjectId[] { currentCommitId }); commit.setAuthor(author); commit.setCommitter(myIdent); commit.setMessage(msgbuf.toString()); oi.insert(commit); oi.flush(); ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build()); final RefUpdate rfu = pdb.updateRef(subscriber.get()); rfu.setForceUpdate(false); rfu.setNewObjectId(commitId); rfu.setExpectedOldObjectId(currentCommitId); rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true); switch (rfu.update()) { case NEW: case FAST_FORWARD: gitRefUpdated.fire(subscriber.getParentKey(), rfu); changeHooks.doRefUpdatedHook(subscriber, rfu, account); // TODO since this is performed "in the background" no mail will be // sent to inform users about the updated branch break; default: throw new IOException(rfu.getResult().name()); } // Recursive call: update subscribers of the subscriber updateSuperProjects(db, Sets.newHashSet(subscriber)); } catch (IOException e) { throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), e); } }
From source file:com.google.gerrit.server.patch.AutoMerger.java
License:Apache License
/** * Perform an auto-merge of the parents of the given merge commit. * * @return auto-merge commit or {@code null} if an auto-merge commit * couldn't be created. Headers of the returned RevCommit are parsed. *///from w w w . j ava2s . c o m public RevCommit merge(Repository repo, RevWalk rw, final ObjectInserter ins, RevCommit merge, ThreeWayMergeStrategy mergeStrategy) throws IOException { rw.parseHeaders(merge); String hash = merge.name(); String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2); Ref ref = repo.getRefDatabase().exactRef(refName); if (ref != null && ref.getObjectId() != null) { RevObject obj = rw.parseAny(ref.getObjectId()); if (obj instanceof RevCommit) { return (RevCommit) obj; } return commit(repo, rw, ins, refName, obj, merge); } ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true); DirCache dc = DirCache.newInCore(); m.setDirCache(dc); m.setObjectInserter(new ObjectInserter.Filter() { @Override protected ObjectInserter delegate() { return ins; } @Override public void flush() { } @Override public void close() { } }); boolean couldMerge; try { couldMerge = m.merge(merge.getParents()); } catch (IOException e) { // It is not safe to continue further down in this method as throwing // an exception most likely means that the merge tree was not created // and m.getMergeResults() is empty. This would mean that all paths are // unmerged and Gerrit UI would show all paths in the patch list. log.warn("Error attempting automerge " + refName, e); return null; } ObjectId treeId; if (couldMerge) { treeId = m.getResultTreeId(); } else { RevCommit ours = merge.getParent(0); RevCommit theirs = merge.getParent(1); rw.parseBody(ours); rw.parseBody(theirs); String oursMsg = ours.getShortMessage(); String theirsMsg = theirs.getShortMessage(); String oursName = String.format("HEAD (%s %s)", ours.abbreviate(6).name(), oursMsg.substring(0, Math.min(oursMsg.length(), 60))); String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(), theirsMsg.substring(0, Math.min(theirsMsg.length(), 60))); MergeFormatter fmt = new MergeFormatter(); Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults(); Map<String, ObjectId> resolved = new HashMap<>(); for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) { MergeResult<? extends Sequence> p = entry.getValue(); try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) { fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name()); buf.close(); try (InputStream in = buf.openInputStream()) { resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in)); } } } DirCacheBuilder builder = dc.builder(); int cnt = dc.getEntryCount(); for (int i = 0; i < cnt;) { DirCacheEntry entry = dc.getEntry(i); if (entry.getStage() == 0) { builder.add(entry); i++; continue; } int next = dc.nextEntry(i); String path = entry.getPathString(); DirCacheEntry res = new DirCacheEntry(path); if (resolved.containsKey(path)) { // For a file with content merge conflict that we produced a result // above on, collapse the file down to a single stage 0 with just // the blob content, and a randomly selected mode (the lowest stage, // which should be the merge base, or ours). res.setFileMode(entry.getFileMode()); res.setObjectId(resolved.get(path)); } else if (next == i + 1) { // If there is exactly one stage present, shouldn't be a conflict... res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else if (next == i + 2) { // Two stages suggests a delete/modify conflict. Pick the higher // stage as the automatic result. entry = dc.getEntry(i + 1); res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else { // 3 stage conflict, no resolve above // Punt on the 3-stage conflict and show the base, for now. res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } builder.add(res); i = next; } builder.finish(); treeId = dc.writeTree(ins); } ins.flush(); return commit(repo, rw, ins, refName, treeId, merge); }
From source file:com.google.gerrit.server.patch.PatchListLoader.java
License:Apache License
public static RevTree automerge(Repository repo, RevWalk rw, RevCommit b, ThreeWayMergeStrategy mergeStrategy, boolean save) throws IOException { String hash = b.name();/*www . j a v a 2 s . com*/ String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2); Ref ref = repo.getRefDatabase().exactRef(refName); if (ref != null && ref.getObjectId() != null) { return rw.parseTree(ref.getObjectId()); } ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true); try (ObjectInserter ins = repo.newObjectInserter()) { DirCache dc = DirCache.newInCore(); m.setDirCache(dc); m.setObjectInserter(new ObjectInserter.Filter() { @Override protected ObjectInserter delegate() { return ins; } @Override public void flush() { } @Override public void close() { } }); boolean couldMerge; try { couldMerge = m.merge(b.getParents()); } catch (IOException e) { // It is not safe to continue further down in this method as throwing // an exception most likely means that the merge tree was not created // and m.getMergeResults() is empty. This would mean that all paths are // unmerged and Gerrit UI would show all paths in the patch list. log.warn("Error attempting automerge " + refName, e); return null; } ObjectId treeId; if (couldMerge) { treeId = m.getResultTreeId(); } else { RevCommit ours = b.getParent(0); RevCommit theirs = b.getParent(1); rw.parseBody(ours); rw.parseBody(theirs); String oursMsg = ours.getShortMessage(); String theirsMsg = theirs.getShortMessage(); String oursName = String.format("HEAD (%s %s)", ours.abbreviate(6).name(), oursMsg.substring(0, Math.min(oursMsg.length(), 60))); String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(), theirsMsg.substring(0, Math.min(theirsMsg.length(), 60))); MergeFormatter fmt = new MergeFormatter(); Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults(); Map<String, ObjectId> resolved = new HashMap<>(); for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) { MergeResult<? extends Sequence> p = entry.getValue(); try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) { fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8"); buf.close(); try (InputStream in = buf.openInputStream()) { resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in)); } } } DirCacheBuilder builder = dc.builder(); int cnt = dc.getEntryCount(); for (int i = 0; i < cnt;) { DirCacheEntry entry = dc.getEntry(i); if (entry.getStage() == 0) { builder.add(entry); i++; continue; } int next = dc.nextEntry(i); String path = entry.getPathString(); DirCacheEntry res = new DirCacheEntry(path); if (resolved.containsKey(path)) { // For a file with content merge conflict that we produced a result // above on, collapse the file down to a single stage 0 with just // the blob content, and a randomly selected mode (the lowest stage, // which should be the merge base, or ours). res.setFileMode(entry.getFileMode()); res.setObjectId(resolved.get(path)); } else if (next == i + 1) { // If there is exactly one stage present, shouldn't be a conflict... res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else if (next == i + 2) { // Two stages suggests a delete/modify conflict. Pick the higher // stage as the automatic result. entry = dc.getEntry(i + 1); res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else { // 3 stage conflict, no resolve above // Punt on the 3-stage conflict and show the base, for now. res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } builder.add(res); i = next; } builder.finish(); treeId = dc.writeTree(ins); } ins.flush(); if (save) { RefUpdate update = repo.updateRef(refName); update.setNewObjectId(treeId); update.disableRefLog(); update.forceUpdate(); } return rw.lookupTree(treeId); } }
From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java
License:Eclipse Distribution License
/** * Reverts the worktree after an unsuccessful merge. We know that for all * modified files the old content was in the old index and the index * contained only stage 0. In case if inCore operation just clear the * history of modified files./* w w w. j a v a 2 s . c o m*/ * * @throws IOException * @throws CorruptObjectException * @throws NoWorkTreeException * @since 3.4 */ @Override protected void cleanUp() throws NoWorkTreeException, CorruptObjectException, IOException { if (this.inCore) { this.modifiedFiles.clear(); return; } DirCache dc = this.db.readDirCache(); Iterator<String> mpathsIt = this.modifiedFiles.iterator(); while (mpathsIt.hasNext()) { String mpath = mpathsIt.next(); DirCacheEntry entry = dc.getEntry(mpath); if (entry != null) { DirCacheCheckout.checkoutEntry(this.db, entry, this.reader); } mpathsIt.remove(); } }
From source file:edu.nju.cs.inform.jgit.unfinished.ListIndex.java
License:Apache License
public static void main(String[] args) throws IOException { try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { // DirCache contains all files of the repository DirCache index = DirCache.read(repository); System.out.println("DirCache has " + index.getEntryCount() + " items"); for (int i = 0; i < index.getEntryCount(); i++) { // the number after the AnyObjectId is the "stage", see the constants in DirCacheEntry System.out.println("Item " + i + ": " + index.getEntry(i)); }//from w w w . j av a2 s .c o m // System.out.println("Now printing staged items..."); for (int i = 0; i < index.getEntryCount(); i++) { DirCacheEntry entry = index.getEntry(i); if (entry.getStage() != DirCacheEntry.STAGE_0) { System.out.println("Item " + i + ": " + entry); } } } }
From source file:ezbake.deployer.publishers.openShift.RhcApplication.java
License:Apache License
public void addStreamAsFile(File p, InputStream ios, Set<PosixFilePermission> filePermissions) throws DeploymentException { File resolvedPath = Files.resolve(getGitRepoPath(), p); if (Files.isDirectory(resolvedPath)) { throw new DeploymentException( "Directory exist by the name of file wishing to write to: " + resolvedPath.toString()); }// w w w. j a v a 2s . c om try { Files.createDirectories(resolvedPath.getParent()); OutputStream oos = new FileOutputStream(resolvedPath); boolean permissions = (filePermissions != null && !filePermissions.isEmpty()); DirCache cache = null; try { IOUtils.copy(ios, oos); if (permissions) { Files.setPosixFilePermissions(resolvedPath, filePermissions); } cache = gitRepo.add().addFilepattern(p.toString()).call(); if (permissions) { // Add executable permissions cache.lock(); // Most of these mthods throw an IOException so we will catch that and unlock DirCacheEntry entry = cache.getEntry(0); log.debug("Setting executable permissions for: " + entry.getPathString()); entry.setFileMode(FileMode.EXECUTABLE_FILE); cache.write(); cache.commit(); } } catch (IOException e) { log.error("[" + getApplicationName() + "]" + "Error writing to file: " + resolvedPath.toString(), e); // Most of the DirCache entries should just thow IOExceptions if (cache != null) { cache.unlock(); } throw new DeploymentException("Error writing to file: " + resolvedPath.toString()); } catch (GitAPIException e) { log.error("[" + getApplicationName() + "]" + "Error writing to file: " + resolvedPath.toString(), e); throw new DeploymentException("Error writing to file: " + resolvedPath.toString()); } finally { IOUtils.closeQuietly(oos); } } catch (IOException e) { log.error( "[" + getApplicationName() + "]" + "Error opening file for output: " + resolvedPath.toString(), e); throw new DeploymentException("Error opening file for output: " + resolvedPath.toString()); } }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
License:Apache License
protected void pushChanges(final File target) { try {/*from w w w . j av a2 s . co m*/ // // Grab our working repository // Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath(); final Git git = Git.open(repoPath.toFile()); // // Get our status // final String base; Status status; if (target == null) { base = "."; } else { Path relativePath = repoPath.relativize(Paths.get(target.getPath())); base = relativePath.toString(); } if (logger.isDebugEnabled()) { logger.debug("Status on base: " + base); } status = git.status().addPath(base).call(); // // Check if its clean // if (status.isClean()) { // // Its clean // AdminNotification.warn(target.getName() + " is clean!"); return; } // // Create the window // final GitPushWindow window = new GitPushWindow(git, target, status); window.setCaption("Push Changes"); window.setModal(true); window.addCloseListener(new CloseListener() { private static final long serialVersionUID = 1L; @Override public void windowClose(CloseEvent e) { if (window.isSaved() == false) { return; } try { // // Needs to be added first // DirCache cache = git.add().addFilepattern(base).call(); for (int i = 0; i < cache.getEntryCount(); i++) { DirCacheEntry entry = cache.getEntry(i); if (logger.isDebugEnabled()) { logger.debug("Entry: " + entry); } } // // Next they need to be committed // RevCommit rev = git.commit().setMessage(window.getComment()).call(); if (logger.isDebugEnabled()) { logger.debug("RevCommit: " + rev); } // // Now we can push changes to the Git repository // Iterable<PushResult> results = git.push().call(); for (PushResult result : results) { logger.info(result); } // // Have the container fire an item set change notification // self.treeContainer.updateItem(target); } catch (NoWorkTreeException | GitAPIException e1) { logger.error(e); AdminNotification.error("Exception occurred while trying to push: " + e1); } } }); window.center(); UI.getCurrent().addWindow(window); } catch (IOException | GitAPIException e) { logger.error(e); AdminNotification.error("Exception occurred while trying to get status: " + e); } }
From source file:org.apache.openaz.xacml.admin.view.windows.GitPushWindow.java
License:Apache License
protected Object generateUntrackedEntry(final GitEntry entry) { Button add = new Button("Add"); add.setImmediate(true);/*from w w w. j a v a 2s. c o m*/ add.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { try { DirCache cache = self.git.add().addFilepattern(entry.getName()).call(); DirCacheEntry cacheEntry = cache.getEntry(entry.getName()); assert cacheEntry != null; if (cacheEntry == null) { return; } if (cacheEntry.isMerged()) { self.refreshStatus(); } } catch (GitAPIException e) { String error = "Failed to add: " + e.getLocalizedMessage(); logger.error(error); AdminNotification.error(error); } } }); return add; }