这里简单封装了一个工具类

    1. package com.example.demo;
    2. import org.eclipse.jgit.api.CloneCommand;
    3. import org.eclipse.jgit.api.Git;
    4. import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
    5. import java.io.File;
    6. public class GitUtils {
    7. /**
    8. * 创建git
    9. * @param uri git地址
    10. * @param branch 操作的分支
    11. * @param directory 本地仓库目录
    12. * @return
    13. */
    14. public static Git createGit(String uri, String branch, String directory) {
    15. try {
    16. return new CloneCommand().setURI(uri)
    17. .setBranch(branch)
    18. .setDirectory(new File(directory))
    19. .call();
    20. } catch (Exception e) {
    21. throw new RuntimeException(e);
    22. }
    23. }
    24. /**
    25. * 推送本地代码到远程
    26. * @param git
    27. * @param message 提交信息
    28. * @param username 远程仓库用户名
    29. * @param password 远程仓库密码
    30. */
    31. public static void push(Git git, String message, String username, String password) {
    32. try {
    33. git.add().addFilepattern(".").call();
    34. git.commit().setMessage(message).call();
    35. git.pull().setCredentialsProvider(
    36. new UsernamePasswordCredentialsProvider(username, password))
    37. .call();
    38. git.close();
    39. } catch (Exception e) {
    40. throw new RuntimeException(e);
    41. }
    42. }
    43. }