Search in sources :

Example 1 with DirCacheEntry

use of org.eclipse.jgit.dircache.DirCacheEntry in project gitblit by gitblit.

the class JGitUtils method getTreeEntries.

/**
	 * Returns all tree entries that do not match the ignore paths.
	 *
	 * @param db
	 * @param ignorePaths
	 * @param dcBuilder
	 * @throws IOException
	 */
public static List<DirCacheEntry> getTreeEntries(Repository db, String branch, Collection<String> ignorePaths) throws IOException {
    List<DirCacheEntry> list = new ArrayList<DirCacheEntry>();
    TreeWalk tw = null;
    try {
        ObjectId treeId = db.resolve(branch + "^{tree}");
        if (treeId == null) {
            // branch does not exist yet
            return list;
        }
        tw = new TreeWalk(db);
        int hIdx = tw.addTree(treeId);
        tw.setRecursive(true);
        while (tw.next()) {
            String path = tw.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1) {
                hTree = tw.getTree(hIdx, CanonicalTreeParser.class);
            }
            if (!ignorePaths.contains(path)) {
                // add all other tree entries
                if (hTree != null) {
                    final DirCacheEntry entry = new DirCacheEntry(path);
                    entry.setObjectId(hTree.getEntryObjectId());
                    entry.setFileMode(hTree.getEntryFileMode());
                    list.add(entry);
                }
            }
        }
    } finally {
        if (tw != null) {
            tw.close();
        }
    }
    return list;
}
Also used : DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser)

Example 2 with DirCacheEntry

use of org.eclipse.jgit.dircache.DirCacheEntry in project gitblit by gitblit.

the class BranchTicketService method createIndex.

/**
	 * Creates an in-memory index of the ticket change.
	 *
	 * @param changeId
	 * @param change
	 * @return an in-memory index
	 * @throws IOException
	 */
private DirCache createIndex(Repository db, long ticketId, Change change) throws IOException, ClassNotFoundException, NoSuchFieldException {
    String ticketPath = toTicketPath(ticketId);
    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // create/update the journal
        // exclude the attachment content
        List<Change> changes = getJournal(db, ticketId);
        changes.add(change);
        String journal = TicketSerializer.serializeJournal(changes).trim();
        byte[] journalBytes = journal.getBytes(Constants.ENCODING);
        String journalPath = ticketPath + "/" + JOURNAL;
        final DirCacheEntry journalEntry = new DirCacheEntry(journalPath);
        journalEntry.setLength(journalBytes.length);
        journalEntry.setLastModified(change.date.getTime());
        journalEntry.setFileMode(FileMode.REGULAR_FILE);
        journalEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, journalBytes));
        // add journal to index
        builder.add(journalEntry);
        ignorePaths.add(journalEntry.getPathString());
        // Add any attachments to the index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = toAttachmentPath(ticketId, attachment.name);
                ignorePaths.add(path);
                // create an index entry for this attachment
                final DirCacheEntry entry = new DirCacheEntry(path);
                entry.setLength(attachment.content.length);
                entry.setLastModified(change.date.getTime());
                entry.setFileMode(FileMode.REGULAR_FILE);
                // insert object
                entry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, attachment.content));
                // add to temporary in-core index
                builder.add(entry);
            }
        }
        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }
        // finish the index
        builder.finish();
    } finally {
        inserter.close();
    }
    return newIndex;
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) TreeSet(java.util.TreeSet) Attachment(com.gitblit.models.TicketModel.Attachment) Change(com.gitblit.models.TicketModel.Change)

Example 3 with DirCacheEntry

use of org.eclipse.jgit.dircache.DirCacheEntry in project gitblit by gitblit.

the class NewRepositoryPage method initialCommit.

/**
	 * Prepare the initial commit for the repository.
	 *
	 * @param repository
	 * @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;
}
Also used : DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Result(org.eclipse.jgit.lib.RefUpdate.Result) UserModel(com.gitblit.models.UserModel) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 4 with DirCacheEntry

use of org.eclipse.jgit.dircache.DirCacheEntry in project gerrit by GerritCodeReview.

the class SubmoduleOp method updateSubmodule.

private RevCommit updateSubmodule(DirCache dc, DirCacheEditor ed, StringBuilder msgbuf, final SubmoduleSubscription s) throws SubmoduleException, IOException {
    OpenRepo subOr;
    try {
        subOr = orm.getRepo(s.getSubmodule().getParentKey());
    } catch (NoSuchProjectException | IOException e) {
        throw new SubmoduleException("Cannot access submodule", e);
    }
    DirCacheEntry dce = dc.getEntry(s.getPath());
    RevCommit oldCommit = null;
    if (dce != null) {
        if (!dce.getFileMode().equals(FileMode.GITLINK)) {
            String errMsg = "Requested to update gitlink " + s.getPath() + " in " + s.getSubmodule().getParentKey().get() + " but entry " + "doesn't have gitlink file mode.";
            throw new SubmoduleException(errMsg);
        }
        oldCommit = subOr.rw.parseCommit(dce.getObjectId());
    }
    final CodeReviewCommit newCommit;
    if (branchTips.containsKey(s.getSubmodule())) {
        newCommit = branchTips.get(s.getSubmodule());
    } else {
        Ref ref = subOr.repo.getRefDatabase().exactRef(s.getSubmodule().get());
        if (ref == null) {
            ed.add(new DeletePath(s.getPath()));
            return null;
        }
        newCommit = subOr.rw.parseCommit(ref.getObjectId());
        addBranchTip(s.getSubmodule(), newCommit);
    }
    if (Objects.equals(newCommit, oldCommit)) {
        // gitlink have already been updated for this submodule
        return null;
    }
    ed.add(new PathEdit(s.getPath()) {

        @Override
        public void apply(DirCacheEntry ent) {
            ent.setFileMode(FileMode.GITLINK);
            ent.setObjectId(newCommit.getId());
        }
    });
    if (verboseSuperProject != VerboseSuperprojectUpdate.FALSE) {
        createSubmoduleCommitMsg(msgbuf, s, subOr, newCommit, oldCommit);
    }
    subOr.rw.parseBody(newCommit);
    return newCommit;
}
Also used : DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) PathEdit(org.eclipse.jgit.dircache.DirCacheEditor.PathEdit) IOException(java.io.IOException) DeletePath(org.eclipse.jgit.dircache.DirCacheEditor.DeletePath) Ref(org.eclipse.jgit.lib.Ref) OpenRepo(com.google.gerrit.server.git.MergeOpRepoManager.OpenRepo) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 5 with DirCacheEntry

use of org.eclipse.jgit.dircache.DirCacheEntry in project gerrit by GerritCodeReview.

the class VersionedMetaData method saveFile.

protected void saveFile(String fileName, byte[] raw) throws IOException {
    DirCacheEditor editor = newTree.editor();
    if (raw != null && 0 < raw.length) {
        final ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, raw);
        editor.add(new PathEdit(fileName) {

            @Override
            public void apply(DirCacheEntry ent) {
                ent.setFileMode(FileMode.REGULAR_FILE);
                ent.setObjectId(blobId);
            }
        });
    } else {
        editor.add(new DeletePath(fileName));
    }
    editor.finish();
}
Also used : DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) PathEdit(org.eclipse.jgit.dircache.DirCacheEditor.PathEdit) DirCacheEditor(org.eclipse.jgit.dircache.DirCacheEditor) DeletePath(org.eclipse.jgit.dircache.DirCacheEditor.DeletePath)

Aggregations

DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)13 DirCache (org.eclipse.jgit.dircache.DirCache)6 DirCacheBuilder (org.eclipse.jgit.dircache.DirCacheBuilder)6 ObjectId (org.eclipse.jgit.lib.ObjectId)6 PathEdit (org.eclipse.jgit.dircache.DirCacheEditor.PathEdit)5 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)5 IOException (java.io.IOException)4 RevCommit (org.eclipse.jgit.revwalk.RevCommit)4 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)3 Test (org.junit.Test)3 TreeSet (java.util.TreeSet)2 DeletePath (org.eclipse.jgit.dircache.DirCacheEditor.DeletePath)2 AnyObjectId (org.eclipse.jgit.lib.AnyObjectId)2 Ref (org.eclipse.jgit.lib.Ref)2 Repository (org.eclipse.jgit.lib.Repository)2 RevBlob (org.eclipse.jgit.revwalk.RevBlob)2 RevWalk (org.eclipse.jgit.revwalk.RevWalk)2 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)2 RefModel (com.gitblit.models.RefModel)1 Attachment (com.gitblit.models.TicketModel.Attachment)1