Skip to content

Latest commit

 

History

History

gitlab

README.md

adm.dev.gitlab

A GitLab API client in ADM over std.net.http: REST and GraphQL, webhooks, and the tokens GitLab issues to people, projects, groups and CI jobs. Self-managed instances work through a base URL.

adm get admlang:adm.dev.gitlab
use adm.dev.gitlab

let gl = try gitlab.connect(token, url = "https://gitlab.example.com")   // GITLAB_TOKEN, gitlab.com when left out
let project = gl.project("group/app")
for let mr in try project.mergeRequests.list(state = gitlab.State.Opened).all() {
	print("!{mr.iid} {mr.title}")
}
let pipeline = try project.pipelines.create("main", variables = {"DEPLOY": "staging"})

Tokens

connect sends a personal, project or group access token as PRIVATE-TOKEN. In a CI job with no token given it takes CI_JOB_TOKEN (sent as JOB-TOKEN) and CI_SERVER_URL. An OAuth token goes as a bearer token; gitlab.oauthClient is the OAuth client of the web flow.

let job = try gitlab.connect()                    // GITLAB_TOKEN, else the CI job's token
let oauth = try gitlab.connect(accessToken, kind = gitlab.TokenKind.OAuth)

REST

Every operation of projects, groups, users, issues, merge requests (approvals, notes, discussions, diffs, merges), commits and statuses, branches, tags and their protection, pipelines, jobs and artifacts, CI variables, releases, packages and the container registry, snippets, labels, milestones and search is a method on the object its path names: the client (gl.projects, gl.groups, gl.users), a project (gl.project("group/app") or by ID), a group, a user or the signed-in user (gl.me), and the collections under them. Required parameters come first, the others are named and left out when not given. A list re-read every sync round asks with the ETag of its last answer: pages.ifChanged(etag) is none when GitLab answers 304, else the page with the ETag to keep (PageUpdate).

let mr = try project.mergeRequests.create("Add geo examples", "feature", "main", removeSourceBranch = true)
try project.mergeRequests.createNote(mr.iid, "Ready for review")
try project.mergeRequests.approve(mr.iid)
try project.mergeRequests.merge(mr.iid, squash = true)

try project.branches.create("release-1", "main")
try project.files.create("CHANGELOG.md", "release-1", "# 1.0\n", "Add the changelog")
let failed = try project.jobs.list(scope = ["failed"]).all(limit = 10)
for let job in failed {
	print("{job.name}: {job.webUrl}")
}
try project.variables.create("DEPLOY_KEY", deployKey, masked = true)
try project.releases.create(tagName = "v1.0.0", name = "1.0")
let hits = try gl.project("group/app").search("issues", "crash").page(1)

Lists are Pages: all() walks every page by the answer's Link header, offset or keyset (pagination = "keyset" where a list takes it), at most limit objects when given; page(n, size) reads one. The rate limit is read from every answer (gl.limits()); a request throttled with 429 waits for Retry-After, at most rateLimitWait (5 minutes).

GraphQL

struct CurrentUser { username string = "" }
struct UserData { currentUser CurrentUser = CurrentUser{} }

let me = UserData{}
try gl.graphql(`query { currentUser { username } }`, target = me)

struct IssueNode { iid string = ""  title string = "" }
let query = `query($cursor: String) { project(fullPath: "group/app") { issues(first: 100, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { iid title } } } }`
for let issue in try gl.graphqlPages<IssueNode>(query, "project.issues").all() {
	print(issue.title)
}

Webhooks

Webhooks.handler checks each delivery's X-Gitlab-Token against the secret token and hands it out as a WebhookEvent, whose accessors decode the payload of its kind (push, tagPush, mergeRequest, issue, note, pipeline, job, deployment, release); decode reads the others into a type of the program's.

let hooks = new gitlab.Webhooks(secret)
try server.handle("/gitlab", hooks.handler(def (event gitlab.WebhookEvent) !none {
	let merged = try event.mergeRequest()
	if !(merged is none) && merged.objectAttributes.action == "merge" {
		print("!{merged.objectAttributes.iid} merged")
	}
	return none
}))

Errors

Calls fail with a GitLabError: its kind (NotFound, Denied, Argument, Invalid, Conflict, RateLimited, Query, ...), the HTTP status, the problems GitLab names by field and its requestId.

Tests

adm test dev/gitlab runs against a loopback server that answers as GitLab does. ADM_TEST_GITLAB_TOKEN, ADM_TEST_GITLAB_URL and ADM_TEST_GITLAB_PROJECT add calls to a real instance in a scratch project the token may write to.

The REST layer (types.adm, operations.adm, operations_test.adm) is generated by tools/generate.py from GitLab's OpenAPI document and tools/supplement.yaml, the endpoints and field types the document leaves out or gives otherwise than GitLab sends them.