Java 实现Git拉包 maven打包项目

开发过程中遇到这样的需求,Java拉取指定代码库指定分支的代码java代码,然后有maven打包,将打包好的jar上传到文件服务器。

解决思路分三步:

1.从Git仓库下载代码文件

2.用maven打包下载好的代码文件

3.上传jar

解决方案:

1.利用eclipse提供的JGit工具包实现拉包,Java执行Windows/Linux脚本实现maven构建(Linux类似)

参考地址:https://github.com/eclipse/jgit

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;

public class GitTest {
    public static void main(String[] arg) {
        String url = "http://git.mrpei.com/peizhouyu/HelloTest.git";
        String localPath = "D:\\project\\";
        String branchName = "master";
        String username = "peizhouyu";
        String password = "123456.";
        try {
            
            //1. 克隆代码
            Git.cloneRepository()
                    .setURI(url).setBranch(branchName)
                    .setDirectory(new File(localPath))
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                    .call();

            //2.执行mvn打包 并等待命令执行完成
            String commond = "cmd /c d: && cd d:\\project && mvn clean package -Dmaven.test.skip=true";
            Process process = Runtime.getRuntime().exec(commond);
            process.waitFor();
            System.out.println("package finish");
            //3.上传文件服务 target文件夹 后缀 jar文件

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.经过阅读JGit源码发现JGit其实也是依靠本地安装的git工具来执行代码下载,所以我们可以直接通过命令调用本地Git工具实现(Linux类似)

public class LocalTest {

    public static void main(String[] args) {
        String url = "http://git.mrpei.com/peizhouyu/HelloTest.git";
        String localPath = "D:\\project\\";
        String branchName = "master";
        String username = "peizhouyu";
        String password = "123456.";
        String newUrl = "http://peizhouyu:123456.@git.jd.com/peizhouyu/HelloTest.git";
        try {
            //0.命令拼接
            String[] result = url.split("/");
            String projectName = result[result.length - 1].split("\\.")[0];
            System.out.println(projectName);
            //1. 克隆代码
            String cloneCommand = "cmd /c d: && cd d:\\project && git clone -b " + branchName + " " + result[0] + "//" + username + ":" + password + "@"
                    + result[2] + "/" + result[3] + "/" + result[4];
            System.out.println(cloneCommand);
            Process cloneProcess = Runtime.getRuntime().exec(cloneCommand);
            cloneProcess.waitFor();
            System.out.println("clone success");
            //2.执行mvn打包 并等待命令执行完成
            //String real = "cmd /c d: && cd d:\\project && git clone -b master http://peizhouyu:123456.@git.mrpei.com/peizhouyu/HelloTest.git && cd d:\\project\\HelloTest && mvn clean package -Dmaven.test.skip=true";
            String packageCommand = "cmd /c d: && cd d:\\project\\" + projectName + " && mvn clean package -Dmaven.test.skip=true";
            System.out.println(packageCommand);
            Process process = Runtime.getRuntime().exec(packageCommand);
            process.waitFor();
            System.out.println("package finish");
            //3.上传文件服务 target文件夹 后缀 jar文件

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

3.利用GitLab API 通过http来下载源码包,本地解压,调用maven命令编译。

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;



public class GitApiTest {

    private final static int BUFFER = 1048576;

    public static void main(String[] args) {
        String apiUrl = "http://git.xx.com/api/v4/projects/";
        String projectId = "11111";
        String branchName = "master";
        String privateToken = "c1EssB1213232ZAvTdL";
        String path = "D:\\project\\hello.tar.gz";
        String sourceFolder = "D:\\project\\hello";

        String projectDir = null;
        String url = apiUrl + projectId + "/repository/archive";
        System.out.println(url);

        Map<String,String> map = new HashMap<String, String>();
        map.put("private_token",privateToken);
        map.put("sha",branchName);
        HttpDownUtil.download("http://git.jd.com/api/v4/projects/30186/repository/archive",map,path);

        System.out.println("下载完成 开始解压");
//            unCompressArchiveGz(path);
        //解压
        File project = new File(path);
//        decompress(project, sourceFolder);
        try {
            unTarGz(project,sourceFolder);

            System.out.println("解压完成");
            //获取解压后的文件夹名(项目文件夹名)
            File[] unZipDirectoryArray = new File(sourceFolder).listFiles();
            for (int i = 0; i < unZipDirectoryArray.length; i++){
                if (unZipDirectoryArray[i].isDirectory()){
                    projectDir = unZipDirectoryArray[i].getAbsolutePath();
                    System.out.println(projectDir);
                }
            }
            //进入项目目录执行 mvn 构建
            System.out.println("开始执行mvn构建");

            //projectDir = "D:\\project\\hello\\HelloTest-master-2c25a3cb8bd88d90838cf07eff20bc652fffbe40";
            String commond = "cmd /c d: && cd " + projectDir +" && mvn clean package -Dmaven.test.skip=true";
            //String commond = "cmd /c d: && cd d:\\project\\hello\\HelloTest-master-8d0c483bf0837bf0bc66914e9d746e1d9af6bad8 && start mvn clean package -Dmaven.test.skip=true";
                System.out.println(commond);
            Process process = Runtime.getRuntime().exec(commond);
            //读取标准输出内容 防止输出缓冲区阻塞程序执行
            String str;
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()));
            while ( (str = bufferedReader.readLine()) !=null) {
                System.out.println(str);
            }
            process.waitFor();
            System.out.println("package finish");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unTarGz(File file,String outputDir) throws IOException{
        TarInputStream tarIn = null;
        try{
            tarIn = new TarInputStream(new GZIPInputStream(
                    new BufferedInputStream(new FileInputStream(file))),
                    1024 * 2);
            createDirectory(outputDir,null);//创建输出目录
            TarEntry entry = null;
            while( (entry = tarIn.getNextEntry()) != null ){
                if(entry.isDirectory()){//是目录
                    entry.getName();
                    createDirectory(outputDir,entry.getName());//创建空目录
                }else{//是文件
                    File tmpFile = new File(outputDir + "/" + entry.getName());
                    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
                    OutputStream out = null;
                    try{
                        out = new FileOutputStream(tmpFile);
                        int length = 0;

                        byte[] b = new byte[2048];

                        while((length = tarIn.read(b)) != -1){
                            out.write(b, 0, length);
                        }
                    }catch(IOException ex){
                        throw ex;
                    }finally{

                        if(out!=null)
                            out.close();
                    }
                }
            }
        }catch(IOException ex){
            throw new IOException("解压归档文件出现异常",ex);
        } finally{
            try{
                if(tarIn != null){
                    tarIn.close();
                }
            }catch(IOException ex){
                throw new IOException("关闭tarFile出现异常",ex);
            }
        }
    }
    public static void createDirectory(String outputDir,String subDir){
        File file = new File(outputDir);
        if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
            file = new File(outputDir + "/" + subDir);
        }
        if(!file.exists()){
            if(!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            file.mkdirs();
        }
    }

}

生成脚本文件 会增加磁盘I/O 不推荐

转载于:https://my.oschina.net/mrpei123/blog/1927835

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值