准备工作
1-本地安装Git
2-搭建Gitlab私服
3-创建项目并上传源代码
获取所有项目API
http://your-gitlab-server//api/v4/projects
--每页显示150个项目
http://your-gitlab-server//api/v4/projects?per_page=150
返回json格式的数据,注意默认显示每页20行数据,可以增加参数?per_page=150获取更多的项目
如果有做token安全限制需要增加相关的token参数
获取项目列表后存储为本地JSON,利用java代码生成下载的命令,调用Process 执行下载命令
java代码下载
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Iterator;
import org.springframework.util.StreamUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestGitlabData {
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String fileName="E:\\gitlab_projects.json";
String jsonStr=readJsonFile(fileName);
JSONArray projects=JSON.parseArray(jsonStr);
//指定需要下载的分支
String branchName="devp";
//指定下载后输出的地址
String srcDir="E:\\prj\\src";
File execDir = new File(srcDir);
for (Iterator iterator = projects.iterator(); iterator.hasNext();) {
JSONObject prj = (JSONObject) iterator.next();
//项目地址
String httpUrlToRepo=prj.getString("http_url_to_repo");
//项目路径
String pathWithNamespace=prj.getString("path_with_namespace");
gitClone(branchName,httpUrlToRepo,pathWithNamespace,execDir);
}
}
static void gitClone(String branchName, String httpUrlToRepo,String pathWithNamespace, File execDir) {
String command = String.format("git clone -b %s %s %s", branchName, httpUrlToRepo, pathWithNamespace);
try {
System.out.println("===========start==================");
System.out.println("start exec command : " + command);
//执行命令行
Process exec = Runtime.getRuntime().exec(command, null, execDir);
exec.waitFor();
String successResult = StreamUtils.copyToString(exec.getInputStream(), Charset.forName("UTF-8"));
String errorResult = StreamUtils.copyToString(exec.getErrorStream(),Charset.forName("UTF-8"));
System.out.println("successResult: " + successResult);
System.out.println("errorResult: " + errorResult);
System.out.println("============end================");
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 可优化,考虑直接利用httpclient工具类直接访问GitLab API获取项目列表
网友评论