介绍

由于我尝试在 Java 中使用 Gitlab 的 API,我将简要介绍如何使用它。
本次使用的API如下。

  • 问题API
  • 存储库API
  • RepositoryFileApi

执行环境如下。

Gitlab : 14.9.4
Java : 1.8

提前准备

这次我使用 gradle 创建了一个 Java 项目。
API 执行是gitlab4j-api用过的。

build.gradle 如下。

apply plugin: "java"

repositories {
  mavenCentral()
}

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
compileJava.options.encoding = 'UTF-8'

dependencies {
  implementation "org.gitlab4j:gitlab4j-api:5.0.1"
}

由于访问令牌用于执行 API,请检查以下内容以了解如何创建它。

易于实施

这是一个简单的实现。

获取 GitLabApi 实例

各种 API 通过 GitlabApi 实例执行。获取实例需要访问令牌。

// GitLabApiインスタンスの取得
GitLabApi gitLabApi = new GitLabApi("http://sample.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN");

在后续实现中,从GitLabApi获取你要操作的API并进行操作。

问题 API

获取问题列表

获取特定项目中提出的问题列表。

// プロジェクトに起票されたIssueをすべて取得する(プロジェクトID=1234)
List<Issue> issueList = gitLabApi.getIssuesApi().getIssues("1234");

// Issueのタイトルを出力
for (Issue issue : issueList) {
    System.out.println(issue.getTitle());
}

创建问题

为指定项目提出问题。可以指定的选项有很多,但是这里我们指定以下,其他的不指定(null)。

  • 项目
  • 标题
  • 说明
  • 标签

我将在描述中包含一个 Markdown 格式表。

// Issueの起票(プロジェクトID=1234)
gitLabApi.getIssuesApi().createIssue(//
        "1234", // ProjectId
        "GitlabAPI sample issue", // Title
        getDescription(), // Description
        null,
        null,
        null,
        "sample_label", // Label
        null,
        null,
        null,
        null
);

String getDescription() {
    StringBuffer sb = new StringBuffer();
    sb.append("# Overview");
    sb.append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("|COLUMN1|COLUMN2|COLUMN3|");
    sb.append(System.lineSeparator());
    sb.append("|---|---|---|");
    sb.append(System.lineSeparator());
    sb.append("|hoge|fuga|piyo|");
    sb.append("|---|---|---|");
    sb.append(System.lineSeparator());
    sb.append("|foo|bar|baz|");
    return sb.toString();
}

将提出如下问题。在这种情况下,API 的草稿中似乎可以包含各种信息。

JavaでGitlab APIを利用してみた

存储库 API

RepositoryApi 主要可以操作Branch。

// Branchの一覧を取得(プロジェクトID=1234)
List<Branch> branchList = gitLabApi.getRepositoryApi().getBranches("1234");

for (Branch branch : branchList) {
    System.out.println(branch.getName());
}

// Branchを保護する(プロジェクトID=1234)
gitLabApi.getRepositoryApi().protectBranch("1234", "YOUR_BRANCH_NAME");

// Branchの保護の解除(プロジェクトID=1234)
gitLabApi.getRepositoryApi().unprotectBranch("1234", "YOUR_BRANCH_NAME");

存储库文件 API

RepositoryFileApi 似乎是一个用于操作由存储库管理的文件的 API。
在这里,我们将在main 分支的qiita/test/ 下方得到hoge.txt

// hoge.txtを取得(プロジェクトID=1234)
File file = gitLabApi.getRepositoryApi().getRawFile("1234", "main", "qiita/test/hoge.txt", null);

System.out.println(file.getName()); // hoge.txt

在最后

这次我处理了IssuesApi、RepositoryApi和RepositoryFileApi,但似乎还有其他有用的API。
如果我可以使用shell命令来操作各种东西会更容易,但我不擅长它,所以java API非常有用。


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308629444.html

相关文章: