Java实现git操作——jGit学习(一)

来源文档

jgit官方使用文档

git clone克隆仓库

// git clone http://****.git -b target --single-branch localpath 
Git.cloneReposity()
	.setURI("http://****.git") //设置从何处clone仓库
	.setGitDir() //设置元目录(.git)
	.setBranch("target") //设置初始化分支
	.setDirectory(new File("localpath")) //设置本地文件目录
	//.setRemote() //设置远程名称
	//.setCloneAllBranches() //fetch所有分支
	//.setBranchesToClone() //指定分支clone,必须设置为类似refs/heads/master的名称
	.call(); //执行命令

构造仓库 repository

Repository repository = new FileRepositoryBuilder()
							.setGitDir(new File("localpath.git"))//设置存储存储库元数据的Git目录
                    		.readEnvironment()//读取标准的Git环境变量,并根据这些变量进行配置。
//此方法尝试读取标准的Git环境变量,如git_dir和git_work_tree来配置这个Builder实例。如果在Builder中已经设置了属性,则不使用该环境变量。
                    		.findGitDir()/*通过搜索文件系统来配置git_dir。
从JVM的当前工作目录开始,在目录树中向上扫描,直到找到一个Git仓库。通过检查getGitDir()!=null可以确定是否成功。
通过添加CeilingDirectory(文件)或通过先前调用ReadEnvironment()继承列表,可以将搜索限制在本地文件系统的特定空间。*/
                    		.build();

git fetch 拉取所有分支

//git fetch --force
Git git = new Git(reposity)
git.fetch().setForceUpdate(true).call();

git reset 重置代码

//git reset --hard origin/branch
git.reset().setRef("origin/branch").call()

git pull 拉取最新代码

//git pull 
git.pull().call();

git status 查看当前状态

//git status
git.status()
	.addPath("src/main/file.java") //查看文件、目录状态
	.call();
Status status = git.status().call();
Set<String> addRes = status.getAdded();//获取added状态的文件列表
Set<String> changedRes = status.getChanged();//获取changed状态的文件列表
Set<String> conflictRes = status.getConflicting();//获取conflict状态的文件列表
Set<String> removedRes = status.getRemoved();//获取removed状态的文件列表
Set<String> missRes = status.getMissing();//获取missing状态的文件列表
Set<String> modifiedRes = status.getModified();//获取modified状态的文件列表
Set<String> untrackedRes = status.getUntracked();//获取untracked状态的文件列表
status.isClean();//暂存区是否clean

git add 添加到暂存区

//git add src/main/file.java
git.add()
	.addFilepattern("src/main/file.java")//指定需要添加的文件或目录路径,不加这句等同于git add .
	.call()

git commit 提交信息

//git commit
git.commit()
	.setAmend(true)// git commit --amend
	.setMessage("message") //git commit -m
	.setAuthor("name", "email") //设置用户名、邮箱
	.call()

git push 推送上库

//git push
git.push()
	.setRemote("origin") //设置远端名称
	.setRefSpecs(new RefSpecs("main")) //设置推送的分支,如果远端没有就创建
	.call()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值