Example usage for org.eclipse.jgit.api Git Git

List of usage examples for org.eclipse.jgit.api Git Git

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git Git.

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:com.microsoft.gittf.core.tasks.pendDiff.CheckinAnalysisChangeCollectionTest.java

License:Open Source License

private RevCommit commit() throws NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException {
    Git git = new Git(repository);

    return git.commit().setAll(true).setMessage("commit").call(); //$NON-NLS-1$
}

From source file:com.microsoft.gittf.core.tasks.PullTask.java

License:Open Source License

private MergeCommand getMergeCommand() {
    if (mergeCommand == null) {
        mergeCommand = new Git(repository).merge();
    }

    return mergeCommand;
}

From source file:com.microsoft.gittf.core.tasks.PullTask.java

License:Open Source License

private RebaseCommand getRebaseCommand() {
    if (rebaseCommand == null) {
        rebaseCommand = new Git(repository).rebase();
    }

    return rebaseCommand;
}

From source file:com.microsoft.gittf.core.tasks.PullTaskTest.java

License:Open Source License

private void prepareRepo() throws Exception {
    URI projectCollectionURI = new URI("http://fakeCollection:8080/tfs/DefaultCollection"); //$NON-NLS-1$
    String tfsPath = "$/"; //$NON-NLS-1$
    String gitRepositoryPath = Util.getRepositoryFile(getName()).getAbsolutePath();

    mockVersionControlService = new MockVersionControlService();

    mockVersionControlService.AddFile("$/project/folder/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file0.txt", 1); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file0.txt", 1); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 2); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 2); //$NON-NLS-1$

    mockVersionControlService.AddFile("$/project/folder/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file2.txt", 3); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file2.txt", 3); //$NON-NLS-1$

    Calendar date = Calendar.getInstance();
    date.set(2012, 11, 12, 18, 15);/* www .java2 s.c o m*/

    MockChangesetProperties changesetProperties = new MockChangesetProperties("ownerDisplayName", //$NON-NLS-1$
            "ownerName", //$NON-NLS-1$
            "committerDisplayName", //$NON-NLS-1$
            "committerName", //$NON-NLS-1$
            "comment", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties, 3);

    repository = RepositoryUtil.createNewRepository(gitRepositoryPath, false);

    CloneTask cloneTask = new CloneTask(projectCollectionURI, mockVersionControlService, tfsPath, repository);
    TaskStatus cloneTaskStatus = cloneTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(cloneTaskStatus.isOK());

    // Update some files
    mockVersionControlService.AddFile("$/project/folder/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder2/file1.txt", 4); //$NON-NLS-1$
    mockVersionControlService.AddFile("$/project/folder/nestedFolder/file1.txt", 4); //$NON-NLS-1$

    MockChangesetProperties changesetProperties2 = new MockChangesetProperties("ownerDisplayName4", //$NON-NLS-1$
            "ownerName4", //$NON-NLS-1$
            "committerDisplayName4", //$NON-NLS-1$
            "committerName4", //$NON-NLS-1$
            "comment4", //$NON-NLS-1$
            date);
    mockVersionControlService.updateChangesetInformation(changesetProperties2, 4);

    writeFileContentInGit("project/folder/file2.txt"); //$NON-NLS-1$
    writeFileContentInGit("project/folder2/file2.txt"); //$NON-NLS-1$
    writeFileContentInGit("project/folder/nestedFolder/file2.txt"); //$NON-NLS-1$

    RevCommit revCommit = new Git(repository).commit().setAll(true).setMessage("git-tf pull test").call(); //$NON-NLS-1$
    assertNotNull(revCommit);

    gitChangeCommitId = revCommit.toObjectId();
}

From source file:com.microsoft.gittf.core.util.RepositoryUtil.java

License:Open Source License

/**
 * Determines if there are uncommitted changes in the working directory or
 * not./*from   w  ww.j  a  v a2s  . c om*/
 * 
 * @param repository
 * @return
 * @throws GitAPIException
 * @throws NoWorkTreeException
 */
public static boolean hasUncommittedChanges(Repository repository) throws NoWorkTreeException, GitAPIException {
    Status currentStatus = new Git(repository).status().call();

    if (!currentStatus.isClean()) {
        return true;
    }

    return false;
}

From source file:com.microsoft.gittf.core.util.TagUtil.java

License:Open Source License

/**
 * Creates a tag/*from   ww  w  .  j av a 2  s  . c  om*/
 * 
 * @param repository
 *        the git repository
 * @param commitID
 *        the commit id to tag
 * @param tagName
 *        the tag name
 * @param tagOwner
 *        the tag owner
 * @return
 */
public static boolean createTag(final Repository repository, ObjectId commitID, String tagName,
        PersonIdent tagOwner) {
    final RevWalk walker = new RevWalk(repository);
    try {
        /* Look up the object to tag */
        RevObject objectToTag = walker.lookupCommit(commitID);

        /* Create a tag command */
        TagCommand tagCommand = new Git(repository).tag();
        tagCommand.setName(tagName);
        tagCommand.setObjectId(objectToTag);
        tagCommand.setForceUpdate(true);
        tagCommand.setTagger(tagOwner);

        /* Call the tag command */
        Ref tagRef = tagCommand.call();

        if (tagRef == null || tagRef == ObjectId.zeroId()) {
            log.warn("Failed to tag commit."); //$NON-NLS-1$

            return false;
        }

        return true;
    } catch (Exception e) {
        // this is not a critical failure so we can still continue with the
        // operation even if tagging failed.

        log.error(e);

        return false;
    } finally {
        if (walker != null) {
            walker.release();
        }
    }
}

From source file:com.microsoft.gittf.core.util.TfsBranchUtil.java

License:Open Source License

/**
 * /*from w  w w  .  j  av  a 2s  .c o m*/
 * Creates a remote tracking ref for tfs. If the repo is bare a regular
 * branch is created too.
 * 
 * @param repository
 * @param startPoint
 * @throws RefAlreadyExistsException
 * @throws RefNotFoundException
 * @throws InvalidRefNameException
 * @throws GitAPIException
 * @throws IOException
 */
public static void create(Repository repository, String startPoint) throws RefAlreadyExistsException,
        RefNotFoundException, InvalidRefNameException, GitAPIException, IOException {
    if (repository.isBare()) {
        CreateBranchCommand createBranch = new Git(repository).branchCreate();
        createBranch.setName(GitTFConstants.GIT_TF_BRANCHNAME);
        createBranch.setForce(true);
        if (startPoint != null && startPoint.length() > 0) {
            createBranch.setStartPoint(startPoint);
        }
        createBranch.call();
    }

    TfsRemoteReferenceUpdate remoteRefUpdate = new TfsRemoteReferenceUpdate(repository, startPoint);
    remoteRefUpdate.update();
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

License:Open Source License

@Override
protected SelectionListener getCreateButtonSelectionListener(final Shell shell) {
    return new SelectionAdapter() {
        @Override// w w  w.j  a va2  s .co  m
        public void widgetSelected(final SelectionEvent e) {
            final CreateGitBuildConfigurationWizard wizard = new CreateGitBuildConfigurationWizard();
            updateAndVerifyBuildDefinition(true);

            wizard.init(buildDefinition);

            final WizardDialog dialog = new WizardDialog(getShell(), wizard);
            final int rc = dialog.open();

            if (rc == IDialogConstants.OK_ID) {
                localBuildProjectCreated = true;

                /*
                 * TFSBuild proj/resp files are created in a cloned
                 * repository, but they could be outside of projects
                 * imported into the Eclipse workspace.
                 */
                final List<IResource> resources = new ArrayList<IResource>();

                final LocationInfo buildProjectLocation = new LocationInfo(
                        new Path(getBuildProjectAbsolutePath()));
                if (buildProjectLocation.isPotentialSubProjectResource()) {
                    resources.add(buildProjectLocation.getSubProjectResource(false));
                }

                final LocationInfo buildResponceLocation = new LocationInfo(
                        new Path(getBuildResponseAbsolutePath()));
                if (buildResponceLocation.isPotentialSubProjectResource()) {
                    resources.add(buildResponceLocation.getSubProjectResource(false));
                }

                if (resources.size() > 0) {
                    final AddToIndexOperation op = new AddToIndexOperation(resources);
                    try {
                        op.execute(new NullProgressMonitor());
                    } catch (final CoreException ex) {
                        log.error("Error adding build files to index", ex); //$NON-NLS-1$
                    }

                } else {
                    final GitRepository repository = getBuildProjectRepository();
                    final Git git = new Git(repository.getLocalRepository());

                    final AddCommand addCommand = git.add();
                    addCommand.addFilepattern(getBuildProjectRelativePath());
                    addCommand.addFilepattern(getBuildResponseRelativePath());

                    try {
                        addCommand.call();
                    } catch (final Exception ex) {
                        log.error("Error adding build files to index", ex); //$NON-NLS-1$
                    }
                }

                checkForBuildFileExistence(true);
                validate();
            }
        }
    };
}

From source file:com.mpdeimos.ct_tests.vcs.GitFileDiffTest.java

License:Apache License

@Test
public void testAddedFiles() {

    try {/*  w  w w .  j  a  v  a 2  s .co m*/
        //         ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
        //         
        //         Repository repository = new FileRepository(gitDir);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setWorkTree(useTestFile("diff1")).build();
        ObjectId head = repository.resolve("new");
        //         TreeWalk treeWalk = TreeUtils.diffWithParents(repository, head);
        //         scan = DiffEntry.scan(treeWalk);
        //         treeWalk.release();

        CommitFinder finder = new CommitFinder(repository);
        GitCommitListFilter filter = new GitCommitListFilter();
        finder.setFilter(filter);
        finder.findFrom(head);
        for (Commit commit : filter.getCommits()) {
            //            ResetCommand reset = new Git(repository).reset();
            //            reset.setMode(ResetType.HARD);
            //            reset.setRef(commit.getId());
            CheckoutCommand checkout = new Git(repository).checkout();
            checkout.setName(commit.getId());
            //            checkout.setStartPoint(commit.getId());
            //            checkout.addPath(".");
            try {
                //               Ref call = reset.call();
                checkout.call();
                System.out.println(checkout.getResult().getStatus() + " checked out " + commit.getMessage());
            } catch (Exception e) {
                fail(e.getMessage());
            }

            //            System.out.println(change.getCommit().getFullMessage());

        }

        //         head = repository.resolve("HEAD~1");
        //         RevWalk revWalk = new RevWalk(repository);
        //         RevCommit tip = revWalk.parseCommit(head);
        //         revWalk.markStart(tip);
        //         revWalk.
        //         TreeWalk treeWalk = new TreeWalk(repository);
        //         treeWalk.setRecursive(true);
        //         treeWalk.addTree(tip.getTree());
        //         

        //         revWalk.markStart(tip);

        //         GitFileDiff[] compute = GitFileDiff.compute(treeWalk, tip);

        //         System.out.println(compute);

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:com.mycila.maven.plugin.license.git.GitLookup.java

License:Apache License

/**
 * Returns the year of the last change of the given {@code file} based on the history of the present git branch. The
 * year is taken either from the committer date or from the author identity depending on how {@link #dateSource} was
 * initialized./*from   w w  w .j  a v  a 2s . c  o  m*/
 * <p>
 * See also the note on time zones in {@link #GitLookup(File, DateSource, TimeZone, int)}.
 *
 * @param file
 * @return
 * @throws NoHeadException
 * @throws GitAPIException
 * @throws IOException
 */
public int getYearOfLastChange(File file) throws NoHeadException, GitAPIException, IOException {
    String repoRelativePath = pathResolver.relativize(file);

    Status status = new Git(repository).status().addPath(repoRelativePath).call();
    if (!status.isClean()) {
        /* Return the current year for modified and unstaged files */
        return toYear(System.currentTimeMillis(), timeZone != null ? timeZone : DEFAULT_ZONE);
    }

    RevWalk walk = new RevWalk(repository);
    walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD)));
    walk.setTreeFilter(AndTreeFilter.create(PathFilter.create(repoRelativePath), TreeFilter.ANY_DIFF));
    walk.setRevFilter(MaxCountRevFilter.create(checkCommitsCount));
    walk.setRetainBody(false);

    int commitYear = 0;
    for (RevCommit commit : walk) {
        int y;
        switch (dateSource) {
        case COMMITER:
            int epochSeconds = commit.getCommitTime();
            y = toYear(epochSeconds * 1000L, timeZone);
            break;
        case AUTHOR:
            PersonIdent id = commit.getAuthorIdent();
            Date date = id.getWhen();
            y = toYear(date.getTime(), id.getTimeZone());
            break;
        default:
            throw new IllegalStateException("Unexpected " + DateSource.class.getName() + " " + dateSource);
        }
        if (y > commitYear) {
            commitYear = y;
        }
    }
    walk.dispose();
    return commitYear;
}