Java 类org.eclipse.jgit.api.Git 实例源码

项目:warrior-jenkins-plugin    文件:WarriorPluginBuilder.java   
@Override
public Boolean invoke(File file, VirtualChannel channel){
    try{
        Git git = Git.cloneRepository()
                .setURI(url)
                .setDirectory(localDir)
                .setTransportConfigCallback(getTransportConfigCallback())
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .call();

        // Default branch to checkout is master
        if(branch==null || branch.isEmpty()){
            branch = "master";
        } else if (cloneType.equals("branch")){
            branch = "origin" + File.separator + branch;
        }
        git.checkout().setName(branch).call();
        git.close();
        }catch(GitAPIException e){
            status = false;
            e.printStackTrace(listener.getLogger());
        }
    return status;
}
项目:yacy_grid_mcp    文件:GitTool.java   
public GitTool() {
    File gitWorkDir = new File(".");
    try {
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}
项目:RefDiff    文件:GitServiceImpl.java   
private List<TrackingRefUpdate> fetch(Repository repository) throws Exception {
       logger.info("Fetching changes of repository {}", repository.getDirectory().toString());
       try (Git git = new Git(repository)) {
        FetchResult result = git.fetch().call();

        Collection<TrackingRefUpdate> updates = result.getTrackingRefUpdates();
        List<TrackingRefUpdate> remoteRefsChanges = new ArrayList<TrackingRefUpdate>();
        for (TrackingRefUpdate update : updates) {
            String refName = update.getLocalName();
            if (refName.startsWith(REMOTE_REFS_PREFIX)) {
                ObjectId newObjectId = update.getNewObjectId();
                logger.info("{} is now at {}", refName, newObjectId.getName());
                remoteRefsChanges.add(update);
            }
        }
        if (updates.isEmpty()) {
            logger.info("Nothing changed");
        }
        return remoteRefsChanges;
       }
}
项目:incubator-netbeans    文件:BlameCommand.java   
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath(Utils.getRelativePath(getRepository().getWorkTree(), file));
    if (revision != null) {
        cmd.setStartCommit(Utils.findCommit(repository, revision));
    } else if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
        // work-around for autocrlf
        cmd.setTextComparator(new AutoCRLFComparator());
    }
    cmd.setFollowFileRenames(true);
    try {
        BlameResult cmdResult = cmd.call();
        if (cmdResult != null) {
            result = getClassFactory().createBlameResult(cmdResult, repository);
        }
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
项目:FunnyCreator    文件:FunnyDownloader.java   
public void cloneRepository(FunnyCreator funnyCreator) throws Exception {
    while (FunnyConstants.REPOSITORY_DIRECTORY.exists()) {
        erase(funnyCreator);
        Thread.sleep(500);
    }

    funnyCreator.info("Cloning FunnyGuilds repository");

    Git.cloneRepository()
            .setURI(FunnyConstants.REPOSITORY)
            .setDirectory(FunnyConstants.REPOSITORY_DIRECTORY)
            .call()
            .close();

    FunnyCreator.getLogger().info("Repository has been cloned!");
}
项目:flow-platform    文件:JGitUtilTest.java   
@Test
public void should_push_success() throws Throwable {
    File localGitFolder = folder.newFolder("info.git");
    // when: init bareGit
    JGitUtil.init(localGitFolder.toPath(), true);

    // then: tag list is 0
    Assert.assertEquals(0, Git.open(localGitFolder).tagList().call().size());

    File onlineGitFolder = folder.newFolder("info");
    JGitUtil.clone(GIT_URL, onlineGitFolder.toPath());
    JGitUtil.remoteSet(onlineGitFolder.toPath(), "local", localGitFolder.toString());
    Git git = Git.open(onlineGitFolder);
    String tag = JGitUtil.tags(git.getRepository()).get(0);

    // when: push latest tag
    JGitUtil.push(onlineGitFolder.toPath(), "local", tag);

    // then: tag size is 1
    Assert.assertEquals(1, Git.open(localGitFolder).tagList().call().size());

    // then: tag is v1.1
    Assert.assertEquals("v1.1", JGitUtil.tags(localGitFolder.toPath()).get(0));
}
项目:incubator-netbeans    文件:CreateTagCommand.java   
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    try {
        RevObject obj = Utils.findObject(repository, taggedObject);
        TagCommand cmd = new Git(repository).tag();
        cmd.setName(tagName);
        cmd.setForceUpdate(forceUpdate);
        cmd.setObjectId(obj);
        cmd.setAnnotated(message != null && !message.isEmpty() || signed);
        if (cmd.isAnnotated()) {
            cmd.setMessage(message);
            cmd.setSigned(signed);
        }
        cmd.call();
        ListTagCommand tagCmd = new ListTagCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor));
        tagCmd.run();
        Map<String, GitTag> tags = tagCmd.getTags();
        tag = tags.get(tagName);
    } catch (JGitInternalException | GitAPIException ex) {
        throw new GitException(ex);
    }
}
项目:incubator-netbeans    文件:CommitTest.java   
public void testCommitNoRoots () throws Exception {
    File toCommit = new File(workDir, "testnotadd.txt");
    write(toCommit, "blablabla");
    GitClient client = getClient(workDir);
    Map<File, GitStatus> statuses = client.getStatus(new File[] { toCommit }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, toCommit, false, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_ADDED, false);
    client.add(new File[] { toCommit }, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(new File[] { toCommit }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, toCommit, true, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, false);
    GitRevisionInfo info = client.commit(new File[0], "initial commit", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(new File[] { toCommit }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, toCommit, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);

    Git git = new Git(repository);
    LogCommand log = git.log();
    RevCommit com = log.call().iterator().next();
    assertEquals("initial commit", info.getFullMessage());
    assertEquals("initial commit", com.getFullMessage());
    assertEquals(ObjectId.toString(com.getId()), info.getRevision());
    Map<File, GitFileInfo> modifiedFiles = info.getModifiedFiles();
    assertTrue(modifiedFiles.get(toCommit).getStatus().equals(Status.ADDED));
}
项目:gmds    文件:Branches.java   
public static void main(String[] args) throws IOException, GitAPIException {
        Repository repo = Commands.getRepo(Consts.META_REPO_PATH);

        Git git = new Git(repo);

        // Create a new branch
        git.branchCreate().setName("newBranch").call();
// Checkout the new branch
        git.checkout().setName("newBranch").call();
        // List the existing branches
        List<Ref> listRefsBranches = git.branchList().setListMode(ListMode.ALL).call();
        listRefsBranches.forEach((refBranch) -> {
            System.out.println("Branch : " + refBranch.getName());
        });
// Go back on "master" branch and remove the created one
        git.checkout().setName("master");
        git.branchDelete().setBranchNames("newBranch");
    }
项目:incubator-netbeans    文件:CatTest.java   
public void testCatRemoved () throws Exception {
    File f = new File(workDir, "removed");
    copyFile(getGoldenFile(), f);
    assertFile(getGoldenFile(), f);
    add(f);
    commit(f);

    GitClient client = getClient(workDir);
    String revision = new Git(repository).log().call().iterator().next().getId().getName();

    // remove and commit
    client.remove(new File[] { f }, false, NULL_PROGRESS_MONITOR);
    commit(f);
    assertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
    assertFile(f, getGoldenFile());

    assertFalse(client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
}
项目:launcher-backend    文件:GitCommitAndPushStep.java   
@Override
public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Map<Object, Object> attributeMap = uiContext.getAttributeMap();

    List<GitClonedRepoDetails> clonedRepos = (List<GitClonedRepoDetails>) attributeMap.get(AttributeMapKeys.GIT_CLONED_REPOS);
    if (clonedRepos != null) {
        for (GitClonedRepoDetails clonedRepo : clonedRepos) {
            Git git = clonedRepo.getGit();
            String gitUrl = clonedRepo.getGitUrl();
            UserDetails userDetails = clonedRepo.getUserDetails();
            File basedir = clonedRepo.getDirectory();
            String message = "Adding pipeline";
            try {
                LOG.info("Performing a git commit and push on URI " + gitUrl);
                gitAddCommitAndPush(git, gitUrl, userDetails, basedir, message);
            } catch (GitAPIException e) {
                return Results.fail("Failed to commit and push repository " + clonedRepo.getGitRepoName() + " due to " + e, e);
            } finally {
                removeTemporaryFiles(basedir);
            }
        }
    }
    return Results.success();
}
项目:csap-core    文件:Simple_GIT_API.java   
@Test
public void simple_checkout_with_no_branch() throws Exception {

    File outputFolder = new File( baseLocation + "testGitNoBranch" );

    FileUtils.deleteDirectory( outputFolder );

    String message = "Perform git checkout of " + inputUrl + " to destination: "
            + outputFolder.getAbsolutePath();
    logger.info(Boot_Container_Test.TC_HEAD + message );

    //
    Git r = Git
            .cloneRepository()
            .setURI( inputUrl )
            .setDirectory( outputFolder )
            .setCredentialsProvider(
                    new UsernamePasswordCredentialsProvider( "dummy", "dummy" ) )
            .call();

    File buildPom = new File( outputFolder + "/pom.xml" );
    assertThat( buildPom )
            .as( "Pom file found" )
            .exists().isFile();
}
项目:spring-cloud-release-tools    文件:GitRepo.java   
void revert(File project, String message) {
    try(Git git = this.gitFactory.open(file(project))) {
        RevCommit commit = git.log().setMaxCount(1).call().iterator().next();
        String shortMessage = commit.getShortMessage();
        String id = commit.getId().getName();
        if (!shortMessage.contains("Update SNAPSHOT to ")) {
            throw new IllegalStateException("Won't revert the commit with id [" + id + "] "
                    + "and message [" + shortMessage + "]. Only commit that updated "
                    + "snapshot to another version can be reverted");
        }
        log.debug("The commit to be reverted is [{}]", commit);
        git.revert().include(commit).call();
        git.commit().setAmend(true).setMessage(message).call();
        printLog(git);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
项目:flow-platform    文件:JGitBasedClient.java   
@Override
public File clone(String branch, boolean noCheckout) throws GitException {
    checkGitUrl();

    CloneCommand cloneCommand = Git.cloneRepository()
        .setURI(gitUrl)
        .setNoCheckout(noCheckout)
        .setBranch(branch)
        .setDirectory(targetDir.toFile());

    try (Git git = buildCommand(cloneCommand).call()) {
        return git.getRepository().getDirectory();
    } catch (GitAPIException e) {
        throw new GitException("Fail to clone git repo", e);
    }
}
项目:flow-platform    文件:PluginServiceImpl.java   
private void commitSomething(Path path) {
    try (Git git = Git.open(path.toFile())) {
        Path emptyFilePath = Paths.get(path.toString(), EMPTY_FILE);

        try {
            Files.createFile(emptyFilePath);
        } catch (FileAlreadyExistsException ignore) {
        }

        git.add()
            .addFilepattern(".")
            .call();

        git.commit()
            .setMessage("add test branch")
            .call();

    } catch (Throwable e) {
        LOGGER.error("Method: commitSomething Exception", e);
    }
}
项目:spring-cloud-release-tools    文件:GitRepoTests.java   
@Test
public void should_push_a_tag_to_new_branch_in_origin() throws Exception {
    File origin = clonedProject(this.tmp.newFolder(), this.springCloudReleaseProject);
    File project = this.gitRepo.cloneProject(this.springCloudReleaseProject.toURI());
    setOriginOnProjectToTmp(origin, project);
    createNewFile(project);
    this.gitRepo.commit(project, "some message");
    this.gitRepo.tag(project, "v5.6.7.RELEASE");

    this.gitRepo.pushTag(project, "v5.6.7.RELEASE");

    try(Git git = openGitProject(origin)) {
        tagIsPresent(git, "v5.6.7");
        git.checkout().setName("v5.6.7.RELEASE").call();
        RevCommit revCommit = git.log().call().iterator().next();
        then(revCommit.getShortMessage()).isEqualTo("some message");
    }
}
项目:EasyPackage    文件:GitUtil.java   
public static void checkoutAndPull(@NonNull String projectRootDir,
        @NonNull String branchOrCommit) {
    Pair<Boolean, Path> fileExist = isFileExist(projectRootDir);
    if (!fileExist.getLeft()) {
        return;
    }
    File file = fileExist.getRight().toFile();
    try (Git git = Git.open(file)) {
        CmdExecResult result = CommandExecUtil.execCmd(
                Constants.TOMCAT_PATH
                        + "/webapps"
                        + Config.getContextPath()
                        + "/shell/gitCheckoutAndPull.sh "
                        + file.getAbsolutePath()
                        + " "
                        + branchOrCommit, true);
        if (result == null || !result.isSuccess()) {
            logger.error("checkout failed, {}", result);
        }
    } catch (IOException e) {
        logger.error("error occurred, {}", e);
    }
}
项目:smart-testing    文件:GitCloner.java   
public Repository cloneRepositoryToTempFolder(boolean checkoutAll) throws GitAPIException, IOException {
    this.targetFolder = createTempFolder(repositoryName);
    final Repository repository = Git.cloneRepository()
                .setURI(repositoryUrl)
                .setDirectory(targetFolder)
                .setCloneAllBranches(true)
                .setBranch("master")
            .call()
        .getRepository();

    if (checkoutAll) {
        checkoutAllBranches(repository);
    }

    LOGGER.info("Cloned test repository to: " + targetFolder);
    return repository;
}
项目:smart-testing    文件:GitChangeResolverTest.java   
@Test
public void should_fetch_all_untracked_files_for_first_commit() throws IOException, GitAPIException {
    // given
    final File parent = gitFolder.newFolder("parent");
    final File newGitFolder = parent.getParentFile();

    gitFolder.newFile("parent/foo.txt");

    try (Git git = Git.init()
        .setDirectory(newGitFolder)
        .call()) {
    }

    this.gitChangeResolver = new GitChangeResolver();

    // when
    final Set<Change> untrackedChanges = gitChangeResolver.diff(newGitFolder, "HEAD~0", "HEAD");

    // then
    assertThat(untrackedChanges).hasSize(1).extracting(Change::getLocation, Change::getChangeType).containsOnly(tuple(
        relative("parent/foo.txt"), ChangeType.ADD));
}
项目:flow-platform    文件:JGitBasedClient.java   
@Override
public List<String> tags() throws GitException {
    try {
        Collection<Ref> refs = buildCommand(Git.lsRemoteRepository()
            .setTags(true)
            .setTimeout(GIT_TRANS_TIMEOUT)
            .setRemote(gitUrl)).call();


        List<Ref> listRefs = Lists.newArrayList(refs);
        listRefs.sort(JGitUtil.REF_COMPARATOR);

        return JGitUtil.simpleRef(refs);
    } catch (GitAPIException e) {
        throw new GitException("Fail to list tags from remote repo", ExceptionUtil.findRootCause(e));
    }
}
项目:jekyll2cms    文件:GitRepoCloner.java   
/**
 * Clones the remote repository (defined in application.properties:
 * repository.remote.url) to the local file system (repository.local.path) -
 * only if the local repository does not already exist.
 */
public boolean cloneRemoteRepo() {

    String method = "cloneRemoteRepo";
    try {
        if (!localRepositoryExists()) {
            LocalRepoCreater.setLocalGit(Git.cloneRepository().setURI(REMOTE_REPO_URL).setDirectory(new File(LOCAL_REPO_PATH)).call());
            LOGGER.info("Repository cloned successfully");
        } else {
            LOGGER.warn("Remote repository is already cloned into local repository");
            LocalRepoCreater.setLocalGit(Git.open(new File(LOCAL_REPO_PATH+".git")));
        }
    } catch (Exception e) {
        LOGGER.error("In method " + method + ": Error while cloning remote git respository", e);
        return false;
    }

    return true;
}
项目:xm-ms-config    文件:JGitRepository.java   
@SneakyThrows
protected void pull() {
    try (
            Repository db = createRepository();
            Git git = Git.wrap(db);
    ) {
        String branchName = gitProperties.getBranchName();
        try {
            git.checkout().setName(branchName).call();
            git.pull().setCredentialsProvider(createCredentialsProvider()).call();
        } catch (RefNotFoundException e) {
            log.info("Branch {} not found in local repository", branchName);
            git.fetch().setCredentialsProvider(createCredentialsProvider()).call();
            git.checkout()
                    .setCreateBranch(true)
                    .setName(branchName)
                    .setUpstreamMode(TRACK)
                    .setStartPoint(DEFAULT_REMOTE_NAME + "/" + branchName).
                    call();
            git.pull().setCredentialsProvider(createCredentialsProvider()).call();
        }
    }
}
项目:flow-platform    文件:JGitUtil.java   
public static Repository getRepo(Path path) throws GitException {
    try (Git git = Git.open(path.toFile())) {
        return git.getRepository();
    } catch (IOException e) {
        throw new GitException(e.getMessage());
    }
}
项目:flow-platform    文件:JGitBasedClient.java   
/**
 * Create local .git with remote info
 *
 * @return .git file path, /targetDir/.git
 */
private File initGit(Set<String> checkoutFiles) throws GitException {
    try (Git git = Git.init().setDirectory(targetDir.toFile()).call()) {
        Repository repository = git.getRepository();
        File gitDir = repository.getDirectory();
        setSparseCheckout(gitDir, checkoutFiles);
        configRemote(repository.getConfig(), "origin", gitUrl);
        return gitDir;
    } catch (GitAPIException e) {
        throw new GitException("Fail to init git repo at: " + targetDir, e);
    }
}
项目:flow-platform    文件:TestBase.java   
protected void initGit() {

        RevCommit commit = null;
        try {
            mocGit = temporaryFolder.newFolder(DEMO_GIT_NAME + GIT_SUFFIX);
            gitCloneMocGit = temporaryFolder.newFolder(DEMO_GIT_NAME);

            JGitUtil.init(mocGit.toPath(), true);
            JGitUtil.clone(mocGit.toString(), gitCloneMocGit.toPath());

            // git commit something
            java.nio.file.Files.createFile(Paths.get(gitCloneMocGit.toString(), "readme.md"));

            // add yml file
            String body = getResource("flow-step-demo.yml");
            Path path = Paths.get(gitCloneMocGit.toString(), ".flow-plugin.yml");
            FileUtils.write(path.toFile(), body);

            // add
            Git git = Git.open(gitCloneMocGit);
            git.add().addFilepattern(".").call();
            commit = git.commit().setMessage("firCi").call();
            JGitUtil.push(gitCloneMocGit.toPath(), "origin", "master");

            // git push tag
            git.tag().setName("1.0").setMessage("add tag 1.0").call();
            JGitUtil.push(gitCloneMocGit.toPath(), "origin", "1.0");
        } catch (Throwable throwable) {

        }

        // update plugin to local git
        for (Plugin plugin : pluginDao.list(null, null, null)) {
            plugin.setSource(mocGit.getParent() + "/firCi");
            plugin.setLatestCommit(commit.getId().getName());
            pluginDao.update(plugin);
        }
    }
项目:flow-platform    文件:JGitUtilTest.java   
@Test
public void should_fetch_tags_success() throws Throwable {
    File localGitFolder = folder.newFolder("info.git");
    File onlineGitFolder = folder.newFolder("info");
    JGitUtil.init(onlineGitFolder.toPath(), false);
    JGitUtil.init(localGitFolder.toPath(), true);
    JGitUtil.remoteSet(onlineGitFolder.toPath(), "origin", GIT_URL);
    JGitUtil.remoteSet(onlineGitFolder.toPath(), "local", localGitFolder.toString());
    JGitUtil.fetchTags(onlineGitFolder.toPath(), GIT_URL);
    Git git = Git.open(onlineGitFolder);
    Assert.assertEquals(2, git.remoteList().call().size());
    Assert.assertEquals(false, JGitUtil.tags(git.getRepository()).isEmpty());
}
项目:n4js    文件:GitUtils.java   
/**
 * Returns the origin of the given repository.
 *
 * @param git
 *            the git repository
 * @return the origin
 * @throws GitAPIException
 *             if an error occurs while accessing the given repository
 */
private static Optional<RemoteConfig> getOriginRemote(Git git) throws GitAPIException {
    List<RemoteConfig> remotes = git.remoteList().call();
    if (remotes.isEmpty())
        return Optional.absent();

    final String origin = getDefaultRemote();
    return from(remotes).firstMatch((remote) -> {
        return remote.getName().equals(origin);
    });
}
项目:flow-platform    文件:JGitUtil.java   
public static List<String> tags(Path gitPath) throws GitException {
    try (Git git = Git.open(gitPath.toFile())) {
        try (Repository repo = git.getRepository()) {
            return tags(repo);
        }
    } catch (IOException e) {
        throw new GitException(e.getMessage());
    }
}
项目:gmds    文件:DbIndex.java   
public static RevTree getRevTree(final Repository repository) {
    try (Git git = new Git(repository)) {
        Iterable<RevCommit> commits = git.log().all().call();
        RevCommit array[] = Iterables.toArray(commits, RevCommit.class);
        return array[0].getTree();
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(DbIndex.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
项目:flow-platform    文件:JGitUtil.java   
/**
 * Setting remote url to local repo
 *
 * @param path
 * @param remoteName
 * @param remoteUrl
 * @return
 * @throws GitException
 */
public static Path remoteSet(Path path, String remoteName, String remoteUrl) throws GitException {
    try (Git git = Git.open(path.toFile())) {
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", remoteName, "url", remoteUrl);
        config.save();
    } catch (IOException e) {
        throw new GitException("set remote url exception", e);
    }

    return path;
}
项目:incubator-netbeans    文件:CommitTest.java   
public void testSingleTreeCommit () throws Exception {
    File folder = new File(workDir, "folder");
    File subfolder1 = new File(folder, "subfolder");
    File subfolder11 = new File(subfolder1, "subfolder1");
    File subfolder12 = new File(subfolder1, "subfolder2");
    subfolder11.mkdirs();
    subfolder12.mkdirs();
    File file1 = new File(subfolder11, "file1");
    File file2 = new File(subfolder12, "file2");
    write(file1, "file1 content");
    write(file2, "file2 content");
    File[] files = new File[] { folder };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    GitRevisionInfo info = client.commit(files, "initial commit", null, null, NULL_PROGRESS_MONITOR);
    Map<File, GitFileInfo> modifiedFiles = info.getModifiedFiles();
    assertEquals(2, modifiedFiles.size());
    assertTrue(modifiedFiles.get(file1).getStatus().equals(Status.ADDED));
    assertTrue(modifiedFiles.get(file2).getStatus().equals(Status.ADDED));

    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, file1, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
    assertStatus(statuses, workDir, file2, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);

    Git git = new Git(repository);
    LogCommand log = git.log();
    RevCommit com = log.call().iterator().next();
    assertEquals("initial commit", com.getFullMessage());
}
项目:flow-platform    文件:JGitBasedClient.java   
@Override
public List<String> branches() throws GitException {
    try {
        Collection<Ref> refs = buildCommand(Git.lsRemoteRepository()
            .setHeads(true)
            .setTimeout(GIT_TRANS_TIMEOUT)
            .setRemote(gitUrl)).call();

        return JGitUtil.simpleRef(refs);
    } catch (GitAPIException e) {
        throw new GitException("Fail to list branches from remote repo", e);
    }
}
项目:flow-platform    文件:JGitBasedClient.java   
private Git gitOpen() throws GitException {
    try {
        return Git.open(getGitPath().toFile());
    } catch (IOException e) {
        throw new GitException("Fail to open .git folder", e);
    }
}
项目:incubator-netbeans    文件:ResetTest.java   
public void testResetPathsChangeType () throws Exception {
    File file = new File(workDir, "f"); // index entry will be modified
    File file2 = new File(file, "file");
    write(file, "blablablabla");
    File[] files = new File[] { file, file2 };
    add(files);
    commit(files);

    GitClient client = getClient(workDir);
    client.remove(files, false, NULL_PROGRESS_MONITOR);
    commit(files);
    file.mkdirs();
    write(file2, "aaaa");
    add(file2);
    commit(files);

    Iterator<RevCommit> logs = new Git(repository).log().call().iterator();
    String revisionCurrent = logs.next().getId().getName();
    logs.next();
    String revisionPrevious = logs.next().getId().getName();

    client.reset(files, revisionPrevious, true, NULL_PROGRESS_MONITOR);
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(2, statuses.size());
    assertStatus(statuses, workDir, file, true, Status.STATUS_ADDED, Status.STATUS_REMOVED, Status.STATUS_NORMAL, false);
    assertStatus(statuses, workDir, file2, true, Status.STATUS_REMOVED, Status.STATUS_ADDED, Status.STATUS_NORMAL, false);

    client.reset(files, revisionCurrent, true, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, file2, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
项目:incubator-netbeans    文件:CatTest.java   
public void testCat () throws Exception {
    File folder = new File(workDir, "folder");
    folder.mkdirs();
    File f = new File(folder, "testcat1");
    copyFile(getGoldenFile(), f);
    assertFile(getGoldenFile(), f);
    add(f);
    GitClient client = getClient(workDir);
    try {
        client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR);
        fail();
    } catch (GitException.MissingObjectException ex) {
        assertEquals(GitObjectType.COMMIT, ex.getObjectType());
        assertEquals(Constants.HEAD, ex.getObjectName());
    }
    commit(f);

    assertTrue(client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
    assertFile(f, getGoldenFile());

    String revision = new Git(repository).log().call().iterator().next().getId().getName();
    assertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
    assertFile(f, getGoldenFile());

    write(f, "blablabla");
    add(f);
    commit(f);
    assertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
    assertFile(f, getGoldenFile());
}
项目:launcher-backend    文件:AbstractGitRepoStep.java   
public static void importNewGitProject(UserDetails userDetails, File basedir, String message, String gitUrl, String branch, String origin, Logger logger) throws GitAPIException {
    GitUtils.disableSslCertificateChecks();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);
    Git git = initCommand.call();
    logger.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());
    gitAddCommitAndPush(git, gitUrl, userDetails, basedir, message, branch, origin, logger);
}
项目:rebazer    文件:RebaseService.java   
@Autowired
public RebaseService( final RebazerConfig config ) {
    this.config = config;
    currentGcCountdown = config.getGarbageCollectionCountdown();

    final CredentialsProvider credentials =
            new UsernamePasswordCredentialsProvider( config.getUser(), config.getPass() );

    config.getRepos().forEach( repo -> {
        final File repoFolder = new File( config.getWorkspace(), repo.getName() );
        Git localRepo = null;
        final String repoUrl = "https://bitbucket.org/" + config.getTeam() + "/" + repo.getName() + ".git";
        repo.setUrl( repoUrl );
        repo.setCredentials( credentials );

        if ( repoFolder.exists() ) {
            localRepo = tryToOpenExistingRepoAndCheckRemote( repoFolder, repoUrl );
            if ( localRepo == null ) {
                try {
                    FileUtils.deleteDirectory( repoFolder );
                } catch ( final IOException e ) {
                    throw new RuntimeException( e );
                }
            }
        }
        if ( localRepo == null ) {
            localRepo = cloneNewRepo( repoFolder, repoUrl, credentials );
        }
        repo.setGit( localRepo );
        cleanUp( repo );
    } );

}
项目:VoxelGamesLibv2    文件:WorldRepository.java   
public void cloneRepo() {
    try {
        Git git = Git.cloneRepository().setURI(url).setDirectory(worldsDir).call();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
}
项目:launcher-backend    文件:GitProvider.java   
public Git cloneRepo(CloneRepoAttributes attributes) throws GitAPIException {
    CloneCommand command = Git.cloneRepository();
    String gitUri = attributes.getUri();

    UserDetails userDetails = attributes.getUserDetails();
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    GitUtils.configureCommand(command, credentialsProvider, userDetails.getSshPrivateKey(), userDetails.getSshPublicKey());

    command = command.setCredentialsProvider(credentialsProvider).
            setCloneAllBranches(attributes.isCloneAll()).
            setURI(gitUri).
            setDirectory(attributes.getDirectory()).setRemote(attributes.getRemote());

    return command.call();
}
项目:ranch2git    文件:GitRepo.java   
private void initRepo() throws IOException, GitAPIException {
    if(localPath.exists()){
        git = Git.open(localPath);
    }else{
        git = Git.cloneRepository().setURI(remote).setDirectory(new File(localPath.getPath())).setCredentialsProvider(cp).call();
    }

}