Categorygithub.com/andygrunwald/go-gerrit
modulepackage
1.0.0
Repository: https://github.com/andygrunwald/go-gerrit.git
Documentation: pkg.go.dev

# README

go-gerrit

GoDoc

go-gerrit is a Go client library for the Gerrit Code Review system.

go-gerrit - Go client/library for Gerrit Code Review

Features

Installation

go-gerrit follows the Go Release Policy. This means we support the current + 2 previous Go versions.

It is go gettable ...

$ go get github.com/andygrunwald/go-gerrit

API / Usage

Have a look at the GoDoc documentation for a detailed API description.

The Gerrit Code Review - REST API was the foundation document.

Authentication

Gerrit supports multiple ways for authentication.

HTTP Basic

Some Gerrit instances (like TYPO3) has auth.gitBasicAuth activated. With this, you can authenticate with HTTP Basic like this:

instance := "https://review.typo3.org/"
client, _ := gerrit.NewClient(instance, nil)
client.Authentication.SetBasicAuth("andy.grunwald", "my secrect password")

self, _, _ := client.Accounts.GetAccount("self")

fmt.Printf("Username: %s", self.Name)

// Username: Andy Grunwald

If you get a 401 Unauthorized, check your Account Settings and have a look at the HTTP Password configuration.

HTTP Digest

Some Gerrit instances (like Wikimedia) has Digest access authentication activated.

instance := "https://gerrit.wikimedia.org/r/"
client, _ := gerrit.NewClient(instance, nil)
client.Authentication.SetDigestAuth("andy.grunwald", "my secrect http password")

self, resp, err := client.Accounts.GetAccount("self")

fmt.Printf("Username: %s", self.Name)

// Username: Andy Grunwald

If the chosen Gerrit instance does not support digest auth, an error like WWW-Authenticate header type is not Digest is thrown.

If you get a 401 Unauthorized, check your Account Settings and have a look at the HTTP Password configuration.

HTTP Cookie

Some Gerrit instances hosted like the one hosted googlesource.com (e.g. Go, Android or Gerrit) support HTTP Cookie authentication.

You need the cookie name and the cookie value. You can get them by click on "Settings > HTTP Password > Obtain Password" in your Gerrit instance.

There you can receive your values. The cookie name will be (mostly) o (if hosted on googlesource.com). Your cookie secret will be something like [email protected]=SomeHash....

instance := "https://gerrit-review.googlesource.com/"
client, _ := gerrit.NewClient(instance, nil)
client.Authentication.SetCookieAuth("o", "my-cookie-secret")

self, _, _ := client.Accounts.GetAccount("self")

fmt.Printf("Username: %s", self.Name)

// Username: Andy G.

Examples

More examples are available

Get version of Gerrit instance

Receive the version of the Gerrit instance used by the Gerrit team for development:

package main

import (
	"fmt"

	"github.com/andygrunwald/go-gerrit"
)

func main() {
	instance := "https://gerrit-review.googlesource.com/"
	client, err := gerrit.NewClient(instance, nil)
	if err != nil {
		panic(err)
	}

	v, _, err := client.Config.GetVersion()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Version: %s", v)

	// Version: 3.4.1-2066-g8db5605430
}

Get all public projects

List all projects from Chromium:

package main

import (
	"fmt"

	"github.com/andygrunwald/go-gerrit"
)

func main() {
	instance := "https://chromium-review.googlesource.com/"
	client, err := gerrit.NewClient(instance, nil)
	if err != nil {
		panic(err)
	}

	opt := &gerrit.ProjectOptions{
		Description: true,
	}
	projects, _, err := client.Projects.ListProjects(opt)
	if err != nil {
		panic(err)
	}

	for name, p := range *projects {
		fmt.Printf("%s - State: %s\n", name, p.State)
	}

	// chromiumos/third_party/bluez - State: ACTIVE
	// external/github.com/Polymer/ShadowDOM - State: ACTIVE
	// external/github.com/domokit/mojo_sdk - State: ACTIVE
	// ...
}

Query changes

Get some changes of the kernel/common project from the AndroidGerrit Review System.

package main

import (
	"fmt"

	"github.com/andygrunwald/go-gerrit"
)

func main() {
	instance := "https://android-review.googlesource.com/"
	client, err := gerrit.NewClient(instance, nil)
	if err != nil {
		panic(err)
	}

	opt := &gerrit.QueryChangeOptions{}
	opt.Query = []string{"project:kernel/common"}
	opt.AdditionalFields = []string{"LABELS"}
	changes, _, err := client.Changes.QueryChanges(opt)
	if err != nil {
		panic(err)
	}

	for _, change := range *changes {
		fmt.Printf("Project: %s -> %s -> %s%d\n", change.Project, change.Subject, instance, change.Number)
	}

	// Project: kernel/common -> ANDROID: GKI: Update symbols to symbol list -> https://android-review.googlesource.com/1830553
	// Project: kernel/common -> ANDROID: db845c_gki.fragment: Remove CONFIG_USB_NET_AX8817X from fragment -> https://android-review.googlesource.com/1830439
	// Project: kernel/common -> ANDROID: Update the ABI representation -> https://android-review.googlesource.com/1830469
	// ...
}

Development

Running tests and linters

Tests only:

$ make test

Checks, tests and linters

$ make vet staticcheck test

Local Gerrit setup

For local development, we suggest the usage of the official Gerrit Code Review docker image:

$ docker run -ti -p 8080:8080 -p 29418:29418 gerritcodereview/gerrit:3.4.1

Wait a few minutes until the Gerrit Code Review NNN ready message appears, where NNN is your current Gerrit version, then open your browser to http://localhost:8080 and you will be in Gerrit Code Review.

Authentication

For local development setups, go to http://localhost:8080/settings/#HTTPCredentials and click GENERATE NEW PASSWORD. Now you can use (only for development purposes):

client.Authentication.SetBasicAuth("admin", "secret")

Replace secret with your new value.

Frequently Asked Questions (FAQ)

How is the source code organized?

The source code organization is inspired by go-github by Google.

Every REST API Endpoint (e.g. /access/, /changes/) is coupled in a service (e.g. AccessService in access.go, ChangesService in changes.go). Every service is part of gerrit.Client as a member variable.

gerrit.Client can provide essential helper functions to avoid unnecessary code duplications, such as building a new request or parse responses.

Based on this structure, implementing a new API functionality is straight forward. Here is an example of *ChangeService.DeleteTopic* / DELETE /changes/{change-id}/topic:

func (s *ChangesService) DeleteTopic(changeID string) (*Response, error) {
    u := fmt.Sprintf("changes/%s/topic", changeID)
    return s.client.DeleteRequest(u, nil)
}

What about the version compatibility with Gerrit?

The library was implemented based on the REST API of Gerrit version 2.11.3-1230-gb8336f1 and tested against this version.

This library might be working with older versions as well. If you notice an incompatibility open a new issue. We also appreciate your Pull Requests to improve this library. We welcome contributions!

What about adding code to support the REST API of an (optional) plugin?

It will depend on the plugin, and you are welcome to open a new issue first to propose the idea and use-case. As an example, the addition of support for events-log plugin was supported because the plugin itself is fairly popular. The structures that the REST API uses could also be used by gerrit stream-events.

License

This project is released under the terms of the MIT license.

# Packages

No description provided by the author

# Functions

CheckResponse checks the API response for errors, and returns them if present.
NewClient returns a new Gerrit API client.
RemoveMagicPrefixLine removes the "magic prefix line" of Gerris JSON response if present.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

ErrAuthenticationFailed is returned by NewClient in the event the provided credentials didn't allow us to query account information using digest, basic or cookie auth.
ErrNoInstanceGiven is returned by NewClient in the event the gerritURL argument was blank.
ErrUserProvidedWithoutPassword is returned by NewClient if a user name is provided without a password.
ErrWWWAuthenticateHeaderInvalid is returned by digestAuthHeader when the WWW-Authenticate invalid.
ErrWWWAuthenticateHeaderMissing is returned by digestAuthHeader when the WWW-Authenticate header is missing.
ErrWWWAuthenticateHeaderNotDigest is returned by digestAuthHeader when the WWW-Authenticate header is not 'Digest'.
ReParseURL is used to parse the url provided to NewClient().

# Structs

AbandonInput entity contains information for abandoning a change.
AccessCheckInfo entity is the result of an access check.
AccessSectionInfo describes the access rights that are assigned on a ref.
AccessService contains Access Right related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html.
AccountCapabilityInfo entity contains information about the global capabilities of a user.
AccountDetailInfo entity contains detailed information about an account.
AccountExternalIdInfo entity contains information for an external id of an account.
AccountInfo entity contains information about an account.
AccountInput entity contains information for the creation of a new account.
AccountNameInput entity contains information for setting a name for an account.
AccountOptions specifies parameters for Query Accounts.
AccountsService contains Account related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html.
ActionInfo entity describes a REST API call the client can make to manipulate a resource.
AddReviewerResult entity describes the result of adding a reviewer to a change.
ApprovalInfo entity contains information about an approval from a user for a label on a change.
AttentionSetInfo entity contains details of users that are in the attention set.
AttentionSetInput entity contains details for adding users to the attention set and removing them from it.
AuthenticationService contains Authentication related functions.
AuthInfo entity contains information about the authentication configuration of the Gerrit server.
BanInput entity contains information for banning commits in a project.
BanResultInfo entity describes the result of banning commits.
BranchInfo entity contains information about a branch.
BranchInput entity contains information for the creation of a new branch.
BranchOptions specifies the parameters to the branch API endpoints.
CacheInfo entity contains information about a cache.
CacheOperationInput entity contains information about an operation that should be executed on caches.
CapabilityOptions specifies the parameters to filter for capabilities.
ChangeConfigInfo entity contains information about Gerrit configuration from the change section.
ChangeEditDetailOptions specifies the parameters to the ChangesService.GetChangeEditDetails.
ChangeEditInput entity contains information for restoring a path within change edit.
ChangeEditMessageInput entity contains information for changing the commit message within a change edit.
ChangeInfo entity contains information about a change.
ChangeInput entity contains information about creating a new change.
ChangeMessageInfo entity contains information about a message attached to a change.
ChangeOptions specifies the parameters for Query changes.
ChangesService contains Change related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html.
CheckAccessOptions is options for check access.
CherryPickInput entity contains information for cherry-picking a change to a new branch.
ChildProjectOptions specifies the parameters to the Child Project API endpoints.
A Client manages communication with the Gerrit API.
CommentInfo entity contains information about an inline comment.
CommentInput entity contains information for creating an inline comment.
CommentRange entity describes the range of an inline comment.
CommitInfo entity contains information about a commit.
CommitMessageInput entity contains information for changing the commit message of a change.
CommitOptions specifies the parameters for GetCommit call.
ConfigCapabilityInfo entity contains information about a capability.type.
ConfigInfo entity contains information about the effective project configuration.
ConfigInput entity describes a new project configuration.
ConfigParameterInfo entity describes a project configuration parameter.
ConfigService contains Config related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html.
DashboardInfo entity contains information about a project dashboard.
DashboardInput entity contains information to create/update a project dashboard.
DashboardSectionInfo entity contains information about a section in a dashboard.
DeleteBranchesInput entity contains information about branches that should be deleted.
DeleteOptionsInfo entity contains information for the deletion of a project.
DeleteTagsInput entity for delete tags.
DeleteVoteInput entity contains options for the deletion of a vote.
DiffContent entity contains information about the content differences in a file.
DiffFileMetaInfo entity contains meta information about a file diff.
DiffInfo entity contains information about the diff of a file in a revision.
DiffOptions specifies the parameters for GetDiff call.
DiffPreferencesInfo entity contains information about the diff preferences of a user.
DiffPreferencesInput entity contains information for setting the diff preferences of a user.
DiffWebLinkInfo entity describes a link on a diff screen to an external site.
DownloadInfo entity contains information about supported download options.
DownloadSchemeInfo entity contains information about a supported download scheme and its commands.
EditFileInfo entity contains additional information of a file within a change edit.
EditInfo entity contains information about a change edit.
EmailConfirmationInput entity contains information for confirming an email address.
EmailInfo entity contains information about an email address of a user.
EmailInput entity contains information for registering a new email address.
EntriesInfo entity contains information about the entries in a cache.
EventInfo contains information about an event emitted by Gerrit.
EventsLogOptions contains options for querying events from the events-logs plugin.
EventsLogService contains functions for querying the API provided by the optional events-log plugin.
FetchInfo entity contains information about how to fetch a patch set via a certain protocol.
FileInfo entity contains information about a file in a patch set.
FilesOptions specifies the parameters for ListFiles and ListFilesReviewed calls.
FixInput entity contains options for fixing commits using the fix change endpoint.
FixReplacementInfo entity describes how the content of a file should be replaced by another content.
FixSuggestionInfo entity represents a suggested fix.
GCInput entity contains information to run the Git garbage collection.
GitPersonInfo entity contains information about the author/committer of a commit.
GitwebInfo entity contains information about the gitweb configuration.
GitwebTypeInfo entity contains information about the gitweb configuration.
GpgKeyInfo entity contains information about a GPG public key.
GpgKeysInput entity contains information for adding/deleting GPG keys.
GroupAuditEventInfo entity contains information about an audit event of a group.
GroupBaseInfo entity contains base information about the group.
GroupInfo entity contains information about a group.
GroupInput entity contains information for the creation of a new internal group.
GroupOptionsInfo entity contains options of the group.
GroupOptionsInput entity contains new options for a group.
GroupsInput entity contains information about groups that should be included into a group or that should be deleted from a group.
GroupsService contains Group related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html.
HashtagsInput entity contains information about hashtags to add to, and/or remove from, a change.
HeadInput entity contains information for setting HEAD for a project.
HitRatioInfo entity contains information about the hit ratio of a cache.
HTTPPasswordInput entity contains information for setting/generating an HTTP password.
IncludedInInfo entity contains information about the branches a change was merged into and tags it was tagged with.
Info entity contains information about Gerrit configuration from the gerrit section.
InheritedBooleanInfo entity represents a boolean value that can also be inherited.
JvmSummaryInfo entity contains information about the JVM.
LabelInfo entity contains information about a label on a change, always corresponding to the current patch set.
ListAccessRightsOptions specifies the parameters to the AccessService.ListAccessRights.
ListCachesOptions specifies the different output formats.
ListGroupMembersOptions specifies the different options for the ListGroupMembers call.
ListGroupsOptions specifies the different options for the ListGroups call.
MaxObjectSizeLimitInfo entity contains information about the max object size limit of a project.
MembersInput entity contains information about accounts that should be added as members to a group or that should be deleted from the group.
MemSummaryInfo entity contains information about the current memory usage.
MergableOptions specifies the parameters for GetMergable call.
MergeableInfo entity contains information about the mergeability of a change.
The MergeInput entity contains information about the merge Docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#merge-input.
MoveInput entity contains information for moving a change.
NotifyInfo entity contains detailed information about who should be notified about an update.
The ParentInfo entity contains information about the parent commit of a patch-set.
PatchOptions specifies the parameters for GetPatch call.
PatchSet contains detailed information about a specific patch set.
PermissionInfo entity contains information about an assigned permission.
PermissionRuleInfo entity contains information about a permission rule that is assigned to group.
PluginConfigInfo entity contains information about Gerrit extensions by plugins.
PluginInfo entity describes a plugin.
PluginInput entity describes a plugin that should be installed.
PluginOptions specifies the different options for the ListPlugins call.
PluginsService contains Plugin related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html.
PreferencesInfo entity contains information about a user’s preferences.
PreferencesInput entity contains information for setting the user preferences.
ProblemInfo entity contains a description of a potential consistency problem with a change.
ProjectAccessInfo entity contains information about the access rights for a project.
ProjectAccessInput describes changes that should be applied to a project access config Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#project-access-input.
ProjectBaseOptions specifies the really basic options for projects and sub functionality (e.g.
ProjectDescriptionInput entity contains information for setting a project description.
ProjectInfo entity contains information about a project.
ProjectInput entity contains information for the creation of a new project.
ProjectOptions specifies the parameters to the ProjectsService.ListProjects.
ProjectParentInput entity contains information for setting a project parent.
ProjectsService contains Project related REST endpoints Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html.
QueryAccountOptions queries accounts visible to the caller.
QueryChangeOptions specifies the parameters to the ChangesService.QueryChanges.
QueryLimitInfo entity contains information about the Query Limit of a user.
QueryOptions specifies global parameters to query changes / reviewers.
ReadyForReviewInput entity contains information for transitioning a change from WIP to ready.
RebaseInput entity contains information for changing parent when rebasing.
ReceiveInfo entity contains information about the configuration of git-receive-pack behavior on the server.
ReflogEntryInfo entity describes an entry in a reflog.
RefUpdate contains data about a reference update.
RelatedChangeAndCommitInfo entity contains information about a related change and commit.
RelatedChangesInfo entity contains information about related changes.
RepositoryStatisticsInfo entity contains information about statistics of a Git repository.
Response is a Gerrit API response.
RestoreInput entity contains information for restoring a change.
RevertInput entity contains information for reverting a change.
ReviewerInfo entity contains information about a reviewer and its votes on a change.
ReviewerInput entity contains information for adding a reviewer to a change.
ReviewerUpdateInfo entity contains information about updates to change's reviewers set.
ReviewInfo entity contains information about a review.
ReviewInput entity contains information for adding a review to a revision.
ReviewResult entity contains information regarding the updates that were made to a review.
RevisionInfo entity contains information about a patch set.
RobotCommentInfo entity contains information about a robot inline comment RobotCommentInfo has the same fields as CommentInfo.
RobotCommentInput entity contains information for creating an inline robot comment.
RuleInput entity contains information to test a Prolog rule.
ServerInfo entity contains information about the configuration of the Gerrit server.
SSHdInfo entity contains information about Gerrit configuration from the sshd section.
SSHKeyInfo entity contains information about an SSH key of a user.
SubmitInfo entity contains information about the change status after submitting.
SubmitInput entity contains information for submitting a change.
SubmitRecord entity describes results from a submit_rule.
SubmitRequirementExpressionInfo entity contains information about a submit requirement exppression.
SubmitRequirementResultInfo entity describes the result of evaluating a submit requirement on a change.
SuggestedReviewerInfo entity contains information about a reviewer that can be added to a change (an account or a group).
SuggestInfo entity contains information about Gerrit configuration from the suggest section.
SummaryInfo entity contains information about the current state of the server.
SummaryOptions specifies the different options for the GetSummary call.
TagInfo entity contains information about a tag.
TagInput entity for create a tag.
TaskInfo entity contains information about a task in a background work queue.
TaskSummaryInfo entity contains information about the current tasks.
ThemeInfo entity describes a theme.
ThreadSummaryInfo entity contains information about the current threads.
Timestamp represents an instant in time with nanosecond precision, in UTC time zone.
TopicInput entity contains information for setting a topic.
TopMenuEntryInfo entity contains information about a top menu entry.
TopMenuItemInfo entity contains information about a menu item in a top menu entry.
UserConfigInfo entity contains information about Gerrit configuration from the user section.
UsernameInput entity contains information for setting the username for an account.
WebLinkInfo entity describes a link to an external site.

# Type aliases

DiffIntralineInfo entity contains information about intraline edits in a file.
Number is a string representing a number.
Doc: https://gerrit-review.googlesource.com/Documentation/user-notify.html#recipient-types.
RevisionKind describes the change kind.