Commit be917537 authored by 雷明明's avatar 雷明明

创建项目

parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>gitserver</artifactId>
<version>1.0</version>
<name>gitserver</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.8.1.202007141445-r</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.example.gitserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GitserverApplication {
public static void main(String[] args) {
SpringApplication.run(GitserverApplication.class, args);
}
}
package com.example.gitserver.common;
public enum ResultCode {
/** 成功 */
SUCCESS("200", "成功"),
/** 操作失败 */
ERROR("500", "操作失败");
private ResultCode(String value, String msg){
this.val = value;
this.msg = msg;
}
public String val() {
return val;
}
public String msg() {
return msg;
}
private String val;
private String msg;
}
package com.example.gitserver.common;
import lombok.Data;
@Data
public class ResultData {
private String code;
private String msg;
private Object data;
public static ResultData success(String msg) {
return resultData(ResultCode.SUCCESS.val(),msg, null);
}
public static ResultData success(String msg,Object data) {
return resultData(ResultCode.SUCCESS.val(), msg, data);
}
public static ResultData fail(String code, String msg) {
return resultData(code, msg, null);
}
public static ResultData fail(String code, String msg, Object data) {
return resultData(code, msg, data);
}
private static ResultData resultData(String code, String msg, Object data) {
ResultData resultData = new ResultData();
resultData.setCode(code);
resultData.setMsg(msg);
resultData.setData(data);
return resultData;
}
}
package com.example.gitserver.controller;
import com.example.gitserver.common.ResultData;
import com.example.gitserver.service.GitService;
import com.example.gitserver.utils.GitUtil;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/git")
public class GitController {
Logger logger = LoggerFactory.getLogger(GitController.class);
@Autowired
private GitService gitService;
/* @RequestMapping("/pull")
public String pull(){
String localPath="D:/gitRepositry/dev";
String remotePath="http://git.mes123.com/root/zh-ws.git";
String username="leimingming";
String password="leiming2012";
GitUtil gitUtil=new GitUtil(localPath,remotePath,username,password);
// gitUtil.create();
try {
// gitUtil.pull("master");
// gitUtil.cloneRepository(remotePath,"dev",localPath,username,password);
// List<String> branchList= gitUtil.branchList("D:/gitRepositry/dev");
// System.out.println(branchList.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "ok";
}
*/
@GetMapping(value = "/clone",produces = {"application/json;charset=UTF-8"})
public ResultData clone(@RequestParam("remotePath") String remotePath,
@RequestParam("remotePath") String localPath,
@RequestParam("remotePath") String user,
@RequestParam("remotePath") String pwd,
@RequestParam(value = "remotePath",required = false) String branch){
//判断本地路径是否被占用
File file= GitUtil.initFile(localPath);
if(null==file){
return ResultData.fail("201","本地文件创建失败!!!");
}else{
try {
gitService.clone(remotePath,file,user,pwd,branch==null?"master":branch);
return ResultData.success("clone git 成功!");
} catch (GitAPIException e) {
logger.error("clone git 失败 !!!",e);
e.printStackTrace();
return ResultData.fail("202","clone git 失败 !!!");
}
}
}
@GetMapping(value = "/pull",produces = {"application/json;charset=UTF-8"})
public ResultData pull(@RequestParam("localPath") String localPath,
@RequestParam("branchName") String branchName,
@RequestParam("user") String user,
@RequestParam("pwd") String pwd){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
gitService.pull(localPath,branchName,user,pwd);
return ResultData.success(branchName+"分支拉取成功!");
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/checkout",produces = {"application/json;charset=UTF-8"})
public ResultData checkout(@RequestParam("localPath") String localPath,@RequestParam("branchName") String branchName){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
gitService.checkout(localPath,branchName);
return ResultData.success(branchName+"分支检出成功!");
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/getRemoteBranchList",produces = {"application/json;charset=UTF-8"})
public ResultData getRemoteBranchList(@RequestParam("localPath") String localPath){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
List<String> names= gitService.getRemoteBranchList(localPath);
return ResultData.success("获取成功!",names);
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/getLocalBranchList",produces = {"application/json;charset=UTF-8"})
public ResultData getLocalBranchList(@RequestParam("localPath") String localPath){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
List<String> names= gitService.getLocalBranchList(localPath);
return ResultData.success("获取成功!",names);
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/changeLocalBranch",produces = {"application/json;charset=UTF-8"})
public ResultData changeLocalBranch(@RequestParam("localPath") String localPath,@RequestParam("branchName") String branchName){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
gitService.changeLocalBranch(localPath,branchName);
return ResultData.success("切换成功!");
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/commit",produces = {"application/json;charset=UTF-8"})
public ResultData commit(@RequestParam("localPath") String localPath,
@RequestParam("branchName") String branchName,
@RequestParam("desc")String desc){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
gitService.changeLocalBranch(localPath,branchName);
gitService.commit(localPath,desc);
return ResultData.success("提交成功!");
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
@GetMapping(value = "/push",produces = {"application/json;charset=UTF-8"})
public ResultData push(@RequestParam("localPath") String localPath,
@RequestParam("branchName") String branchName,
@RequestParam("user") String user,
@RequestParam("pwd") String pwd){
//判断本地路径是否存在
File file= new File(localPath);
if(!file.exists()){
return ResultData.fail("201","本地文件路径不存在!!!");
}else{
try {
gitService.push(localPath,branchName,user,pwd);
return ResultData.success("提交远程仓库成功!");
} catch (GitAPIException | IOException e) {
logger.error("操作失败!!!",e);
e.printStackTrace();
return ResultData.fail("202","操作失败!!!");
}
}
}
}
package com.example.gitserver.service;
import com.example.gitserver.common.ResultData;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import java.io.File;
import java.io.IOException;
import java.util.List;
public interface GitService {
void clone(String remotePath, File localPath, String user, String pwd,String branch) throws GitAPIException;
List<String> getRemoteBranchList(String localPath) throws GitAPIException, IOException;
List<String> getLocalBranchList(String localPath) throws GitAPIException, IOException;
void pull(String localPath,String branchName,String user,String pwd) throws IOException, GitAPIException;
void checkout(String localPath,String branchName) throws IOException, GitAPIException;
Ref changeLocalBranch(String localPath, String branch) throws IOException, GitAPIException;
void commit(String localPath,String desc) throws IOException, GitAPIException;
void push(String localPath,String branch,String user,String pwd) throws IOException, GitAPIException;
}
package com.example.gitserver.service.impl;
import com.example.gitserver.common.ResultData;
import com.example.gitserver.service.GitService;
import com.example.gitserver.utils.GitUtil;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service("gitService")
public class GitServiceImpl implements GitService {
Logger logger= LoggerFactory.getLogger(GitServiceImpl.class);
@Override
public void clone(String remotePath, File localFile, String user, String pwd,String branch) throws GitAPIException {
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
try (Git git = Git.cloneRepository()
.setURI(remotePath)
.setBranch(branch)
.setDirectory(localFile)
.setCredentialsProvider(provider)
//.setProgressMonitor(new CloneProgressMonitor())
.call()){
}
}
@Override
public void pull(String localPath,String branchName,String user,String pwd) throws IOException, GitAPIException {
try(Git git = GitUtil.openGit(localPath)){
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
PullResult result= git.pull().setRemoteBranchName(branchName).setCredentialsProvider(provider).call();
logger.info(result.isSuccessful()+"...."+result.toString());
}
}
@Override
public void checkout(String localPath,String branchName) throws IOException, GitAPIException {
try(Git git = GitUtil.openGit(localPath)){
git.checkout().setCreateBranch(true).setName(branchName).setForced(true).call();
}
}
@Override
public List<String> getRemoteBranchList(String localPath) throws GitAPIException, IOException {
try (Git git = GitUtil.openGit(localPath)) {
List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
List<String> all = new ArrayList<>(list.size());
list.forEach(ref -> {
String name = ref.getName();
if (name.startsWith(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME)) {
all.add(name.substring((Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME).length() + 1));
}
});
return all;
}
}
@Override
public List<String> getLocalBranchList(String localPath) throws GitAPIException, IOException {
try (Git git = GitUtil.openGit(localPath)) {
List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
List<String> all = new ArrayList<>(list.size());
list.forEach(ref -> {
String name = ref.getName();
if (name.startsWith(Constants.R_HEADS)) {
all.add(name.substring((Constants.R_HEADS).length()));
}
});
return all;
}
}
@Override
public Ref changeLocalBranch(String localPath,String branch) throws IOException, GitAPIException {
try (Git git = GitUtil.openGit(localPath)) {
Ref ref = git.checkout().setCreateBranch(false).setName(branch).call();
return ref;
}
}
@Override
public void commit(String localPath,String desc) throws IOException, GitAPIException {
try (Git git = GitUtil.openGit(localPath)) {
git.add().addFilepattern(".").call();
RevCommit revCommit= git.commit().setAll(true).setMessage(desc).call();
logger.info(revCommit.getFullMessage()+".."+revCommit.getTree());
}
}
@Override
public void push(String localPath,String branch,String user,String pwd) throws IOException, GitAPIException {
try (Git git = GitUtil.openGit(localPath)) {
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
// Ref ref=changeLocalBranch(localPath,branch);
// git.push().add(ref).setCredentialsProvider(provider).call();
// git.push().setRemote("origin/"+branch)
// .setCredentialsProvider(provider).call();
Iterable<PushResult> list = git.push().setRemote("origin").add(branch).setCredentialsProvider(provider).call();
if(list != null) {
for(PushResult pr : list) {
logger.info(pr.getMessages());
}
}
}
}
}
package com.example.gitserver.utils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class GitUtil {
Logger log= LoggerFactory.getLogger(GitUtil.class);
private String localPath, localGitPath, remotePath;
private Repository localRepository;
private String username;
private String password;
private Git git;
public GitUtil(String localPath, String remotePath,String username ,String password) {
this.username = username;
this.password = password;
this.localPath = localPath;
this.remotePath = remotePath;
this.localGitPath = this.localPath + "/.git";
try {
localRepository = new FileRepository(localGitPath);
} catch (IOException e) {
e.printStackTrace();
}
git = new Git(localRepository);
}
/**
* 创建本地仓库
*
* @throws IOException
*/
public void create() throws IOException {
Repository repository = new FileRepository(localGitPath);
repository.create();
log.info("create success");
}
/**
* clone克隆远程分支到本地
*
* @param branchName
* @throws GitAPIException
*/
public void cloneBranch(String branchName) throws GitAPIException {
Git.cloneRepository()
.setURI(remotePath)
.setBranch(branchName)
.setDirectory(new File(localPath)).call();
log.info("clone success");
}
/**
* pull远程代码
*
* @param branchName 远程分支名称
* @throws Exception
*/
public void pull(String branchName) throws Exception {
git.pull().setRemoteBranchName(branchName).call();
log.info("pull success");
}
/**
* 将单个文件加入Git
*
* @param fileName 添加文件名
* @throws Exception
*/
public void add(String fileName) throws Exception {
File myFile = new File(localPath + fileName);
myFile.createNewFile();
git.add().addFilepattern(fileName).call();
log.info("add success");
}
/**
* 将增加的所有文件加入Git
*
* @throws Exception
*/
public void addAll() throws Exception {
git.add().addFilepattern(".").call();
log.info("add success");
}
/**
* 提交文件
*
* @param message 提交备注
* @throws Exception
*/
public void commit(String message) throws Exception {
git.commit().setMessage(message).call();
log.info("commit success");
}
/**
* 同步远程仓库
*
* @throws Exception
*/
public void push() throws Exception {
git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(this.username, this.password)).call();
log.info("push success");
}
public void checkOutBranch(String localPath) throws IOException {
//- refs/heads/test refs/remotes/origin/dev_test_dev02 refs/remotes/origin/test
// Git git =this.openGit(localPath);
try {
Git git = Git.open(new File("E:/repo"));
List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();//ALL -a 所有分支 REMOTE -r 远程分支
System.out.println(list);
//切换远端分支
// Ref ref= git.checkout().setCreateBranch(true)//创建新分支
// .setName("dev_test_dev02")
// .setStartPoint("origin/dev_test_dev02")//对应于起点选项
// .call();
// System.out.println(ref);
//切换本地分支
Ref ref = git.checkout().setCreateBranch(false).setName("test").call();
System.out.println(ref);
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 获取分支集合
* @param localPath
* @return
* @throws GitAPIException
* @throws IOException
*/
/* public List<String> branchList(String localPath) throws GitAPIException, IOException {
try (Git git = openGit(localPath)) {
List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
List<String> all = new ArrayList<>(list.size());
list.forEach(ref -> {
String name = ref.getName();
if (name.startsWith(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME)) {
all.add(name.substring((Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME).length() + 1));
}
});
return all;
} catch (TransportException t) {
t.printStackTrace();
throw t;
}
}*/
/**
* clone代码到本地仓库
* @param remoteUrl 远程路径
* @param branch 分支名称
* @param projectPath 本地文件路径
* @param user 用户名称
* @param pwd 密码
* @return
* @throws InvalidRemoteException
* @throws TransportException
* @throws GitAPIException
*/
/* public boolean cloneRepository(String remoteUrl, String branch, String projectPath, String user, String pwd) throws InvalidRemoteException, TransportException, GitAPIException {
File projectDir = new File(projectPath);
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
try (Git git = Git.cloneRepository()
.setURI(remoteUrl)
.setBranch(branch)
.setDirectory(projectDir)
.setCredentialsProvider(provider)
//.setProgressMonitor(new CloneProgressMonitor())
.call()) {
}
return true;
}
*/
/**
* 初始化git
* @param remotePath
* @param localPath
* @param username
* @param password
* @param branch
* @return
* @throws GitAPIException
* @throws IOException
*/
/* private Git initGit(String remotePath, String localPath, String username,String password,String branch) throws GitAPIException, IOException {
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(username, password);
createLocalRepo(localPath);
Git git =null;
if (!new File(localPath +"/"+ ".git").exists()) {
git= Git.cloneRepository().setCredentialsProvider(provider).setURI(remotePath).setBranch(branch)
.setDirectory(new File(localPath)).call();
}else{
git= Git.open( new File(localPath));
}
return git;
}*/
public static Git openGit(String localPath) throws IOException {
Git git = new Git(new FileRepository(localPath + "/.git"));
return git;
}
public static File initFile(String filePath){
File file = new File(filePath);
if(! file.exists()){
file.mkdirs();
return file;
}
return null;
}
}
package com.example.gitserver;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GitserverApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment