当前位置: 首页>>代码示例>>Java>>正文


Java Git类代码示例

本文整理汇总了Java中org.eclipse.jgit.api.Git的典型用法代码示例。如果您正苦于以下问题:Java Git类的具体用法?Java Git怎么用?Java Git使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Git类属于org.eclipse.jgit.api包,在下文中一共展示了Git类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: invoke

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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;
}
 
开发者ID:warriorframework,项目名称:warrior-jenkins-plugin,代码行数:25,代码来源:WarriorPluginBuilder.java

示例2: load

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
/**
 * 从指定的git仓库地址(目前仅支持http和https)和文件名获取资源,通过UsernameCredential支持鉴权
 * @return 资源的字符串
 * @throws Exception 资源不存在或网络不通
 */
@Override
public String load() throws Exception {
    //本地临时目录,用户存放clone的代码
    String tempDirPath = localPath + "/iaac.aliyun.tmp_" + new Date().getTime();
    File tempDir = new File(tempDirPath);
    tempDir.mkdirs();
    String result = null;
    try {
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(url);
        clone.setBranch(this.branch);
        clone.setDirectory(tempDir);

        //设置鉴权
        if (this.credential != null) {
            UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider = new
                    UsernamePasswordCredentialsProvider(this.credential.getUsername(), this.credential.getPassword());
            //git仓库地址
            clone.setCredentialsProvider(usernamePasswordCredentialsProvider);
        }
        //执行clone
        Git git = clone.call();
        //从本地路径中获取指定的文件
        File file = new File(tempDir.getAbsolutePath() + "/" + this.fileName);
        //返回文件的字符串
        result = FileUtils.readFileToString(file, "utf-8");
    } catch (Exception e) {
        throw e;
    } finally {
        //清除本地的git临时目录
        FileUtils.deleteDirectory(tempDir);
    }
    return result;
}
 
开发者ID:peterchen82,项目名称:iaac4j.aliyun,代码行数:40,代码来源:GitLoader.java

示例3: revert

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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);
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-release-tools,代码行数:19,代码来源:GitRepo.java

示例4: GitTool

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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 = "";
    }
}
 
开发者ID:yacy,项目名称:yacy_grid_mcp,代码行数:17,代码来源:GitTool.java

示例5: fetch

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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;
       }
}
 
开发者ID:aserg-ufmg,项目名称:RefDiff,代码行数:22,代码来源:GitServiceImpl.java

示例6: run

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:BlameCommand.java

示例7: cloneRepository

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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!");
}
 
开发者ID:FunnyGuilds,项目名称:FunnyCreator,代码行数:17,代码来源:FunnyDownloader.java

示例8: should_push_success

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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));
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:25,代码来源:JGitUtilTest.java

示例9: run

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:24,代码来源:CreateTagCommand.java

示例10: testCommitNoRoots

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:CommitTest.java

示例11: main

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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");
    }
 
开发者ID:alexmy21,项目名称:gmds,代码行数:19,代码来源:Branches.java

示例12: testCatRemoved

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
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));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:CatTest.java

示例13: execute

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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();
}
 
开发者ID:fabric8-launcher,项目名称:launcher-backend,代码行数:26,代码来源:GitCommitAndPushStep.java

示例14: simple_checkout_with_no_branch

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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();
}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:26,代码来源:Simple_GIT_API.java

示例15: clone

import org.eclipse.jgit.api.Git; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:17,代码来源:JGitBasedClient.java


注:本文中的org.eclipse.jgit.api.Git类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。