package com.css.simulation.resource.scheduler.infra.configuration.git;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;

/**
 * <!-- git 操作类库 -->
 * <dependency>
 * <groupId>org.eclipse.jgit</groupId>
 * <artifactId>org.eclipse.jgit</artifactId>
 * <version>${org.eclipse.jgit.version}</version>
 * </dependency>
 */
@Slf4j
public class GitUtil {

    /**
     * @param url           git 地址
     * @param username      用户名
     * @param password      密码
     * @param directoryPath 空目录
     * @param cover         如果目录内有文件，是否覆盖
     */
    @SneakyThrows
    @SuppressWarnings("all")
    public static void clone(String url, String username, String password, String directoryPath, boolean cover) {
        File directoryFile = new File(directoryPath);
        if (directoryFile.exists()) {
            File[] files = directoryFile.listFiles();
            if (files == null || files.length == 0) {
                clone(url, username, password, directoryFile);
            } else {
                if (cover) {
                    for (File file : files) {
                        file.delete();
                    }
                    clone(url, username, password, directoryFile);
                } else {
                    throw new RuntimeException("GitUtil--clone 目标下载目录不是空目录。");
                }
            }
        } else {
            directoryFile.mkdirs();
            clone(url, username, password, directoryFile);
        }

    }

    @SneakyThrows
    private static void clone(String url, String username, String password, File directoryFile) {
        Git git = Git.cloneRepository()
                .setURI(url)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .setDirectory(directoryFile)
                .call();
    }
}
