java拉取github项目单个文件

4 篇文章 0 订阅

一、知识点汇总

  • stage: 缓存区(index), 准备commit的数据

  • stash: 临时记录本,写了一半的代码,想先保存一下,回到最开始去开发功能或者摘取代码之类

  • git 三种对象 :

    blob: 理解为文件内容的SHA-1结果
    Tree: 理解文件夹的SHA-1结果,里面包含子文件夹与文件(blob),也有对应的文件名
    commiter: 理解为对Tree的提交,同时记录作者、提交注释、提交时间等

二、java代码的处理

  • java中执行checkout命令的对象 Git, CloneCommand
  • 初始化git

CloneCommand cloneCommand = Git.cloneRepository().setCredentialsProvider(gitCredentialsProvider)
.setURI(“xxxx.git”)
.setBranch(“master”)
.setDirectory(repoGitDir)
.setNoCheckout(true)
Git call = cloneCommand.call()

  • 拉取目标文件

call.checkout()
.setStartPoint(“origin/master”)
.addPath(“目标文件路径”).call()

  • 获取文件对象

Repository repository = call.getRepository()
File workTreeFile = repository.workTree
File objectFile = new File(workTreeFile,“目标文件路径”)

三、java代码拉取单个git文件

        Git call = null
        try{
            File repoGitDir = new File("存放目录")
            if(repoGitDir.exists()){
                FileUtils.deleteDirectory(repoGitDir)
            }
            repoGitDir.mkdir()

            CloneCommand cloneCommand = Git.cloneRepository().setCredentialsProvider(gitCredentialsProvider)
                    .setURI("xxxx.git")
                    .setBranch("master")
                    .setDirectory(repoGitDir)
                    .setNoCheckout(true)
            call = cloneCommand.call()
            call.checkout()
                    .setStartPoint("origin/master")
                    .addPath("目标文件路径").call()

            Repository repository = call.getRepository()
            File workTreeFile = repository.workTree
            File objectFile = new File(workTreeFile,"目标文件路径")
            if(objectFile && objectFile.exists()){
                return new String(objectFile.getBytes())
            } else {
                throw new Exception("文件不存在")
            }
        } catch(Exception e){
	        throw e
        } finally {
            if(call){
                call.getRepository().close()
            }

            File targetFile = new File(getTargetDirectoryPath(entityId + File.separator + subPath))
            if (targetFile.exists()) {
                log.info("delete file {}, url:{}", targetFile.getAbsolutePath(), subPath)
                targetFile.delete()
            }

            File docDirectory = new File(getTargetDirectoryPath(entityId))
            if(docDirectory.exists()){
                FileUtils.deleteDirectory(docDirectory)
            }
        }

四 注意

  • 最后删除整个.git目录,不然得话,无法拉取其它文件,因为遇到过,不删除得话,会出现一些问题
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值