方法一

1、app/build.gradle添加任务去解析配置依赖,本人使用的是gradle 7.0.1版本,不同版本差异比较大。

task listAllDependencies {
    doLast {
        configurations.each { config ->
            println "Configuration: ${config.name}"
            config.allDependencies.each { dep ->
                println "---- ${dep.group}:${dep.name}:${dep.version}"
            }
            try {
                copyJars(config)
            } catch (Exception e) {
                e.printStackTrace()
            }
            try {
                copyPoms(config)
            } catch (Exception e) {
                e.printStackTrace()
            }


        }
    }
}


private void copyJars(Configuration configuration) {

    if (!configuration.canBeResolved) {
        return
    }
    def repoDir = new File(project.buildDir, 'offline-repo')
    configuration.resolvedConfiguration.resolvedArtifacts.each { artifact ->
        def moduleVersionId = artifact.moduleVersion.id
        print("artifact name=${artifact.name}  type=${artifact.type} path=${artifact.file.absolutePath}")
        File moduleDir = new File(repoDir, "${moduleVersionId.group.replace('.','/')}/${moduleVersionId.name}/${moduleVersionId.version}")
        if (!moduleDir.exists()) {
            moduleDir.mkdirs()
        }
        copy {
            from artifact.file.absolutePath
            into new File(moduleDir, artifact.file.name).absolutePath
        }

    }
}

private void copyPoms(Configuration configuration) {
    if (!configuration.canBeResolved) {
        return
    }


    def repoDir = new File(project.buildDir, 'offline-repo')

    try {
        def componentIds = configuration.incoming.resolutionResult.allDependencies.collect { it.selected.id }
        def result = project.dependencies.createArtifactResolutionQuery()
                .forComponents(componentIds)
                .withArtifacts(MavenModule, MavenPomArtifact)
                .execute()
        for(component in result.resolvedComponents) {
            def componentId = component.id

            if(componentId instanceof ModuleComponentIdentifier) {
                print("pom ${componentId.group}:${componentId.module}:${componentId.version}")
                File moduleDir = new File(repoDir, "${componentId.group.replace('.','/')}/${componentId.module}/${componentId.version}")
                if (!moduleDir.exists()) {
                    moduleDir.mkdirs()
                }
                File pomFile = component.getArtifacts(MavenPomArtifact)[0].file
                copy {
                    from pomFile.absolutePath
                    into new File(moduleDir, pomFile.name).absolutePath
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace()
    }

}

2、针对编译插件,根目录/build.gradle中声明的插件

./gradlew buildEnvironment 可以输出依赖关系,根据关系去对应编译构件。

方法二

需要按maven的仓库格式创建pom文件,如果有就拷贝,没有则需要创建一个。脚本如下

package com.suyxin;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GradleDpToMaven {
    static String gradleCacheDir = "C:\\Users\\Administrator\\.gradle\\caches\\modules-2\\files-2.1\\";
    static String copyDir = "D:\\repoCopyGradle\\";
    static ExecutorService executor = Executors.newFixedThreadPool(64);
    static ExecutorService deleteExecutor = Executors.newFixedThreadPool(64);
    static HashSet<String> artifactVersionSet = new HashSet();
    static HashSet<String> artifactPomSet = new HashSet();

    public static void main(String[] args) {
        //compareSingleVersion
//        System.out.println(compareVersion("1.0.358-16456","1.0.358-abdasdfs"));
//        System.out.println(compareVersion("1.0.3","1.0.4"));
//        System.out.println(compareVersion("1.0.5","1.0"));


        long start = System.currentTimeMillis();
        try {
            deleteFile(new File(copyDir), 0);
            deleteExecutor.shutdown();
            deleteExecutor.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            loopFiles(new File(gradleCacheDir), 0);
            executor.shutdown();
            executor.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("cost " + (System.currentTimeMillis() - start) + " ms");
        }

        Iterator<String> it = artifactPomSet.iterator();
        while (it.hasNext()) {
            String versionDp = it.next();
            artifactVersionSet.remove(versionDp);
        }
        Iterator<String> notHadPomIt = artifactVersionSet.iterator();
        while (notHadPomIt.hasNext()) {
            System.out.println("not had pom " + notHadPomIt.next());
        }


//        createPomMd5();


    }

    public static void createPomMd5() {
        String path = "";
        File file = new File(path);
        try {
            writeStringFile(getFileMD5(file), path + ".md5");
            writeStringFile(getFileSha1(file), path + ".sha1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 先根遍历序递归删除文件夹
     *
     * @param dirFile 要被删除的文件或者目录
     * @return 删除成功返回true, 否则返回false
     */
    public static void  deleteFile(File dirFile, int index) {
        // 如果dir对应的文件不存在,则退出
        if (!dirFile.exists()) {
            return ;
        }

        if (dirFile.isFile()) {
            deleteExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    dirFile.delete();
                }
            });
        } else {
            for (File file : dirFile.listFiles()) {
                deleteFile(file, index + 1);
            }
        }

    }

    public static List<File> loopFiles(File file, int index) {
        List<File> fileList = new ArrayList<>();
        if (!file.exists()) {
            return fileList;
        }
        if (file.isDirectory()) {
            File[] lists = file.listFiles();
            if (lists == null || lists.length <= 0) {
                return fileList;
            }
            String[] path = file.getAbsolutePath().replace(gradleCacheDir, "").split("\\\\");
            if (index == 2 && path.length > 1) { //遍历到artifact构建,需要创建metal.xml
                List<String> versionList = new ArrayList<>();
                String groupName = path[0];
                String artifactName = path[1];

                for (int i = 0; i < lists.length; i++) {
                    String versionName = lists[i].getName();
                    versionList.add(versionName);
                    //每个version下面所有文件。
                    List<File> sourceFileList = loopFiles(lists[i], index + 1);
                    String newDirPath = copyDir + groupName.replace(".", File.separator) + File.separator + artifactName + File.separator + versionName + File.separator;
                    File newDir = new File(newDirPath);
                    if (!newDir.exists()) {
                        newDir.mkdirs();
                    }
                    boolean hadPomFile = false;
                    for (int j = 0; j < sourceFileList.size(); j++) {
                        File sourceFile = sourceFileList.get(j);
                        String sourceFileName = sourceFile.getName();
                        if (sourceFileName.endsWith(".pom")) {
                            hadPomFile = true;
                        }

                        executor.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
//                                    System.out.println("copy to  start " + groupName + ":" + artifactName + ":" + versionName + ":" + sourceFileName);
                                    File targetFile = new File(newDirPath + sourceFileName);
                                    if (targetFile.exists()) {
                                        targetFile.delete();
                                    }
                                    copyFileUsingFileStreams(sourceFile, targetFile);
                                    writeStringFile(getFileMD5(sourceFile), newDirPath + sourceFileName + ".md5");
                                    writeStringFile(getFileSha1(sourceFile), newDirPath + sourceFileName + ".sha1");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
//                                    System.out.println("------end copy " + groupName + ":" + artifactName + ":" + versionName + ":" + sourceFileName);
                                }
                            }
                        });
                    }

                    if (!hadPomFile) {
                        executor.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    writePomFile(newDirPath, groupName, artifactName, versionName);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                }
                if (!versionList.isEmpty()) {
                    String metaDirPath = copyDir + groupName.replace(".", File.separator) + File.separator + artifactName + File.separator;
                    File dir = new File(metaDirPath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                writeMavenMetalXml(metaDirPath, groupName, artifactName, versionList);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } else {
                for (int i = 0; i < lists.length; i++) {
                    fileList.addAll(loopFiles(lists[i], index + 1));
                }
            }
        } else { //遍历到我们想要的文件了。
            if (file.getName().endsWith(".jar") || file.getName().endsWith(".aar") || file.getName().endsWith(".pom")) {
                fileList.add(file);
            }
        }
        return fileList;

    }




    public static int compareSingleVersion(String v1, String v2){
        if (v1.equals(v2)) {
            return 0;
        }
        long diff = 0;
        try {
            if (isNumeric(v1) && isNumeric(v2)) {
                diff = Long.parseLong(v1)
                        - Long.parseLong(v2);
            }else{
                diff =  v1.compareTo(v2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //20180820090554比abdasdfs 数字和非数字比较,只能比字符串
            diff =  v1.compareTo(v2);
        }
        return diff > 0 ? 1 : -1;
    }
    /**
     * 版本号比较
     *
     * @param v1
     * @param v2
     * @return 0代表相等,1代表左边大,-1代表右边大
     * 1.132.343  2.a.b
     * Utils.compareVersion("1.0-20180820090554","1.0.358-abdasdfs")=1
     */
    public static int compareVersion(String v1, String v2) {
        if (v1.equals(v2)) {
            return 0;
        }
        String[] versionDot1  = v1.split("-");
        String[] versionDot2  = v2.split("-");
        String[] version1Array = versionDot1[0].split("[.]");
        String[] version2Array = versionDot2[0].split("[.]");
        int index = 0;
        int minLen = Math.min(version1Array.length, version2Array.length);
        long diff = 0;

        //纯数字
        while (index < minLen
                && (diff = compareSingleVersion(version1Array[index],version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {

            for (int i = index; i < version1Array.length; i++) {
//                if (Long.parseLong(version1Array[i]) > 0) {
                return 1;
//                }
            }

            for (int i = index; i < version2Array.length; i++) {
//                if (Long.parseLong(version2Array[i]) > 0) {
                return -1;
//                }
            }

            if(versionDot1.length>1 && versionDot2.length>1){
                diff =  compareSingleVersion(versionDot1[1],versionDot2[1]);
            }
            if (diff != 0) {
                return diff > 0 ? 1 : -1;
            }
            if(versionDot1.length>1){
                return 1;
            }
            if(versionDot2.length>1){
                return -1;
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    public static boolean isNumeric(String str) {
        //Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//这个也行
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * <?xml version="1.0" encoding="UTF-8"?>
     * <metadata>
     * <groupId>com.ssabc.webviewinject</groupId>
     * <artifactId>webviewInject</artifactId>
     * <versioning>
     * <latest>1.0.2</latest>
     * <release>1.0.2</release>
     * <versions>
     * <version>1.0.0</version>
     * <version>1.0.2</version>
     * </versions>
     * <lastUpdated>20241023061856</lastUpdated>
     * </versioning>
     * </metadata>
     */

    public static String formatStr = "yyyyMMddHHmmss";

    public static String formatToYYYYMMDDHHMMSS(Date date) {
        DateFormat dateFormat = new SimpleDateFormat(formatStr);
        return dateFormat.format(date);
    }

    private static void writeMavenMetalXml(String metaDirPath, String groupName, String artifactName, List<String> versionList) throws Exception {
        StringBuilder sb = new StringBuilder();
        Collections.sort(versionList, new Comparator<String>() {
            @Override
            public int compare(String version1, String version2) {
                return compareVersion(version1, version2);
            }
        });
        String latestVersion = versionList.get(versionList.size() - 1);
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
                .append("<metadata>\n")
                .append(" <groupId>").append(groupName).append("</groupId>\n")
                .append(" <artifactId>").append(artifactName).append("</artifactId>\n")
                .append(" <versioning>\n")
                .append("  <latest>").append(latestVersion).append("</latest>\n")
                .append("  <release>").append(latestVersion).append("</release>\n");
        sb.append("    <versions>\n");
        for (int i = 0; i < versionList.size(); i++) {
            sb.append("     <version>").append(versionList.get(i)).append("</version>\n");
        }
        sb.append("    </versions>\n")
                .append("   <lastUpdated>").append(formatToYYYYMMDDHHMMSS(new Date())).append("</lastUpdated>\n")
                .append("  </versioning>\n")
                .append("</metadata>");
        String metaXmlPath = metaDirPath + "maven-metadata.xml";
        writeStringFile(sb.toString(), metaXmlPath);
        File metaXmlFile = new File(metaXmlPath);
        writeStringFile(getFileMD5(metaXmlFile), metaXmlPath + ".md5");
        writeStringFile(getFileSha1(metaXmlFile), metaXmlPath + ".sha1");
    }

    private static void writeStringFile(String content, String path) throws Exception {

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        new FileOutputStream(file.getAbsolutePath()).write(content.getBytes(StandardCharsets.UTF_8));

    }

    /**
     * <?xml version="1.0" encoding="UTF-8"?>
     * <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
     *     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     *   <modelVersion>4.0.0</modelVersion>
     *   <groupId>com.abc.plugin.haha</groupId>
     *   <artifactId>plugin</artifactId>
     *   <version>0.0.3</version>
     *
     * </project>
     */
    private static void writePomFile(String dirPath,String groupName,String artifactId,String version) throws Exception{
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
                .append("<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n")
                .append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n")
                .append(" <modelVersion>4.0.0</modelVersion>\n")
                .append(" <groupId>").append(groupName).append("</groupId>\n")
                .append(" <artifactId>").append(artifactId).append("</artifactId>\n")
                .append(" <version>").append(version).append("</version>\n")
                .append(" </project>");
        String pomFilePath = dirPath + artifactId+"-"+version+".pom";

        System.out.println("writePomFile " + pomFilePath);
        writeStringFile(sb.toString(), pomFilePath);
        File pomFile = new File(pomFilePath);
        writeStringFile(getFileMD5(pomFile), pomFilePath + ".md5");
        writeStringFile(getFileSha1(pomFile), pomFilePath + ".sha1");
    }

    private static void copyFileUsingFileStreams(File source, File dest) {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static String getFileMD5(File file) throws NoSuchAlgorithmException, IOException {
        MessageDigest md5Digest = MessageDigest.getInstance("MD5");
        Path filePath = Paths.get(file.getAbsolutePath());
        byte[] fileBytes = Files.readAllBytes(filePath);
        byte[] digest = md5Digest.digest(fileBytes);
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static String getFileSha1(File file) throws NoSuchAlgorithmException, IOException {
        MessageDigest md5Digest = MessageDigest.getInstance("SHA-1");
        Path filePath = Paths.get(file.getAbsolutePath());
        byte[] fileBytes = Files.readAllBytes(filePath);
        byte[] digest = md5Digest.digest(fileBytes);
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐