use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitblit by gitblit.
the class RefLogUtils method createIndex.
/**
* Creates an in-memory index of the reflog entry.
*
* @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(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;
}
use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitblit by gitblit.
the class BranchTicketService method deleteTicketImpl.
/**
* Deletes a ticket from the repository.
*
* @param ticket
* @return true if successful
*/
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) {
if (ticket == null) {
throw new RuntimeException("must specify a ticket!");
}
boolean success = false;
Repository db = repositoryManager.getRepository(ticket.repository);
try {
RefModel ticketsBranch = getTicketsBranch(db);
if (ticketsBranch == null) {
throw new RuntimeException(BRANCH + " does not exist!");
}
String ticketPath = toTicketPath(ticket.number);
TreeWalk treeWalk = null;
try {
ObjectId treeId = db.resolve(BRANCH + "^{tree}");
// Create the in-memory index of the new/updated ticket
DirCache index = DirCache.newInCore();
DirCacheBuilder builder = index.builder();
// Traverse HEAD to add all other paths
treeWalk = new TreeWalk(db);
int hIdx = -1;
if (treeId != null) {
hIdx = treeWalk.addTree(treeId);
}
treeWalk.setRecursive(true);
while (treeWalk.next()) {
String path = treeWalk.getPathString();
CanonicalTreeParser hTree = null;
if (hIdx != -1) {
hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
}
if (!path.startsWith(ticketPath)) {
// add entries from HEAD for all other paths
if (hTree != null) {
final DirCacheEntry entry = new DirCacheEntry(path);
entry.setObjectId(hTree.getEntryObjectId());
entry.setFileMode(hTree.getEntryFileMode());
// add to temporary in-core index
builder.add(entry);
}
}
}
// finish temporary in-core index used for this commit
builder.finish();
success = commitIndex(db, index, deletedBy, "- " + ticket.number);
} catch (Throwable t) {
log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number, db.getDirectory()), t);
} finally {
// release the treewalk
if (treeWalk != null) {
treeWalk.close();
}
}
} finally {
db.close();
}
return success;
}
use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitiles by GerritCodeReview.
the class PathServlet method showTree.
private void showTree(HttpServletRequest req, HttpServletResponse res, WalkResult wr) throws IOException {
GitilesView view = ViewFilter.getView(req);
Config cfg = getAccess(req).getConfig();
List<String> autodive = view.getParameters().get(AUTODIVE_PARAM);
if (autodive.size() != 1 || !NO_AUTODIVE_VALUE.equals(autodive.get(0))) {
byte[] path = Constants.encode(view.getPathPart());
ObjectReader reader = wr.getObjectReader();
CanonicalTreeParser child = getOnlyChildSubtree(reader, wr.id, path);
if (child != null) {
while (true) {
path = new byte[child.getEntryPathLength()];
System.arraycopy(child.getEntryPathBuffer(), 0, path, 0, child.getEntryPathLength());
CanonicalTreeParser next = getOnlyChildSubtree(reader, child.getEntryObjectId(), path);
if (next == null) {
break;
}
child = next;
}
res.sendRedirect(GitilesView.path().copyFrom(view).setPathPart(RawParseUtils.decode(child.getEntryPathBuffer(), 0, child.getEntryPathLength())).toUrl());
return;
}
}
// TODO(sop): Allow caching trees by SHA-1 when no S cookie is sent.
renderHtml(req, res, "gitiles.pathDetail", ImmutableMap.of("title", !view.getPathPart().isEmpty() ? view.getPathPart() : "/", "breadcrumbs", view.getBreadcrumbs(wr.hasSingleTree), "type", FileType.TREE.toString(), "data", new TreeSoyData(wr.getObjectReader(), view, cfg, wr.root, req.getRequestURI()).setArchiveFormat(getArchiveFormat(getAccess(req))).toSoyData(wr.id, wr.tw)));
}
use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project indy by Commonjava.
the class GitManager method verifyChangesExist.
private boolean verifyChangesExist(final Collection<String> paths) throws GitSubsystemException {
return lockAnd(me -> {
try {
final DiffFormatter formatter = new DiffFormatter(System.out);
formatter.setRepository(repo);
final ObjectId oid = repo.resolve(Constants.HEAD);
if (oid == null) {
return true;
}
final RevWalk walk = new RevWalk(repo);
final RevCommit commit = walk.parseCommit(oid);
final RevTree treeWalk = walk.parseTree(commit);
final List<TreeFilter> filters = new ArrayList<>();
for (final String path : paths) {
filters.add(PathFilter.create(path));
}
filters.add(TreeFilter.ANY_DIFF);
walk.setTreeFilter(AndTreeFilter.create(filters));
final CanonicalTreeParser tree = new CanonicalTreeParser();
final ObjectReader oldReader = repo.newObjectReader();
try {
tree.reset(oldReader, treeWalk.getId());
} finally {
oldReader.release();
}
walk.dispose();
final FileTreeIterator files = new FileTreeIterator(repo);
final List<DiffEntry> entries = formatter.scan(tree, files);
return entries != null && !entries.isEmpty();
} catch (final IOException e) {
throw new GitSubsystemException("Failed to scan for actual changes among: %s. Reason: %s", e, paths, e.getMessage());
}
});
}
use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project searchcode-server by boyter.
the class IndexGitRepoJob method updateGitRepository.
/**
* Update a git repository and return if it has changed and the differences
*/
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
boolean changed = false;
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
Repository localRepository = null;
Git git = null;
try {
localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));
Ref head = localRepository.getRef("HEAD");
git = new Git(localRepository);
git.reset();
git.clean();
PullCommand pullCmd = git.pull();
if (useCredentials) {
pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
}
pullCmd.call();
Ref newHEAD = localRepository.getRef("HEAD");
if (!head.toString().equals(newHEAD.toString())) {
changed = true;
// Get the differences between the the heads which we updated at
// and use these to just update the differences between them
ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
ObjectReader reader = localRepository.newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
oldTreeIter.reset(reader, oldHead);
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset(reader, newHead);
List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
for (DiffEntry entry : entries) {
if ("DELETE".equals(entry.getChangeType().name())) {
deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
} else {
changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
}
}
}
} catch (IOException | GitAPIException | InvalidPathException ex) {
changed = false;
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
} finally {
Singleton.getHelpers().closeQuietly(localRepository);
Singleton.getHelpers().closeQuietly(git);
}
return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Aggregations