A GitLab API client enabling Go programs to interact with GitLab in a simple and uniform way

Related tags

go-gitlab
Overview

go-gitlab

A GitLab API client enabling Go programs to interact with GitLab in a simple and uniform way

Build Status Sourcegraph GoDoc Go Report Card

NOTE

Release v0.6.0 (released on 25-08-2017) no longer supports the older V3 Gitlab API. If you need V3 support, please use the f-api-v3 branch. This release contains some backwards incompatible changes that were needed to fully support the V4 Gitlab API.

Coverage

This API client package covers most of the existing Gitlab API calls and is updated regularly to add new and/or missing endpoints. Currently the following services are supported:

  • Applications
  • Award Emojis
  • Branches
  • Broadcast Messages
  • Commits
  • Container Registry
  • Custom Attributes
  • Deploy Keys
  • Deployments
  • Discussions (threaded comments)
  • Environments
  • Epic Issues
  • Epics
  • Events
  • Feature Flags
  • Geo Nodes
  • GitLab CI Config Templates
  • Gitignores Templates
  • Group Access Requests
  • Group Issue Boards
  • Group Members
  • Group Milestones
  • Group Wikis
  • Group-Level Variables
  • Groups
  • Instance Clusters
  • Invites
  • Issue Boards
  • Issues
  • Jobs
  • Keys
  • Labels
  • License
  • Merge Request Approvals
  • Merge Requests
  • Namespaces
  • Notes (comments)
  • Notification Settings
  • Open Source License Templates
  • Pages Domains
  • Personal Access Tokens
  • Pipeline Schedules
  • Pipeline Triggers
  • Pipelines
  • Project Access Requests
  • Project Badges
  • Project Clusters
  • Project Import/export
  • Project Members
  • Project Milestones
  • Project Snippets
  • Project-Level Variables
  • Projects (including setting Webhooks)
  • Protected Branches
  • Protected Environments
  • Protected Tags
  • Repositories
  • Repository Files
  • Runners
  • Search
  • Services
  • Settings
  • Sidekiq Metrics
  • System Hooks
  • Tags
  • Todos
  • Users
  • Validate CI Configuration
  • Version
  • Wikis

Usage

import "github.com/xanzy/go-gitlab"

Construct a new GitLab client, then use the various services on the client to access different parts of the GitLab API. For example, to list all users:

git, err := gitlab.NewClient("yourtokengoeshere")
if err != nil {
  log.Fatalf("Failed to create client: %v", err)
}
users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{})

There are a few With... option functions that can be used to customize the API client. For example, to set a custom base URL:

git, err := gitlab.NewClient("yourtokengoeshere", gitlab.WithBaseURL("https://git.mydomain.com/api/v4"))
if err != nil {
  log.Fatalf("Failed to create client: %v", err)
}
users, _, err := git.Users.ListUsers(&gitlab.ListUsersOptions{})

Some API methods have optional parameters that can be passed. For example, to list all projects for user "svanharmelen":

git := gitlab.NewClient("yourtokengoeshere")
opt := &ListProjectsOptions{Search: gitlab.String("svanharmelen")}
projects, _, err := git.Projects.ListProjects(opt)

Examples

The examples directory contains a couple for clear examples, of which one is partially listed here as well:

package main

import (
	"log"

	"github.com/xanzy/go-gitlab"
)

func main() {
	git, err := gitlab.NewClient("yourtokengoeshere")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create new project
	p := &gitlab.CreateProjectOptions{
		Name:                 gitlab.String("My Project"),
		Description:          gitlab.String("Just a test project to play with"),
		MergeRequestsEnabled: gitlab.Bool(true),
		SnippetsEnabled:      gitlab.Bool(true),
		Visibility:           gitlab.Visibility(gitlab.PublicVisibility),
	}
	project, _, err := git.Projects.CreateProject(p)
	if err != nil {
		log.Fatal(err)
	}

	// Add a new snippet
	s := &gitlab.CreateProjectSnippetOptions{
		Title:           gitlab.String("Dummy Snippet"),
		FileName:        gitlab.String("snippet.go"),
		Content:         gitlab.String("package main...."),
		Visibility:      gitlab.Visibility(gitlab.PublicVisibility),
	}
	_, _, err = git.ProjectSnippets.CreateSnippet(project.ID, s)
	if err != nil {
		log.Fatal(err)
	}
}

For complete usage of go-gitlab, see the full package docs.

ToDo

  • The biggest thing this package still needs is tests 😞

Issues

Author

Sander van Harmelen ([email protected])

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Issues
  • Can i get private-token with my password?

    Can i get private-token with my password?

    I can get my username&password only, and how can i create the go-gitlab client?? In my app, i cannot use OAUTH2.0 token anymore.

    wontfix 
    opened by LiangXugang 29
  • Support the v4 API

    Support the v4 API

    Lets track this in an issue. The GitLab API v3 is officially deprecated and will be supported until at least 9.3. Given the current release schedule (once per month), that means it will be unsupported 3 months from now.

    I would like to be able to start consuming v4 functionality so I might start work on a v4 branch.

    I think all current documentation links need to be updated to the v3 documentation as currently the links all point to the v4 documentation which causes confusion. Separately some effort should be made to start supporting v4 specific functionality (probably in a feature branch). Once both those things are completed, v3 could be spun out to a separate branch and v4 can be merged to master.

    Below are the changes made between V3 and V4. A tickbox indicates that work has been completed on that change.

    Completed

    • [x] Rename Build Triggers to be Pipeline Triggers API !9713. Fixed in #152.
      • POST /projects/:id/trigger/builds to POST /projects/:id/trigger/pipeline
      • Require description when creating a new trigger POST /projects/:id/triggers
    • [x] Removed GET /projects/:search (use: GET /projects?search=x) !8877. Fixed in #161.
    • [x] iid filter has been removed from GET /projects/:id/issues !8967. Fixed in #161.
    • [x] GET /projects/:id/merge_requests?iid[]=x&iid[]=y array filter has been renamed to iids !8793. Fixed in #161.
    • [x] Endpoints under GET /projects/merge_request/:id have been removed (use: GET /projects/merge_requests/:id) !8793. Fixed in #161.
    • [x] Project snippets do not return deprecated field expires_at !8723. Fixed in #161.
    • [x] Endpoints under GET /projects/:id/keys have been removed (use GET /projects/:id/deploy_keys) !8716. Fixed in #161.
    • [x] Update v3 documentation to point to archived v3 docs. Fixed in #160.
    • [x] Return basic info about pipeline in GET /projects/:id/pipelines !8875. Fixed in #163
    • [x] Renamed all build references to job !9463. Fixed in #166.
    • [x] Use visibility as string parameter everywhere !9337. Fixed in #167.
    • [x] Project filters are no longer available as GET /projects/foo, but as GET /projects?foo=true instead !8962. Fixed in #170.
      • GET /projects/visible & GET /projects/all are consolidated into GET /projects and can be used with or without authorization
      • GET /projects/owned moved to GET /projects?owned=true
      • GET /projects/starred moved to GET /projects?starred=true
    • [x] GET /projects returns all projects visible to current user, even if the user is not a member !9674. Fixed in #170.
      • To get projects the user is a member of, use GET /projects?membership=true
    • [x] Return HTTP status code 400 for all validation errors when creating or updating a member instead of sometimes 422 error. !9523. Doesn't require changes.
    • [x] Status 409 returned for POST /projects/:id/members when a member already exists !9093. Doesn't require changes.
    • [x] Remove GET /groups/owned. Use GET /groups?owned=true instead !9505. Fixed in commit 62634b8.
    • [x] Moved POST /projects/fork/:id to POST /projects/:id/fork !8940. Fixed in commit 577e19d.
    • [x] Renamed the merge_when_build_succeeds parameter to merge_when_pipeline_succeeds on the following endpoints: !9335
      • PUT /projects/:id/merge_requests/:merge_request_id/merge
      • POST /projects/:id/merge_requests/:merge_request_id/cancel_merge_when_pipeline_succeeds
      • POST /projects
      • POST /projects/user/:user_id
      • PUT /projects/:id
    • [x] Update endpoints for repository files !9637. Fixed in commit a0b1dcb.
      • Moved GET /projects/:id/repository/files?file_path=:file_path to GET /projects/:id/repository/files/:file_path (:file_path should be URL-encoded)
      • GET /projects/:id/repository/blobs/:sha now returns JSON attributes for the blob identified by :sha, instead of finding the commit identified by :sha and returning the raw content of the blob in that commit identified by the required ?filepath=:filepath
      • Moved GET /projects/:id/repository/commits/:sha/blob?file_path=:file_path and GET /projects/:id/repository/blobs/:sha?file_path=:file_path to GET /projects/:id/repository/files/:file_path/raw?ref=:sha
      • GET /projects/:id/repository/tree parameter ref_name has been renamed to ref for consistency
    • [x] Removed the following deprecated Templates endpoints (these are still accessible with /templates prefix) !8853
      • /licences
      • /licences/:key
      • /gitignores
      • /gitlab_ci_ymls
      • /dockerfiles
      • /gitignores/:key
      • /gitlab_ci_ymls/:key
      • /dockerfiles/:key
    • [x] Moved DELETE /todos to POST /todos/mark_as_done and DELETE /todos/:todo_id to POST /todos/:todo_id/mark_as_done !9410
    • [x] Return pagination headers for all endpoints that return an array !8606
    • [x] Removed DELETE /projects/:id/deploy_keys/:key_id/disable. Use DELETE /projects/:id/deploy_keys/:key_id instead !9366
    • [x] Moved PUT /users/:id/(block|unblock) to POST /users/:id/(block|unblock) !9371
    • [x] Make subscription API more RESTful. Use POST /projects/:id/:subscribable_type/:subscribable_id/subscribe to subscribe and POST /projects/:id/:subscribable_type/:subscribable_id/unsubscribe to unsubscribe from a resource. !9325
    • [x] Labels filter on GET /projects/:id/issues and GET /issues now matches only issues containing all labels (i.e.: Logical AND, not OR) !8849
    • [x] Renamed param branch_name to branch on the following endpoints !8936
      • POST /projects/:id/repository/branches
      • POST /projects/:id/repository/commits
      • POST/PUT/DELETE :id/repository/files
    • [x] Renamed branch_name to branch on DELETE /projects/:id/repository/branches/:branch response !8936
    • [x] Remove public param from create and edit actions of projects !8736
    • [x] Remove subscribed field from responses returning list of issues or merge requests. Fetch individual issues or merge requests to obtain the value of subscribed !9661
    • [x] Notes do not return deprecated field upvote and downvote !9384
    • [x] Return 202 with JSON body on async removals on V4 API (DELETE /projects/:id/repository/merged_branches and DELETE /projects/:id) !9449
    • [x] GET /projects/:id/milestones?iid[]=x&iid[]=y array filter has been renamed to iids !9096
    • [x] Drop GET /projects/:id/repository/commits/:sha/jobs !9463
    • [x] Simplify project payload exposed on Environment endpoints !9675
    • [x] API uses merge request IIDs (internal ID, as in the web UI) rather than IDs. This affects the merge requests, award emoji, todos, and time tracking APIs. !9530
    • [x] API uses issue IIDs (internal ID, as in the web UI) rather than IDs. This affects the issues, award emoji, todos, and time tracking APIs. !9530
    • [x] Change initial page from 0 to 1 on GET /projects/:id/repository/commits (like on the rest of the API) [!9679] (https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/9679)
    • [x] Return correct Link header data for GET /projects/:id/repository/commits [!9679] (https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/9679)
    opened by johanbrandhorst 13
  • Implement a rate limiting stategy

    Implement a rate limiting stategy

    This adds both a rate limiter in order to try and prevent hitting the limit all together, and in addition it adds some retry logic.

    Fixes #630

    opened by svanharmelen 12
  • Duplicated variables in ProjectVariablesService.UpdateVariable

    Duplicated variables in ProjectVariablesService.UpdateVariable

    func (s *ProjectVariablesService) UpdateVariable(pid interface{}, key string, opt *UpdateVariableOptions, options ...OptionFunc) (*ProjectVariable, *Response, error) {
    	project, err := parseID(pid)
    	if err != nil {
    		return nil, nil, err
    	}
    	u := fmt.Sprintf("projects/%s/variables/%s",
    		url.QueryEscape(project),
    		url.QueryEscape(key),
    	)
    

    You are accepting 2 "key" variables. In function and as a parameter of UpdateVariableOptions. Can we use just one instead of two? Does it make sense or am I missing something?

    opened by killmeplz 12
  • Add support for new project import/export API

    Add support for new project import/export API

    GitLab recently released an API to import/export projects.

    Proposal would be to add support to go-gitlab for this: https://docs.gitlab.com/ee/api/project_import_export.html

    enhancement 
    opened by olearycrew 12
  • WIP Terraform endpoint support

    WIP Terraform endpoint support

    Hello there, this is a WIP. I'd like to get early feedback on the general direction of this work. I tried to be consistent with the existing codebase. I intent to add more tests, links to docs, etc and actually test against a real GitLab instance once the support is available (it's being worked on).

    opened by ash2k 11
  • Emoji Award API

    Emoji Award API

    Is this missing in the current state of the project? It looks like it.

    https://docs.gitlab.com/ce/api/award_emoji.html

    enhancement 
    opened by Lorac 11
  • golang.org/x/oauth2

    golang.org/x/oauth2

    Is it possible to reference github's class library and use golang's class library to cause us to fail to download in China,I cannot go get golang.org/x/oauth2

    opened by relax-admin 10
  • Add support for custom rate limiter

    Add support for custom rate limiter

    Sort of a feature request, use cases may include private gitlab instance not doing the rate limiting itself and not returning rate limit headers and / or when someone wishes to limit load to lower than what's automatically configured.

    Can make a pull request to add it, wanted some thoughts and considerations that I'm not thinking about :)

    Thanks.

    opened by 2785 10
  • Added Tests for Namespaces

    Added Tests for Namespaces

    According to Docs: https://docs.gitlab.com/13.12/ee/api/namespaces.html and https://docs.gitlab.com/ee/api/namespaces.html

    opened by Urento 0
  • Search Namespaces Deprecated?

    Search Namespaces Deprecated?

    The Search Namespaces is not in the Docs anymore (https://docs.gitlab.com/ee/api/namespaces.html) and should maybe get deprecated

    https://github.com/xanzy/go-gitlab/blob/5f216031d9ef0581f96286a5ec48d086c1833868/namespaces.go#L80

    opened by Urento 1
  • feat: Added Pages Support

    feat: Added Pages Support

    Link to the Docs: https://docs.gitlab.com/ee/api/pages.html#unpublish-pages

    opened by Urento 0
  • Added more tests

    Added more tests

    I also added the "Enabled" and "Managed" Field to the GroupCluster

    If you need anything changed I can still change things

    opened by Urento 5
  • Add Support for Merge Results

    Add Support for Merge Results

    Please add support for

    Projects -> General Settings -> Merge Options -> Merge Result pipelines and Merge Trains Screen Shot 2021-07-30 at 11 21 56 AM

    opened by Alfredo-Moreira 0
  • Add new struct for MergeRequestApprovals.GetConfiguration

    Add new struct for MergeRequestApprovals.GetConfiguration

    Added a new struct for merge request approvals get configuration

    Current function used MergeRequestApprovals which doesn't fit the actual API response.

    Example response with cURL:

    curl --location --request GET 'https://example.com//api/v4/projects/1/merge_requests/1/approvals' --header 'PRIVATE-TOKEN: XXXX'
    
    {
        "id": 1,
        "iid": 2,
        "project_id": 1,
        "title": "Test",
        "description": "",
        "state": "opened",
        "created_at": "2021-07-19T23:09:21.907Z",
        "updated_at": "2021-07-23T13:59:55.714Z",
        "merge_status": "can_be_merged",
        "approved": false,
        "approvals_required": 2,
        "approvals_left": 1,
        "require_password_to_approve": false,
        "approved_by": [
            {
                "user": {
                    "id": 182,
                    "name": "Jane Doe",
                    "username": "jane.doe",
                    "state": "active",
                    "avatar_url": "",
                    "web_url": "https://example.com/jane.doe"
                }
            }
        ],
        "suggested_approvers": [
            {
                "id": 11,
                "name": "John Doe",
                "username": "john.doe",
                "state": "active",
                "avatar_url": "",
                "web_url": "https://example.com/john.doe"
            }
        ],
        "approvers": [],
        "approver_groups": [],
        "user_has_approved": false,
        "user_can_approve": false,
        "approval_rules_left": [
            {
                "id": 1,
                "name": "Default",
                "rule_type": "regular"
            }
        ],
        "has_approval_rules": true,
        "merge_request_approvers_available": true,
        "multiple_approval_rules_available": true
    }
    
    opened by ottramst 1
  • Add GenericPackagesServices (#1100)

    Add GenericPackagesServices (#1100)

    This PR continues the work in #1101, rebasing it to master, updating its interface (returning download URL), and some real-world testing (fixed the URL endpoint and request type).

    opened by neomantra 0
  • feat: Add HeadPipelineID In MergeEvent

    feat: Add HeadPipelineID In MergeEvent

    Like this

    {
        "object_attributes": {
            "head_pipeline_id": null
        }
    }
    
    {
        "object_attributes": {
            "head_pipeline_id": 123
        }
    }
    
    opened by HZMarico 1
  • Add support for refresh_token when create client

    Add support for refresh_token when create client

    in the current interface: NewXXXClient(token string, ... Options)

    it only takes in access_token as first parameter, we need to support refresh_token in the Client as well (like in form of oauth2.Token) so that the long-lasting Client works properly.

    please advise how to achieve that if we've already done so.

    opened by linneawang 3
  • Export not found project

    Export not found project

    Hello, I am using the library to interact with Gitlab but when I go to download the repository files it gives me this error, if someone could help me

    Thanks

    image

    image

    When I run this method it returns this to me

    https://gitlab.com/api/v4/projects/26975042/export

    {"id":26975042,"description":"","name":"template-technique-java-springboot","name_with_namespace":"cli-project / template-technique-java-springboot","path":"template-technique-java-springboot","path_with_namespace":"proyectos/template-technique-java-springboot","created_at":"2021-05-27T18:28:38.369Z","export_status":"none"}

    opened by omar26begue 2
Owner
Xanzy
Xanzy
A static code analyzer for annotated TODO comments

todocheck todocheck is a static code analyzer for annotated TODO comments. It let's you create actionable TODOs by annotating them with issues from an

Preslav Mihaylov 351 Sep 3, 2021
Sloc, Cloc and Code: scc is a very fast accurate code counter with complexity calculations and COCOMO estimates written in pure Go

Sloc Cloc and Code (scc) A tool similar to cloc, sloccount and tokei. For counting physical the lines of code, blank lines, comment lines, and physica

Ben Boyter 2.7k Sep 10, 2021
A reference for the Go community that covers the fundamentals of writing clean code and discusses concrete refactoring examples specific to Go.

A reference for the Go community that covers the fundamentals of writing clean code and discusses concrete refactoring examples specific to Go.

Lasse Martin Jakobsen 1.8k Sep 6, 2021
MOVED TO GITLAB

blanket blanket is a tool that helps you catch functions which don't have direct unit tests in your Go packages. Installation go get -u gitlab.com/ver

Jeffrey D. 14 Mar 23, 2020
🔥 ~6x faster, stricter, configurable, extensible, and beautiful drop-in replacement for golint

revive Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. Revive provides a framework for developme

Minko Gechev 2.9k Sep 14, 2021
Know when GC runs from inside your golang code

gcnotifier gcnotifier provides a way to receive notifications after every run of the garbage collector (GC). Knowing when GC runs is useful to instruc

Carlo Alberto Ferraris 160 Jul 5, 2021
octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

Ken’ichiro Oyama 9 Sep 10, 2021
errcheck checks that you checked errors.

errcheck errcheck is a program for checking for unchecked errors in go programs. Install go get -u github.com/kisielk/errcheck errcheck requires Go 1

Kamil Kisiel 1.7k Sep 14, 2021
Fast linters Runner for Go

golangci-lint Fast linters runner for Go golangci-lint is a fast Go linters runner. It runs linters in parallel, uses caching, supports yaml config, h

null 8.5k Sep 9, 2021
Manage your repository's TODOs, tickets and checklists as config in your codebase.

tickgit ??️ tickgit is a tool to help you manage latent work in a codebase. Use the tickgit command to view pending tasks, progress reports, completio

Augmentable 262 Sep 7, 2021
[mirror] Performance measurement, storage, and analysis.

Go performance measurement, storage, and analysis tools This subrepository holds the source for various packages and tools related to performance meas

Go 276 Sep 6, 2021
A Go linter to check that errors from external packages are wrapped

Wrapcheck A simple Go linter to check that errors from external packages are wrapped during return to help identify the error source during debugging.

Tom Arrell 71 Sep 5, 2021
Tool to populate your code with traceable and secure error codes

Essential part of any project, especially customer facing is proper and secure error handling. When error happens and customer reports it, it would be nice to know the context of the error and where it exactly occured.

vs 51 Apr 4, 2021
This is a style verifier intended to be used with the Gerrit checks plugin.

GERRITFMT This is a style verifier intended to be used with the Gerrit checks plugin. HOW TO USE Install formatters: go install github.com/bazelbuild/

Google 22 Apr 20, 2021
Run linters from Go code -

Lint - run linters from Go Lint makes it easy to run linters from Go code. This allows lint checks to be part of a regular go build + go test workflow

Surul Software Labs GmbH 66 Oct 5, 2020
Find outdated golang packages

This project is not supported anymore Go-outdated is minimalistic library that helps to find outdated packages hosted on github.com in your golang pro

null 45 Feb 7, 2021
Nightly binary builds of Emacs for macOS as a self-contained Emacs.app, with native-compilation.

Emacs Builds Nightly binary builds of Emacs for macOS as a self-contained Emacs.app, with native-compilation. Features Self-contained Emacs.app applic

Jim Myhrberg 49 Aug 31, 2021