List of usage examples for org.eclipse.jgit.dircache DirCache getEntryCount
public int getEntryCount()
From source file:com.chungkwong.jgitgui.StageTreeItem.java
License:Open Source License
@Override public Node getContentPage() { Git git = (Git) getValue();/*from w w w . j av a 2 s . 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.gitblit.wicket.pages.NewRepositoryPage.java
License:Apache License
/** * Prepare the initial commit for the repository. * * @param repository//w ww.ja v a 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.github.kaitoy.goslings.server.dao.jgit.RepositoryDaoImpl.java
License:Open Source License
@Override public Index getIndex(String token) { try {//from w w w. j av a 2 s. com 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.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 ww. ja v a 2 s . 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();//from w ww .j a v a 2 s . co m 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: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 a v a 2 s .c om // 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:io.fabric8.vertx.maven.plugin.it.ExtraManifestInfoIT.java
License:Apache License
@Test public void testGITSCM() throws IOException, VerificationException, GitAPIException { File testDir = initProject(GIT_PROJECT_ROOT); assertThat(testDir).isDirectory();/* w w w . ja v a 2 s.co m*/ initVerifier(testDir); prepareProject(testDir, verifier); File gitFolder = GitUtil.findGitFolder(testDir); assertThat(testDir).isNotNull(); assertThat(testDir.getName()).endsWith("manifest-git-it"); assertThat(gitFolder).isNull(); Git git = prepareGitSCM(testDir, verifier); gitFolder = git.getRepository().getDirectory(); assertThat(gitFolder.getParentFile().getName()).isEqualTo(testDir.getName()); assertThat(git.status().call().getUntracked()).contains("pom.xml", "src/main/java/demo/SimpleVerticle.java"); //Now add and commit the file DirCache index = git.add().addFilepattern(".").call(); assertThat(index.getEntryCount()).isEqualTo(2); git.commit().setMessage("First Import").call(); runPackage(verifier); assertManifest(testDir, "git"); }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
License:Apache License
protected void pushChanges(final File target) { try {//from w ww . jav a 2 s. com // // 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.zeppelin.notebook.repo.GitNotebookRepo.java
License:Apache License
@Override public Revision checkpoint(String noteId, String notePath, String commitMessage, AuthenticationInfo subject) throws IOException { String noteFileName = buildNoteFileName(noteId, notePath); Revision revision = Revision.EMPTY;/*from w w w . j a v a 2 s .c o m*/ try { List<DiffEntry> gitDiff = git.diff().call(); boolean modified = gitDiff.parallelStream() .anyMatch(diffEntry -> diffEntry.getNewPath().equals(noteFileName)); if (modified) { LOGGER.debug("Changes found for pattern '{}': {}", noteFileName, gitDiff); DirCache added = git.add().addFilepattern(noteFileName).call(); LOGGER.debug("{} changes are about to be commited", added.getEntryCount()); RevCommit commit = git.commit().setMessage(commitMessage).call(); revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime()); } else { LOGGER.debug("No changes found {}", noteFileName); } } catch (GitAPIException e) { LOGGER.error("Failed to add+commit {} to Git", noteFileName, e); } return revision; }
From source file:org.apache.zeppelin.notebook.repo.OldGitNotebookRepo.java
License:Apache License
@Override public Revision checkpoint(String pattern, String commitMessage, AuthenticationInfo subject) { Revision revision = Revision.EMPTY;/*from w w w. j a va 2s . co m*/ try { List<DiffEntry> gitDiff = git.diff().call(); if (!gitDiff.isEmpty()) { LOG.debug("Changes found for pattern '{}': {}", pattern, gitDiff); DirCache added = git.add().addFilepattern(pattern).call(); LOG.debug("{} changes are about to be commited", added.getEntryCount()); RevCommit commit = git.commit().setMessage(commitMessage).call(); revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime()); } else { LOG.debug("No changes found {}", pattern); } } catch (GitAPIException e) { LOG.error("Failed to add+commit {} to Git", pattern, e); } return revision; }