Git提交代码工具
为什么想弄个这个呢,因为在刚刚加入到公司中,学的知识都更多理论一些,在使用git的时候容易犯错,代码写的不好只不过是在debug的过程中难为自己,如果git用不好同事的代码就没了,不要影响到别人哦
程序中隐藏配置或敏感信息
在项目的跟目录下找到.gitignore
这个文件,在文件内添加src/main/resources/get-config.yaml
保证git信息安全。恭喜你.gitignore
的操作步骤你也会用了 哈哈哈哈哈哈
clone 克隆
File dir = new File(config.getRepoPath());
if (dir.exists()) {
log.info("本地目录已存在,将跳过删除: " + dir.getAbsolutePath());
} else {
Git git = Git.cloneRepository()
.setURI(config.getRemoteURL())
.setDirectory(dir)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(config.getUsername(), config.getPassword()))
.call();
git.close();
log.info("克隆完成: " + dir.getAbsolutePath());
}
push 推送
注意在每次push之前一定要pull,防止你在push的时候将同事的代码给覆盖了。
try (Git git = Git.open(new File(config.getRepoPath()))) {
git.add().addFilepattern(".").call();
git.commit().setMessage(commitMessage)
.setAuthor("Auto Commit", config.getUsername())
.call();
//拉取代码
PullTools.PullProject(config);
git.push()
.setRemote(config.getRemoteURL())
.setRefSpecs(new RefSpec("HEAD:refs/heads/" + branchName))
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(config.getUsername(), config.getPassword()))
.call();
log.info("推送成功: " + branchName);
}
merge 合并
最关键的地方就是这里
你的每次push都是在本地操作,基本上没人会动你的分支,只有你将代码提交到远程分支的时候才会和同事之间的代码有冲突。
try (Git git = Git.open(new File(config.getRepoPath()))) {
// 切换到目标分支
PullTools.checkoutOrCreateBranch(git, toBranch);
// 拉取目标分支
PullResult pullResult = git.pull()
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(config.getUsername(), config.getPassword()))
.call();
if (pullResult.isSuccessful()) {
log.info("拉取远程 {} 成功", toBranch);
} else {
log.warn("拉取远程 {} 失败", toBranch);
}
// 合并源分支
Ref fromRef = git.getRepository().findRef(fromBranch);
ObjectId fromCommit = fromRef.getObjectId();
RevWalk walk = new RevWalk(git.getRepository());
RevCommit commit = walk.parseCommit(fromCommit);
MergeResult result = git.merge()
.include(commit)
.setCommit(true)
.setMessage("Merge branch '" + fromBranch + "' into " + toBranch)
.call();
if (result.getMergeStatus().isSuccessful()) {
log.info("成功合并 {} 到 {}", fromBranch, toBranch);
} else {
log.warn("合并失败: {}", result.getMergeStatus());
}
walk.dispose();
// 推送合并结果
git.push()
.setRemote(config.getRemoteURL())
.setRefSpecs(new RefSpec("refs/heads/" + toBranch))
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(config.getUsername(), config.getPassword()))
.call();
代码路径
具体的代码在https://gitee.com/cold-welding/jgit-test/blob/master 这里,可以直接下载到本地当作工具来使用。
如果打算使用./作为根文件来使用的话记得将src/test/java/util,src/test/java/test,src/test/java/config和src/main/resources/git-config.yaml 将这几个文件放到git忽略项里,如果有什么好的点子,让我在添加的功能可以跟我讲。持续更新
学习沉淀分享,成为更好的自己