gitLab 工具类

gitLab 工具类:
Java 通过api操作gitLab

maven

		<!--gitlab api-->
		<dependency>
			<groupId>org.gitlab4j</groupId>
			<artifactId>gitlab4j-api</artifactId>
			<version>5.0.1</version>
		</dependency>


		<dependency>
			<groupId>org.eclipse.jgit</groupId>
			<artifactId>org.eclipse.jgit</artifactId>
			<version>5.13.0.202109080827-r</version>
		</dependency>


import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.lib.Ref;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.Pager;
import org.gitlab4j.api.models.*;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;


/**
 * gitLab 工具类
 */
public class test2 {

    //项目
    private static final String project_name="newproject06";
    //定义本地git路径
//    public static final String LOCALPATH = "D:/git/zcnewproject/";

    public static final String LOCALPATH = "D:/git/"+project_name+"/";
    //.git文件路径
    public static final String LOCALGITFILE = LOCALPATH + ".git";
    //远程仓库地址
    public static final String REMOTEREPOURI = "http://11.11.111.1111/lowCode/"+project_name+".git";
    //操作git的用户名
    public static final String USER = "1464920111@qq.com";
    //密码
    public static final String PASSWORD = "zc@75911111";

    //git地址
    private static final String GITLAB_URL = "http://11.11.111.1111/";
    //token
    private static final String PRIVATE_TOKEN = "isGistWL-11111111-d";
    //u-zxvJaD7HsiUYK5xPCH

    //群组code
    private static final String NAME_SPACE="lowCode";

    //默认分支
    private static final String branchName = "master";


    public static void main(String[] args) throws GitLabApiException {
//        Project project = createdProject(project_name);
//        System.out.println("main:"+project.getId());
//        String BranchName = "zc05";
//        createBranch(project,BranchName);
//        setupRepo();
//        pullBranchToLocal();
//        commitFilesToBranch(BranchName);

        addUserToProject("cicd",project_name,AccessLevel.MAINTAINER);
    }


    /**
     * 分页获取用户信息
     * @param gitLabApi
     * @param itemsPerPage
     * @return
     * @throws GitLabApiException
     */
    public static Pager<User> getUser(GitLabApi gitLabApi, int itemsPerPage) throws GitLabApiException {
      return  gitLabApi.getUserApi().getUsers(itemsPerPage);
    }
    /**
     * 通过用户名称查询用户
     * @param gitLabApi
     * @param username
     * @return
     */
    public static User findUserIdByUsername(GitLabApi gitLabApi, String username) {
        User user = null;
        try {
             user =gitLabApi.getUserApi().getUser(username);
        } catch (Exception e) {
            System.err.println("Error finding user ID: " + e.getMessage());
        }
        return user; // 如果没有找到用户,则返回-1或任何表示未找到的值
    }


    /**
     * 项目添加用户
     * @param username
     * @param projectName
     * @param accessLevel
     */
    public static void addUserToProject(String username, String projectName, AccessLevel accessLevel) {
        try (GitLabApi gitLabApi = new GitLabApi(GITLAB_URL, PRIVATE_TOKEN)) {
            User user = findUserIdByUsername(gitLabApi,username);
            if(user != null){
                // 将用户添加到项目并设置权限
                gitLabApi.getProjectApi().updateMember(NAME_SPACE+"/"+projectName, Long.valueOf(user.getId()),accessLevel);
            }
        } catch (Exception e) {
            System.err.println("Error adding user to project: " + e.getMessage());
        }
    }



    //建立与远程仓库的联系,仅需要执行一次
    public static String setupRepo() {
        String msg = "";
        try {
            Git git = Git.cloneRepository().setURI(REMOTEREPOURI)
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD)).setBranch("master")
                    .setDirectory(new File(LOCALPATH)).call();
            msg = "git init success!";
            System.out.println("setupRepo: "+msg);
        } catch (Exception e) {
            msg = "git已经初始化!";
            System.out.println("setupRepo: "+msg);
        }

        return msg;
    }
    //pull拉取远程仓库文件
    public static boolean pullBranchToLocal(){
        boolean resultFlag = false;
        //git仓库地址
        Git git;
        try {
            git = new Git(new FileRepository(LOCALGITFILE));
            git.pull().setRemoteBranchName("master")
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER,PASSWORD)).call();
            resultFlag = true;
        } catch (IOException | GitAPIException e) {
            e.printStackTrace();
        }
        return resultFlag;
    }
    //提交git
//    public static boolean commitFiles() {
//        Git git = null;
//        try {
//            git = Git.open(new File(LOCALGITFILE));
//            AddCommand addCommand = git.add();
//
//            //add操作 add -A操作在jgit不知道怎么用 没有尝试出来 有兴趣的可以看下jgitAPI研究一下 欢迎留言
//            addCommand.addFilepattern(".").call();
//
//            RmCommand rm=git.rm();
//            Status status=git.status().call();
//
//            //循环add missing 的文件 没研究出missing和remove的区别 就是删除的文件也要提交到git
//            Set<String> missing=status.getMissing();
//            for(String m : missing){
//                System.out.println("missing files: "+m);
//                rm.addFilepattern(m).call();
//
//                //每次需重新获取rm status 不然会报错
//                rm=git.rm();
//                status=git.status().call();
//            }
//            //循环add remove 的文件
//            Set<String> removed=status.getRemoved();
//            for(String r : removed){
//                System.out.println("removed files: "+r);
//                rm.addFilepattern(r).call();
//                rm=git.rm();
//                status=git.status().call();
//            }
//
//            //提交
//            git.commit()
//                    .setMessage("commit").call();
//            //推送
//            git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD)).call();
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }



    /**
     * 创建分支
     * @param branchNameNew
     * @return
     * @throws GitLabApiException
     */
    public static void createBranch(Project createdProject ,String branchNameNew) throws GitLabApiException {
        GitLabApi gitLabApi = new GitLabApi(GITLAB_URL, PRIVATE_TOKEN);
        Branch branch = null;
        try {
            // 判断分支是否存在
            branch = gitLabApi.getRepositoryApi().getBranch(createdProject.getId(), branchNameNew);
        } catch (GitLabApiException e) {
            if(e.getHttpStatus()==404){
                System.err.println("Error-isRemoteBranchExists : " + e.getMessage());
                //TODO
            }

        }
        if(branch == null){
            gitLabApi.getRepositoryApi().createBranch(createdProject.getId(), branchNameNew, branchName);
        }

    }

    /**
     * 创建项目
     * @param projectName
     * @return
     * @throws GitLabApiException
     */
    public static Project createdProject(String projectName) throws GitLabApiException {
        GitLabApi gitLabApi = new GitLabApi(GITLAB_URL, PRIVATE_TOKEN);
        // 判断项目是否存在

        Project createdProject = null;
        try {
            // 判断项目是否存在
            createdProject = gitLabApi.getProjectApi().getProject(NAME_SPACE+"/"+projectName);
        } catch (GitLabApiException e) {
            if(e.getHttpStatus()==404){
                System.out.println("Error : " + e.getMessage());
                //TODO
            }

        }
        if(createdProject== null){
            // 创建项目
            Project project = new Project();
            project.setName(projectName);
            project.setDescription("A new project created by Java API");
            project.setNamespace(new Namespace().withId(295L)); // 设置命名空间ID(替换为实际的命名空间ID)
            project.setDefaultBranch("master"); // 可选,默认分支名
            project.setVisibility(Visibility.INTERNAL); // 或其他可见性级别:PUBLIC、PRIVATE
            createdProject = gitLabApi.getProjectApi().createProject(project);
            System.out.println("Created project: " + createdProject.getPathWithNamespace());
        }
        return createdProject;
    }

    /**
     * // 判断本地是否存在branchName分支
     * @param git
     * @param branchName
     * @return
     */
    public static boolean isLocalBranchExists(Git git, String branchName) {
        try {
            // 获取本地分支列表
            List<Ref> branches = git.branchList().call();

            // 遍历分支列表,查找指定名称的分支
            for (Ref ref : branches) {
                if (ref.getName().endsWith("/" + branchName)) {
                    return true;
                }
            }
        } catch (GitAPIException e) {
            System.err.println("Error occurred while checking local branches: " + e.getMessage());
        }

        return false;
    }


    /**
     * //提交git
     * @param branchName
     * @return
     */
    public static boolean commitFilesToBranch(String branchName) {
        Git git = null;
        try {
            git = Git.open(new File(LOCALGITFILE));

            git.fetch().setRemote("origin") .setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD)).call();
            boolean isLocalBranchExists = isLocalBranchExists(git,branchName);
            if(!isLocalBranchExists){
                git.branchCreate().setName(branchName).setStartPoint("origin/"+branchName).call();
                System.out.println("commitFilesToBranch:将"+branchName+"拉到本地仓库");
            }


            // 检查并切换到目标分支(假设它已经存在)
            CheckoutCommand checkoutCommand = git.checkout();
            checkoutCommand.setName(branchName);

            try {
                checkoutCommand.call();
            } catch (CheckoutConflictException e) {
                System.out.println("Checkout conflict occurred. Resolving conflicts by keeping local changes...");

                // 获取冲突文件列表
                List<String> conflictingFiles = e.getConflictingPaths();

                for (String filePath : conflictingFiles) {
                    try {
                        // 删除暂存区中的文件版本(即目标分支的版本)
                        git.rm().addFilepattern(filePath).call();
                        // 将工作目录中的文件添加到暂存区,相当于选择了本地版本
                        git.add().addFilepattern(filePath).call();
                    } catch (GitAPIException ex) {
                        System.err.println("Error while resolving conflict for file " + filePath + ": " + ex.getMessage());
                    }
                }

                // 再次尝试切换分支
                checkoutCommand.call();
            }

            AddCommand addCommand = git.add();
            addCommand.addFilepattern(".").call();

            RmCommand rm = git.rm();
            Status status = git.status().call();

            Set<String> missing = status.getMissing();
            for (String m : missing) {
                System.out.println("missing files: " + m);
                rm.addFilepattern(m).call();
                rm = git.rm();
                status = git.status().call();
            }

            Set<String> removed = status.getRemoved();
            for (String r : removed) {
                System.out.println("removed files: " + r);
                rm.addFilepattern(r).call();
                rm = git.rm();
                status = git.status().call();
            }

            git.commit()
                    .setMessage("commit to branch " + branchName).call();

            // 推送到远程仓库的对应分支
            RefSpec refSpec = new RefSpec("HEAD:refs/heads/" + branchName);
            git.push()
                    .setRemote("origin")
                    .setRefSpecs(refSpec)
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD))
                    .call();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值