自动提交到远程仓库脚本
先引入JGit包
<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>7.1.0.202411261347-r</version>
</dependency>
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import java.io.File;
import java.io.IOException;
public class GitAutoPush {
public static void main(String[] args) {
String localRepoPath = "/path/to/your/local/repo"; // 本地仓库路径
String remoteRepoUrl = "https://github.com/yourusername/yourrepo.git"; // 远程仓库地址
String username = "yourusername"; // GitHub 用户名
String password = "yourpassword"; // GitHub 密码,推荐使用 token 替代密码
try {
// 获取本地仓库
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = builder.setGitDir(new File(localRepoPath + "/.git"))
.readEnvironment()
.findGitDir()
.build();
// 初始化 Git 实例
Git git = new Git(repository);
// 添加所有文件更改到暂存区
git.add().addFilepattern(".").call();
// 提交更改
git.commit().setMessage("Auto commit changes").call();
// 设置推送凭证
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
// 推送到远程仓库
git.push()
.setCredentialsProvider(credentialsProvider)
.setRemote("origin")
.setPushAll()
.call();
System.out.println("Changes pushed successfully!");
} catch (GitAPIException | IOException e) {
e.printStackTrace();
}
}
}
浙公网安备 33010602011771号