Example usage for org.eclipse.jgit.dircache DirCacheEntry setLength

List of usage examples for org.eclipse.jgit.dircache DirCacheEntry setLength

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCacheEntry setLength.

Prototype

public void setLength(long sz) 

Source Link

Document

Set the cached size (in bytes) of this file.

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@Override
public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {

    monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN);

    String repoFileURI = COMMENTS_FILE_URI;

    try {//from   w  w w .  j  a  v a 2s. c  o m
        Git git = Git.open(new File(uri));
        Repository repository = git.getRepository();
        ObjectInserter objectInserter = repository.newObjectInserter();

        String commentRefName = getCommentRefName(modelReview);
        Ref commentRef = repository.exactRef(commentRefName);

        DirCache index = DirCache.newInCore();
        DirCacheBuilder dirCacheBuilder = index.builder();

        monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN);

        if (commentRef != null) {

            /*
             * The ref already exists so we have to copy the previous
             * RevTree to keep all already attached files
             */

            RevWalk revWalk = new RevWalk(repository);
            RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId());
            RevTree tree = prevCommit.getTree();

            List<String> ignoredFiles = new ArrayList<>();
            /*
             * add file path of the new file to the ignored file paths, as
             * we don't want any already existing old file in our new tree
             */
            ignoredFiles.add(repoFileURI);
            buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles);

            revWalk.close();
        }

        monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI));

        addCommentsToResource(modelReview, resource);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        resource.save(outputStream, null);

        // insert file as object
        byte[] content = outputStream.toByteArray();
        long length = content.length;
        InputStream inputStream = new ByteArrayInputStream(content);
        ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream);
        inputStream.close();

        // create tree entry
        DirCacheEntry entry = new DirCacheEntry(repoFileURI);
        entry.setFileMode(FileMode.REGULAR_FILE);
        entry.setLastModified(System.currentTimeMillis());
        entry.setLength(length);
        entry.setObjectId(objectId);
        dirCacheBuilder.add(entry);

        dirCacheBuilder.finish();

        // write new tree in database
        ObjectId indexTreeId = index.writeTree(objectInserter);

        monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN);

        // create commit
        CommitBuilder commitBuilder = new CommitBuilder();
        PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview");
        commitBuilder.setCommitter(personIdent);
        commitBuilder.setAuthor(personIdent);
        commitBuilder.setMessage(
                MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName()));

        if (commentRef != null) {
            commitBuilder.setParentId(commentRef.getObjectId());
        }
        commitBuilder.setTreeId(indexTreeId);

        // commit
        ObjectId commitId = objectInserter.insert(commitBuilder);
        objectInserter.flush();

        RefUpdate refUpdate = repository.updateRef(commentRefName);
        refUpdate.setNewObjectId(commitId);
        if (commentRef != null)
            refUpdate.setExpectedOldObjectId(commentRef.getObjectId());
        else
            refUpdate.setExpectedOldObjectId(ObjectId.zeroId());

        /*
         * TODO the result handling below is copied from the CommitCommand
         * class, I don't know if this is really necessary in our case
         */
        Result result = refUpdate.forceUpdate();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD: {
            if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
                /*
                 * Commit was successful. Now delete the files used for
                 * merge commits
                 */
                repository.writeMergeCommitMsg(null);
                repository.writeMergeHeads(null);
            } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeCherryPickHead(null);
            } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeRevertHead(null);
            }
            break;
        }
        case REJECTED:
        case LOCK_FAILURE:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(),
                            refUpdate.getRef(), result));
        default:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            refUpdate.getRef().getName(), commitId.toString(), result)));
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } finally {
        monitor.done();
    }

}

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * //from   ww  w.j a v a 2 s .  com
 * @param repo
 * @param headId
 * @param sourceFolder
 * @param obliterate
 *            if true the source folder tree is used as the new tree for
 *            gh-pages and non-existent files are considered deleted
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, File sourceFolder, boolean obliterate)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    try {
        // Add all files to the temporary index
        Set<String> ignorePaths = new TreeSet<String>();
        List<File> files = listFiles(sourceFolder);
        for (File file : files) {
            // create an index entry for the file
            final DirCacheEntry dcEntry = new DirCacheEntry(
                    StringUtils.getRelativePath(sourceFolder.getPath(), file.getPath()));
            dcEntry.setLength(file.length());
            dcEntry.setLastModified(file.lastModified());
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // add this entry to the ignore paths set
            ignorePaths.add(dcEntry.getPathString());

            // insert object
            InputStream inputStream = new FileInputStream(file);
            try {
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, file.length(), inputStream));
            } finally {
                inputStream.close();
            }

            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }

        if (!obliterate) {
            // 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.release();
        }

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Writes a file to the tickets branch.//  w  ww.jav  a2s .  c o m
 *
 * @param db
 * @param file
 * @param content
 * @param createdBy
 * @param msg
 */
private void writeTicketsFile(Repository db, String file, String content, String createdBy, String msg) {
    if (getTicketsBranch(db) == null) {
        createTicketsBranch(db);
    }

    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();

    try {
        // create an index entry for the revised index
        final DirCacheEntry idIndexEntry = new DirCacheEntry(file);
        idIndexEntry.setLength(content.length());
        idIndexEntry.setLastModified(System.currentTimeMillis());
        idIndexEntry.setFileMode(FileMode.REGULAR_FILE);

        // insert new ticket index
        idIndexEntry.setObjectId(
                inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes(Constants.ENCODING)));

        // add to temporary in-core index
        builder.add(idIndexEntry);

        Set<String> ignorePaths = new HashSet<String>();
        ignorePaths.add(file);

        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }

        // finish temporary in-core index used for this commit
        builder.finish();

        // commit the change
        commitIndex(db, newIndex, createdBy, msg);

    } catch (ConcurrentRefUpdateException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    } finally {
        inserter.close();
    }
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Creates an in-memory index of the ticket change.
 *
 * @param changeId/*  w  w w. j a  v  a2 s  . c  o  m*/
 * @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;
}

From source file:com.gitblit.utils.IssueUtils.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * /*from  www  .j a  va2 s  .c  o  m*/
 * @param repo
 * @param headId
 * @param change
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, String issuePath, Change change)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // Add any attachments to the temporary index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = issuePath + "/" + attachment.id;
                ignorePaths.add(path);

                // create an index entry for this attachment
                final DirCacheEntry dcEntry = new DirCacheEntry(path);
                dcEntry.setLength(attachment.content.length);
                dcEntry.setLastModified(change.created.getTime());
                dcEntry.setFileMode(FileMode.REGULAR_FILE);

                // insert object
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, attachment.content));

                // 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.release();

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.gitblit.utils.PushLogUtils.java

License:Apache License

/**
 * Creates an in-memory index of the push log entry.
 * //from   w w w .  ja  va 2s. com
 * @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(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.release();

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.gitblit.utils.RefLogUtils.java

License:Apache License

/**
 * Creates an in-memory index of the reflog entry.
 *
 * @param repo/*  w  w w  .j  a  va 2 s . co  m*/
 * @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;
}

From source file:com.gitblit.wicket.pages.EditFilePage.java

License:Apache License

public EditFilePage(final PageParameters params) {
    super(params);

    final UserModel currentUser = (GitBlitWebSession.get().getUser() != null)
            ? GitBlitWebSession.get().getUser()
            : UserModel.ANONYMOUS;//from  ww w  .j  a v  a  2s . co m

    final String path = WicketUtils.getPath(params).replace("%2f", "/").replace("%2F", "/");
    MarkupProcessor processor = new MarkupProcessor(app().settings(), app().xssFilter());

    Repository r = getRepository();
    RevCommit commit = JGitUtils.getCommit(r, objectId);
    String[] encodings = getEncodings();

    // Read raw markup content and transform it to html
    String documentPath = path;
    String markupText = JGitUtils.getStringContent(r, commit.getTree(), path, encodings);

    // Hunt for document
    if (StringUtils.isEmpty(markupText)) {
        String name = StringUtils.stripFileExtension(path);

        List<String> docExtensions = processor.getAllExtensions();
        for (String ext : docExtensions) {
            String checkName = name + "." + ext;
            markupText = JGitUtils.getStringContent(r, commit.getTree(), checkName, encodings);
            if (!StringUtils.isEmpty(markupText)) {
                // found it
                documentPath = path;
                break;
            }
        }
    }

    if (markupText == null) {
        markupText = "";
    }

    BugtraqProcessor bugtraq = new BugtraqProcessor(app().settings());
    markupText = bugtraq.processText(getRepository(), repositoryName, markupText);

    Fragment fragment;
    String displayedCommitId = commit.getId().getName();

    if (currentUser.canEdit(getRepositoryModel()) && JGitUtils.isTip(getRepository(), objectId.toString())) {

        final Model<String> documentContent = new Model<String>(markupText);
        final Model<String> commitMessage = new Model<String>("Document update");
        final Model<String> commitIdAtLoad = new Model<String>(displayedCommitId);

        fragment = new Fragment("doc", "markupContent", EditFilePage.this);

        Form<Void> form = new Form<Void>("documentEditor") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit() {
                final Repository repository = getRepository();
                final String document = documentContent.getObject();
                final String message = commitMessage.getObject();

                final String branchName = JGitUtils.getBranch(getRepository(), objectId).getName();
                final String authorEmail = StringUtils.isEmpty(currentUser.emailAddress)
                        ? (currentUser.username + "@gitblit")
                        : currentUser.emailAddress;

                boolean success = false;

                try {
                    ObjectId docAtLoad = getRepository().resolve(commitIdAtLoad.getObject());

                    logger.trace("Commiting Edit File page: " + commitIdAtLoad.getObject());

                    DirCache index = DirCache.newInCore();
                    DirCacheBuilder builder = index.builder();
                    byte[] bytes = document.getBytes(Constants.ENCODING);

                    final DirCacheEntry fileUpdate = new DirCacheEntry(path);
                    fileUpdate.setLength(bytes.length);
                    fileUpdate.setLastModified(System.currentTimeMillis());
                    fileUpdate.setFileMode(FileMode.REGULAR_FILE);
                    fileUpdate.setObjectId(repository.newObjectInserter()
                            .insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
                    builder.add(fileUpdate);

                    Set<String> ignorePaths = new HashSet<String>();
                    ignorePaths.add(path);

                    for (DirCacheEntry entry : JGitUtils.getTreeEntries(repository, branchName, ignorePaths)) {
                        builder.add(entry);
                    }

                    builder.finish();

                    final boolean forceCommit = false;

                    success = JGitUtils.commitIndex(repository, branchName, index, docAtLoad, forceCommit,
                            currentUser.getDisplayName(), authorEmail, message);

                } catch (IOException | ConcurrentRefUpdateException e) {
                    e.printStackTrace();
                }

                if (success == false) {
                    getSession().error(MessageFormat.format(getString("gb.fileNotMergeable"), path));
                    return;
                }

                getSession().info(MessageFormat.format(getString("gb.fileCommitted"), path));
                setResponsePage(EditFilePage.class, params);
            }
        };

        final TextArea<String> docIO = new TextArea<String>("content", documentContent);
        docIO.setOutputMarkupId(false);

        form.add(new Label("commitAuthor",
                String.format("%s <%s>", currentUser.getDisplayName(), currentUser.emailAddress)));
        form.add(new TextArea<String>("commitMessage", commitMessage));

        form.setOutputMarkupId(false);
        form.add(docIO);

        addBottomScriptInline(
                "attachDocumentEditor(document.querySelector('textarea#editor'), $('#commitDialog'));");

        fragment.add(form);

    } else {

        MarkupDocument markupDoc = processor.parse(repositoryName, displayedCommitId, documentPath, markupText);
        final Model<String> documentContent = new Model<String>(markupDoc.html);

        fragment = new Fragment("doc", "plainContent", EditFilePage.this);

        fragment.add(new Label("content", documentContent).setEscapeModelStrings(false));
    }

    // document page links
    fragment.add(new BookmarkablePageLink<Void>("blameLink", BlamePage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, documentPath)));
    fragment.add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, documentPath)));
    String rawUrl = RawServlet.asLink(getContextUrl(), repositoryName, objectId, documentPath);
    fragment.add(new ExternalLink("rawLink", rawUrl));

    add(fragment);

}

From source file:com.gitblit.wicket.pages.NewRepositoryPage.java

License:Apache License

/**
 * Prepare the initial commit for the repository.
 *
 * @param repository/*w w w.ja v  a  2 s.  co  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.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

/**
 * adds a new path with the specified stage to the index builder
 *
 * @param path/*  w  w  w .ja va2 s  . c  o m*/
 * @param p
 * @param stage
 * @param lastMod
 * @param len
 * @return the entry which was added to the index
 */
private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage, long lastMod, long len) {
    if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
        DirCacheEntry e = new DirCacheEntry(path, stage);
        e.setFileMode(p.getEntryFileMode());
        e.setObjectId(p.getEntryObjectId());
        e.setLastModified(lastMod);
        e.setLength(len);
        this.builder.add(e);
        return e;
    }
    return null;
}