Example usage for org.eclipse.jgit.lib Constants HEAD

List of usage examples for org.eclipse.jgit.lib Constants HEAD

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants HEAD.

Prototype

String HEAD

To view the source code for org.eclipse.jgit.lib Constants HEAD.

Click Source Link

Document

Special name for the "HEAD" symbolic-ref.

Usage

From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java

License:Apache License

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>//from  w  w w .jav a2 s.co m
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        ScmVersion version, boolean recursive) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol())
            && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }

    Git git = null;
    try {

        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());

        String branch = version != null ? version.getName() : null;

        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }

        getLogger().debug("try checkout of branch: " + branch);

        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }

            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();

            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }

        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);

        if (git == null) {
            git = Git.open(fileSet.getBasedir());
        }

        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists()
                && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);

            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }

        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true)
                    .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }

        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        getLogger().debug("current branch: " + git.getRepository().getBranch());

        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.JGitUtils.java

License:Apache License

/**
 * Get a list of commits between two revisions.
 *
 * @param repo     the repository to work on
 * @param sortings sorting//from   ww w.j  av a 2 s. co  m
 * @param fromRev  start revision
 * @param toRev    if null, falls back to head
 * @param fromDate from which date on
 * @param toDate   until which date
 * @param maxLines max number of lines
 * @return a list of commits, might be empty, but never <code>null</code>
 * @throws IOException
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 */
public static List<RevCommit> getRevCommits(Repository repo, RevSort[] sortings, String fromRev, String toRev,
        final Date fromDate, final Date toDate, int maxLines)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {

    List<RevCommit> revs = new ArrayList<RevCommit>();
    RevWalk walk = new RevWalk(repo);

    ObjectId fromRevId = fromRev != null ? repo.resolve(fromRev) : null;
    ObjectId toRevId = toRev != null ? repo.resolve(toRev) : null;

    if (sortings == null || sortings.length == 0) {
        sortings = new RevSort[] { RevSort.TOPO, RevSort.COMMIT_TIME_DESC };
    }

    for (final RevSort s : sortings) {
        walk.sort(s, true);
    }

    if (fromDate != null && toDate != null) {
        //walk.setRevFilter( CommitTimeRevFilter.between( fromDate, toDate ) );
        walk.setRevFilter(new RevFilter() {
            @Override
            public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException,
                    MissingObjectException, IncorrectObjectTypeException, IOException {
                int cmtTime = cmit.getCommitTime();

                return (cmtTime >= (fromDate.getTime() / 1000)) && (cmtTime <= (toDate.getTime() / 1000));
            }

            @Override
            public RevFilter clone() {
                return this;
            }
        });
    } else {
        if (fromDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.after(fromDate));
        }
        if (toDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.before(toDate));
        }
    }

    if (fromRevId != null) {
        RevCommit c = walk.parseCommit(fromRevId);
        c.add(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markUninteresting(real);
    }

    if (toRevId != null) {
        RevCommit c = walk.parseCommit(toRevId);
        c.remove(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markStart(real);
    } else {
        final ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null) {
            throw new RuntimeException("Cannot resolve " + Constants.HEAD);
        }
        RevCommit real = walk.parseCommit(head);
        walk.markStart(real);
    }

    int n = 0;
    for (final RevCommit c : walk) {
        n++;
        if (maxLines != -1 && n > maxLines) {
            break;
        }

        revs.add(c);
    }
    return revs;
}

From source file:org.apache.zeppelin.notebook.repo.GitNotebookRepo.java

License:Apache License

/**
 * the idea is to:/*  www  .j  av a2  s. c  o  m*/
 * 1. stash current changes
 * 2. remember head commit and checkout to the desired revision
 * 3. get note and checkout back to the head
 * 4. apply stash on top and remove it
 */
@Override
public synchronized Note get(String noteId, String notePath, String revId, AuthenticationInfo subject)
        throws IOException {
    Note note = null;
    RevCommit stash = null;
    String noteFileName = buildNoteFileName(noteId, notePath);
    try {
        List<DiffEntry> gitDiff = git.diff().setPathFilter(PathFilter.create(noteFileName)).call();
        boolean modified = !gitDiff.isEmpty();
        if (modified) {
            // stash changes
            stash = git.stashCreate().call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOGGER.debug("Created stash : {}, stash size : {}", stash, stashes.size());
        }
        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        // checkout to target revision
        git.checkout().setStartPoint(revId).addPath(noteFileName).call();
        // get the note
        note = super.get(noteId, notePath, subject);
        // checkout back to head
        git.checkout().setStartPoint(head.getName()).addPath(noteFileName).call();
        if (modified && stash != null) {
            // unstash changes
            ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
            ObjectId dropped = git.stashDrop().setStashRef(0).call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOGGER.debug("Stash applied as : {}, and dropped : {}, stash size: {}", applied, dropped,
                    stashes.size());
        }
    } catch (GitAPIException e) {
        LOGGER.error("Failed to return note from revision \"{}\"", revId, e);
    }
    return note;
}

From source file:org.apache.zeppelin.notebook.repo.OldGitNotebookRepo.java

License:Apache License

/**
 * the idea is to:/*  ww  w .  ja  va2  s .co m*/
 * 1. stash current changes
 * 2. remember head commit and checkout to the desired revision
 * 3. get note and checkout back to the head
 * 4. apply stash on top and remove it
 */
@Override
public synchronized Note get(String noteId, String revId, AuthenticationInfo subject) throws IOException {
    Note note = null;
    RevCommit stash = null;
    try {
        List<DiffEntry> gitDiff = git.diff().setPathFilter(PathFilter.create(noteId)).call();
        boolean modified = !gitDiff.isEmpty();
        if (modified) {
            // stash changes
            stash = git.stashCreate().call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOG.debug("Created stash : {}, stash size : {}", stash, stashes.size());
        }
        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        // checkout to target revision
        git.checkout().setStartPoint(revId).addPath(noteId).call();
        // get the note
        note = super.get(noteId, subject);
        // checkout back to head
        git.checkout().setStartPoint(head.getName()).addPath(noteId).call();
        if (modified && stash != null) {
            // unstash changes
            ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
            ObjectId dropped = git.stashDrop().setStashRef(0).call();
            Collection<RevCommit> stashes = git.stashList().call();
            LOG.debug("Stash applied as : {}, and dropped : {}, stash size: {}", applied, dropped,
                    stashes.size());
        }
    } catch (GitAPIException e) {
        LOG.error("Failed to return note from revision \"{}\"", revId, e);
    }
    return note;
}

From source file:org.archicontribs.modelrepository.dialogs.ConflictsDialog.java

License:Open Source License

private void createTableControl(Composite parent) {
    Composite tableComp = new Composite(parent, SWT.BORDER);
    TableColumnLayout tableLayout = new TableColumnLayout();
    tableComp.setLayout(tableLayout);//  w  ww  .  j av  a  2  s  .c o m
    tableComp.setLayoutData(new GridData(GridData.FILL_BOTH));

    Table table = new Table(tableComp, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
    table.setHeaderVisible(true);
    fTableViewer = new CheckboxTableViewer(table);
    fTableViewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
    fTableViewer.getTable().setLinesVisible(true);
    fTableViewer.setComparator(new ViewerComparator());

    // Columns
    TableViewerColumn column1 = new TableViewerColumn(fTableViewer, SWT.NONE, 0);
    column1.getColumn().setText(Messages.ConflictsDialog_5);
    tableLayout.setColumnData(column1.getColumn(), new ColumnWeightData(100, true));

    // Content Provider
    fTableViewer.setContentProvider(new IStructuredContentProvider() {
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

        public void dispose() {
        }

        public Object[] getElements(Object inputElement) {
            MergeResult result = fHandler.getMergeResult();
            return result.getConflicts().keySet().toArray();
        }
    });

    fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            String path = (String) ((StructuredSelection) event.getSelection()).getFirstElement();

            try {
                fFileViewerOurs.setText(
                        GraficoUtils.getFileContents(fHandler.getLocalGitFolder(), path, Constants.HEAD));
                fFileViewerTheirs.setText(
                        GraficoUtils.getFileContents(fHandler.getLocalGitFolder(), path, "origin/master")); //$NON-NLS-1$
                fFileViewerDiff
                        .setText(GraficoUtils.getWorkingTreeFileContents(fHandler.getLocalGitFolder(), path));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    // Label Provider
    fTableViewer.setLabelProvider(new LabelProvider());

    // Start the table
    fTableViewer.setInput(""); // anything will do //$NON-NLS-1$
}

From source file:org.chodavarapu.jgitaws.jgit.AmazonRepository.java

License:Eclipse Distribution License

@Override
public void create(boolean bare) throws IOException {
    if (exists())
        throw new IOException(MessageFormat.format(JGitText.get().repositoryAlreadyExists, ""));

    String master = Constants.R_HEADS + Constants.MASTER;
    RefUpdate.Result result = updateRef(Constants.HEAD, true).link(master);
    if (result != RefUpdate.Result.NEW)
        throw new IOException(result.name());
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

@Override
public String getDiff() throws Exception {
    final ObjectId head = repo.resolve(Constants.HEAD + "^{tree}");

    if (head == null) {
        LOGGER.warning("Unable to resolve the HEAD of this git tree");
        throw new NoHeadException(JGitText.get().cannotReadTree);
    }//  w  w  w  .  jav a 2  s. com
    final CanonicalTreeParser p = new CanonicalTreeParser();
    final ObjectReader reader = repo.newObjectReader();

    try {
        p.reset(reader, head);
    } finally {
        reader.release();
    }
    final AbstractTreeIterator oldTree = p;
    final AbstractTreeIterator newTree = new DirCacheIterator(repo.readDirCache());
    final OutputStream out = new ByteArrayOutputStream();
    final ChangeOnlyDiffFormatter diffFmt = new ChangeOnlyDiffFormatter(new BufferedOutputStream(out));

    diffFmt.setRepository(repo);
    diffFmt.setPathFilter(TreeFilter.ALL);
    diffFmt.setProgressMonitor(NullProgressMonitor.INSTANCE);

    LOGGER.finer("Scanning the git tree for diffs");
    final List<DiffEntry> result = diffFmt.scan(oldTree, newTree);

    diffFmt.format(result);
    diffFmt.flush();
    diffFmt.release();

    return out.toString();
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

private boolean verifyChangesExist(final Collection<String> paths) throws GitSubsystemException {
    try {/*from w  w w. j  ava2  s .  c  om*/
        final DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setRepository(repo);

        // resolve the HEAD object
        final ObjectId oid = repo.resolve(Constants.HEAD);
        if (oid == null) {
            // if there's no head, then these must be real changes...
            return true;
        }

        // reset a new tree object to the HEAD
        final RevWalk walk = new RevWalk(repo);
        final RevCommit commit = walk.parseCommit(oid);
        final RevTree treeWalk = walk.parseTree(commit);

        // construct filters for the paths we're trying to add/commit
        final List<TreeFilter> filters = new ArrayList<>();
        for (final String path : paths) {
            filters.add(PathFilter.create(path));
        }

        // we're interested in trees with an actual diff. This should improve walk performance.
        filters.add(TreeFilter.ANY_DIFF);

        // set the path filters from above
        walk.setTreeFilter(AndTreeFilter.create(filters));

        // setup the tree for doing the comparison vs. uncommitted files
        final CanonicalTreeParser tree = new CanonicalTreeParser();
        final ObjectReader oldReader = repo.newObjectReader();
        try {
            tree.reset(oldReader, treeWalk.getId());
        } finally {
            oldReader.release();
        }
        walk.dispose();

        // this iterator will actually scan the uncommitted files for diff'ing
        final FileTreeIterator files = new FileTreeIterator(repo);

        // do the scan.
        final List<DiffEntry> entries = formatter.scan(tree, files);

        // we're not interested in WHAT the differences are, only that there are differences.
        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());
    }
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

public List<ChangeSummary> getChangelog(final File f, final int start, final int length)
        throws GitSubsystemException {
    if (length == 0) {
        return Collections.emptyList();
    }//ww  w.j  a v  a2 s .  c om

    try {
        final ObjectId oid = repo.resolve(Constants.HEAD);

        final PlotWalk pw = new PlotWalk(repo);
        final RevCommit rc = pw.parseCommit(oid);
        toChangeSummary(rc);
        pw.markStart(rc);

        final String filepath = relativize(f);
        logger.info("Getting changelog for: {} (start: {}, length: {})", filepath, start, length);

        if (!isEmpty(filepath) && !filepath.equals("/")) {
            pw.setTreeFilter(AndTreeFilter.create(PathFilter.create(filepath), TreeFilter.ANY_DIFF));
        } else {
            pw.setTreeFilter(TreeFilter.ANY_DIFF);
        }

        final List<ChangeSummary> changelogs = new ArrayList<ChangeSummary>();
        int count = 0;
        final int stop = length > 0 ? length + 1 : 0;
        RevCommit commit = null;
        while ((commit = pw.next()) != null && (stop < 1 || count < stop)) {
            if (count < start) {
                count++;
                continue;
            }

            //                printFiles( commit );
            changelogs.add(toChangeSummary(commit));
            count++;
        }

        if (length < -1) {
            final int remove = (-1 * length) - 1;
            for (int i = 0; i < remove; i++) {
                changelogs.remove(changelogs.size() - 1);
            }
        }

        return changelogs;
    } catch (RevisionSyntaxException | IOException e) {
        throw new GitSubsystemException("Failed to resolve HEAD commit for: %s. Reason: %s", e, f,
                e.getMessage());
    }
}

From source file:org.commonjava.gitwrap.BareGitRepository.java

License:Open Source License

protected final void doClone(final String remoteUrl, final String remoteName, final String branch)
        throws GitWrapException {
    final FileRepository repository = getRepository();

    final String branchRef = Constants.R_HEADS + (branch == null ? Constants.MASTER : branch);

    try {/*  w  w w.ja v  a 2 s .  c  om*/
        final RefUpdate head = repository.updateRef(Constants.HEAD);
        head.disableRefLog();
        head.link(branchRef);

        final RemoteConfig remoteConfig = new RemoteConfig(repository.getConfig(), remoteName);
        remoteConfig.addURI(new URIish(remoteUrl));

        final String remoteRef = Constants.R_REMOTES + remoteName;

        RefSpec spec = new RefSpec();
        spec = spec.setForceUpdate(true);
        spec = spec.setSourceDestination(Constants.R_HEADS + "*", remoteRef + "/*");

        remoteConfig.addFetchRefSpec(spec);

        remoteConfig.update(repository.getConfig());

        repository.getConfig().setString("branch", branch, "remote", remoteName);
        repository.getConfig().setString("branch", branch, "merge", branchRef);

        repository.getConfig().save();

        fetch(remoteName);
        postClone(remoteUrl, branchRef);
    } catch (final IOException e) {
        throw new GitWrapException("Failed to clone from: %s. Reason: %s", e, remoteUrl, e.getMessage());
    } catch (final URISyntaxException e) {
        throw new GitWrapException("Failed to clone from: %s. Reason: %s", e, remoteUrl, e.getMessage());
    }
}