Java操作Git实现增量发布

Java操作Git实现增量发布

  1. 导入maven依赖
    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>3.5.0.201409260305-r</version>
    </dependency>
  1. 添加代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    @Test
    public void test3() throws IOException, GitAPIException {
    Repository repository = new FileRepositoryBuilder()
    .setGitDir(new File("/Users/brucexie/Documents/work/yuewen/yuewen_channel_marketing_api/.git"))
    .build();

    Git git = new Git(repository);
    DiffCommand diff = git.diff();
    List<DiffEntry> call = diff.call();
    List<String> diffFileList = new ArrayList();
    for (DiffEntry diffEntry : call) {
    String newPath = diffEntry.getNewPath();
    if (newPath.indexOf("/") > 0)
    diffFileList.add(newPath.substring(newPath.lastIndexOf("/") + 1));
    else
    diffFileList.add(newPath);
    }

    System.out.println("变更文件列表如下:");
    diffFileList.stream().forEach(System.out::println);
    System.out.println("\n准备发送文件...\n");
    diffFileList.stream().forEach(item -> {
    try {
    System.out.printf("SCP 开始发送文件 \n %s ... ", item);

    TimeUnit.SECONDS.sleep(1);
    System.out.printf("\n完成发送文件 %s \n", item);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    });

    System.out.println("准备执行dos命令: ");
    System.out.println(run("git status"));

    }

    public static String run(String command) throws IOException {
    Scanner input = null;
    String result = "";
    Process process = null;
    try {
    process = Runtime.getRuntime().exec(command);
    try {
    //等待命令执行完成
    process.waitFor(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    InputStream is = process.getInputStream();
    input = new Scanner(is);
    while (input.hasNextLine()) {
    result += input.nextLine() + "\n";
    }
    result = command + "\n" + result; //加上命令本身,打印出来
    } finally {
    if (input != null) {
    input.close();
    }
    if (process != null) {
    process.destroy();
    }
    }
    return result;
    }
  2. 查看执行结果