1
0
mirror of https://github.com/taigrr/wtf synced 2025-01-18 04:03:14 -08:00

Add gerrit widget

This commit is contained in:
Anand Sudhir Prayaga 2018-06-27 15:59:50 +02:00 committed by Chris Cummer
parent b78893db02
commit b976a1b847
54 changed files with 8021 additions and 268 deletions

32
Gopkg.lock generated
View File

@ -4,14 +4,20 @@
[[projects]]
name = "cloud.google.com/go"
packages = ["compute/metadata"]
revision = "0fd7230b2a7505833d5f69b75cbd6c9582401479"
version = "v0.23.0"
revision = "777200caa7fb8936aed0f12b1fd79af64cc83ec9"
version = "v0.24.0"
[[projects]]
branch = "master"
name = "github.com/adlio/trello"
packages = ["."]
revision = "05dcd358e32866f2353c4f49077346a0eb585436"
revision = "8a458717123e328d9103a3bf075e64bc1ec961f8"
[[projects]]
branch = "master"
name = "github.com/andygrunwald/go-gerrit"
packages = ["."]
revision = "5632c7fad122548dfabeb3011e98d3b0a08a89d7"
[[projects]]
branch = "master"
@ -50,7 +56,7 @@
branch = "master"
name = "github.com/google/go-github"
packages = ["github"]
revision = "a83ae98ad5d09188c49d6056edb60ec9bdf202bd"
revision = "60d040d2dafa18fa3e86cbf22fbc3208ef9ef1e0"
[[projects]]
branch = "master"
@ -80,7 +86,7 @@
branch = "master"
name = "github.com/olebedev/config"
packages = ["."]
revision = "9a10d05a33a8b9e828f20491e21e8927dec35f72"
revision = "ed90d2035b8114c30b9cb65e7d52e10a7148f8c6"
[[projects]]
name = "github.com/pkg/errors"
@ -104,7 +110,7 @@
branch = "master"
name = "github.com/rivo/tview"
packages = ["."]
revision = "e643d10b365df4caec5ed32e4c1103e185af9079"
revision = "306abd9cb98c97417ab6c58aa0400b2e5daac88b"
[[projects]]
name = "github.com/stretchr/testify"
@ -113,16 +119,16 @@
version = "v1.2.2"
[[projects]]
branch = "master"
name = "github.com/xanzy/go-gitlab"
packages = ["."]
revision = "1c1cfedc5a8ffe122b1981e8b0822fe22f461643"
revision = "5c6e84fea386746fd31ff46da2253f6b7ed7dce2"
version = "v0.10.6"
[[projects]]
branch = "master"
name = "github.com/yfronto/newrelic"
packages = ["."]
revision = "f7fa0c6f30ac3d86360c73726cfe9dd526a63d21"
revision = "7c9c2852e8f9e69a80bff4f4f1fe4cdd15eeba19"
[[projects]]
branch = "master"
@ -131,7 +137,7 @@
"context",
"context/ctxhttp"
]
revision = "db08ff08e8622530d9ed3a0e8ac279f6d4c02196"
revision = "afe8f62b1d6bbd81f31868121a50b06d8188e1f9"
[[projects]]
branch = "master"
@ -143,7 +149,7 @@
"jws",
"jwt"
]
revision = "113ce6928c4638e14fd5eba69b9e6ec899d5dd83"
revision = "ef147856a6ddbb60760db74283d2424e98c87bff"
[[projects]]
name = "golang.org/x/text"
@ -167,7 +173,7 @@
"googleapi/internal/uritemplates",
"sheets/v4"
]
revision = "2eea9ba0a3d94f6ab46508083e299a00bbbc65f6"
revision = "3639d6d93f377f39a1de765fa4ef37b3c7ca8bd9"
[[projects]]
name = "google.golang.org/appengine"
@ -195,6 +201,6 @@
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "147a44acfec399fa7d09cafbc213c1c2c222fd6140bc87b35e942d85891995d9"
inputs-digest = "a7a00554f9040d7617458773eafa64b82f9502eace145152cb50eb082800e936"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -45,6 +45,10 @@
name = "github.com/xanzy/go-gitlab"
branch = "master"
[[constraint]]
name = "github.com/andygrunwald/go-gerrit"
branch = "master"
[[constraint]]
name = "github.com/jessevdk/go-flags"
version = "1.4.0"

View File

@ -73,6 +73,7 @@ Many thanks to all these developers.
* [calendar](https://google.golang.org/api/calendar/v3)
* [config](https://github.com/olebedev/config)
* [go-gerrit](https://github.com/andygrunwald/go-gerrit)
* [go-github](https://github.com/google/go-github)
* [goreleaser](https://github.com/goreleaser/goreleaser)
* [newrelic](https://github.com/yfronto/newrelic)

View File

@ -0,0 +1,90 @@
---
title: "Gerrit"
date: 2018-06-27T15:55:42-07:00
draft: false
---
<img src="/imgs/modules/gerrit.png" width="640" height="384" alt="gerrit screenshot" />
Displays information about your projects hosted on Gerrit:
#### Open Incoming Reviews
All open reviews that are requesting your approval.
#### My Outgoing Reviews
All open reviews created by you.
## Source Code
```bash
wtf/gerrit/
```
## Required ENV Variables
<span class="caption">Key:</span> `WTF_GERRIT_PASSWORD` <br />
<span class="caption">Action:</span> Your <a href="https://gerrit-review.googlesource.com/Documentation/user-upload.html#http">Gerrit HTTP Password</a>.
## Keyboard Commands
<span class="caption">Key:</span> `/` <br />
<span class="caption">Action:</span> Open/close the widget's help window.
<span class="caption">Key:</span> `h` <br />
<span class="caption">Action:</span> Show the previous project.
<span class="caption">Key:</span> `l` <br />
<span class="caption">Action:</span> Show the next project.
<span class="caption">Key:</span> `←` <br />
<span class="caption">Action:</span> Show the previous project.
<span class="caption">Key:</span> `→` <br />
<span class="caption">Action:</span> Show the next project.
## Configuration
```yaml
gerrit:
enabled: true
position:
top: 2
left: 3
height: 2
width: 2
refreshInterval: 300
projects:
- org/test-project"
- dotfiles
username: "myname"
```
### Attributes
`enabled` <br />
Determines whether or not this module is executed and if its data displayed onscreen. <br />
Values: `true`, `false`.
`position` <br />
Defines where in the grid this module's widget will be displayed. <br />
`refreshInterval` <br />
How often, in seconds, this module will update its data. <br />
Values: A positive integer, `0..n`.
`domain` <br />
_Optional_. Your Gerrit corporate domain. <br />
Values: A valid URI.
`projects` <br />
A list of Gerrit project names to fetch data for. <br />
`username` <br />
Your Gerrit username. <br />
`verifyServerCertificate` <br />
_Optional_ <br />
Determines whether or not the server's certificate chain and host name are verified. <br />
Values: `true`, `false`.

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@ -29,6 +29,7 @@
<li class="sidebar-list-item-2"><a href="/posts/modules/clocks/">Clocks</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/cryptocurrencies/cryptolive/">CryptoLive</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/cmdrunner/">CmdRunner</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/gerrit/">Gerrit</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/git/">Git</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/github/">GitHub</a></li>
<li class="sidebar-list-item-2"><a href="/posts/modules/gitlab/">Gitlab</a></li>

73
gerrit/display.go Normal file
View File

@ -0,0 +1,73 @@
package gerrit
import (
"fmt"
"github.com/senorprogrammer/wtf/wtf"
)
func (widget *Widget) display() {
project := widget.currentGerritProject()
if project == nil {
fmt.Fprintf(widget.View, "%s", " Gerrit project data is unavailable (1)")
return
}
widget.View.SetTitle(fmt.Sprintf("%s- %s", widget.Name, widget.title(project)))
str := wtf.SigilStr(len(widget.GerritProjects), widget.Idx, widget.View) + "\n"
str = str + " [red]Stats[white]\n"
str = str + widget.displayStats(project)
str = str + "\n"
str = str + " [red]Open Incoming Reviews[white]\n"
str = str + widget.displayMyIncomingReviews(project, wtf.Config.UString("wtf.mods.gerrit.username"))
str = str + "\n"
str = str + " [red]My Outgoing Reviews[white]\n"
str = str + widget.displayMyOutgoingReviews(project, wtf.Config.UString("wtf.mods.gerrit.username"))
widget.View.SetText(str)
}
func (widget *Widget) displayMyOutgoingReviews(project *GerritProject, username string) string {
ors := project.myOutgoingReviews(username)
if len(ors) == 0 {
return " [grey]none[white]\n"
}
str := ""
for _, r := range ors {
str = str + fmt.Sprintf(" [green]%4s[white] %s\n", r.ChangeID, r.Subject)
}
return str
}
func (widget *Widget) displayMyIncomingReviews(project *GerritProject, username string) string {
irs := project.myIncomingReviews(username)
if len(irs) == 0 {
return " [grey]none[white]\n"
}
str := ""
for _, r := range irs {
str = str + fmt.Sprintf(" [green]%4s[white] %s\n", r.ChangeID, r.Subject)
}
return str
}
func (widget *Widget) displayStats(project *GerritProject) string {
str := fmt.Sprintf(
" Reviews: %d\n",
project.ReviewCount(),
)
return str
}
func (widget *Widget) title(project *GerritProject) string {
return fmt.Sprintf("[green]%s [white]", project.Path)
}

100
gerrit/gerrit_repo.go Normal file
View File

@ -0,0 +1,100 @@
package gerrit
import (
glb "github.com/andygrunwald/go-gerrit"
)
type GerritProject struct {
gerrit *glb.Client
Path string
Changes *[]glb.ChangeInfo
}
func NewGerritProject(path string, gerrit *glb.Client) *GerritProject {
project := GerritProject{
gerrit: gerrit,
Path: path,
}
return &project
}
// Refresh reloads the gerrit data via the Gerrit API
func (project *GerritProject) Refresh() {
project.Changes, _ = project.loadChanges()
}
/* -------------------- Counts -------------------- */
func (project *GerritProject) IssueCount() int {
if project.Changes == nil {
return 0
}
return len(*project.Changes)
}
func (project *GerritProject) ReviewCount() int {
if project.Changes == nil {
return 0
}
return len(*project.Changes)
}
/* -------------------- Unexported Functions -------------------- */
// myOutgoingReviews returns a list of my outgoing reviews created by username on this project
func (project *GerritProject) myOutgoingReviews(username string) []glb.ChangeInfo {
changes := []glb.ChangeInfo{}
if project.Changes == nil {
return changes
}
for _, change := range *project.Changes {
user := change.Owner
if user.Username == username {
changes = append(changes, change)
}
}
return changes
}
// myIncomingReviews returns a list of merge requests for which username has been requested to ChangeInfo
func (project *GerritProject) myIncomingReviews(username string) []glb.ChangeInfo {
changes := []glb.ChangeInfo{}
if project.Changes == nil {
return changes
}
for _, change := range *project.Changes {
reviewers := change.Reviewers
for _, reviewer := range reviewers["REVIEWER"] {
if reviewer.Username == username {
changes = append(changes, change)
}
}
}
return changes
}
func (project *GerritProject) loadChanges() (*[]glb.ChangeInfo, error) {
opt := &glb.QueryChangeOptions{}
opt.Query = []string{"(projects:" + project.Path + "+ is:open + owner:self) " + " OR " +
"(projects:" + project.Path + " + is:open + ((reviewer:self + -owner:self + -star:ignore) + OR + assignee:self))"}
opt.AdditionalFields = []string{"DETAILED_LABELS", "DETAILED_ACCOUNTS"}
changes, _, err := project.gerrit.Changes.QueryChanges(opt)
if err != nil {
return nil, err
}
return changes, err
}

180
gerrit/widget.go Normal file
View File

@ -0,0 +1,180 @@
package gerrit
import (
"crypto/tls"
"fmt"
glb "github.com/andygrunwald/go-gerrit"
"github.com/gdamore/tcell"
"github.com/rivo/tview"
"github.com/senorprogrammer/wtf/wtf"
"net/http"
"os"
"regexp"
)
const HelpText = `
Keyboard commands for Gerrit:
/: Show/hide this help window
h: Previous project
l: Next project
r: Refresh the data
arrow left: Previous project
arrow right: Next project
`
type Widget struct {
wtf.TextWidget
app *tview.Application
pages *tview.Pages
gerrit *glb.Client
GerritProjects []*GerritProject
Idx int
}
var (
GerritURLPattern = regexp.MustCompile(`^(http|https)://(.*)$`)
)
func NewWidget(app *tview.Application, pages *tview.Pages) *Widget {
baseURL := wtf.Config.UString("wtf.mods.gerrit.domain")
username := wtf.Config.UString("wtf.mods.gerrit.username")
password := os.Getenv("WTF_GERRIT_PASSWORD")
verifyServerCertificate := wtf.Config.UBool("wtf.mods.gerrit.verifyServerCertificate", true)
httpClient := &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: !verifyServerCertificate,
},
},
}
gerritUrl := baseURL
submatches := GerritURLPattern.FindAllStringSubmatch(baseURL, -1)
if len(submatches) > 0 && len(submatches[0]) > 2 {
submatch := submatches[0]
gerritUrl = fmt.Sprintf(
"%s://%s:%s@%s", submatch[1], username, password, submatch[2])
}
gerrit, err := glb.NewClient(gerritUrl, httpClient)
if err != nil {
panic(err)
}
widget := Widget{
TextWidget: wtf.NewTextWidget(" Gerrit ", "gerrit", true),
app: app,
pages: pages,
gerrit: gerrit,
Idx: 0,
}
widget.GerritProjects = widget.buildProjectCollection(wtf.Config.UList("wtf.mods.gerrit.projects"))
widget.View.SetInputCapture(widget.keyboardIntercept)
return &widget
}
/* -------------------- Exported Functions -------------------- */
func (widget *Widget) Refresh() {
for _, project := range widget.GerritProjects {
project.Refresh()
}
widget.UpdateRefreshedAt()
widget.display()
}
func (widget *Widget) Next() {
widget.Idx = widget.Idx + 1
if widget.Idx == len(widget.GerritProjects) {
widget.Idx = 0
}
widget.display()
}
func (widget *Widget) Prev() {
widget.Idx = widget.Idx - 1
if widget.Idx < 0 {
widget.Idx = len(widget.GerritProjects) - 1
}
widget.display()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) buildProjectCollection(projectData []interface{}) []*GerritProject {
gerritProjects := []*GerritProject{}
for _, name := range projectData {
project := NewGerritProject(name.(string), widget.gerrit)
gerritProjects = append(gerritProjects, project)
}
return gerritProjects
}
func (widget *Widget) currentGerritProject() *GerritProject {
if len(widget.GerritProjects) == 0 {
return nil
}
if widget.Idx < 0 || widget.Idx >= len(widget.GerritProjects) {
return nil
}
return widget.GerritProjects[widget.Idx]
}
func (widget *Widget) keyboardIntercept(event *tcell.EventKey) *tcell.EventKey {
switch string(event.Rune()) {
case "/":
widget.showHelp()
return nil
case "h":
widget.Prev()
return nil
case "l":
widget.Next()
return nil
case "r":
widget.Refresh()
return nil
}
switch event.Key() {
case tcell.KeyLeft:
widget.Prev()
return nil
case tcell.KeyRight:
widget.Next()
return nil
default:
return event
}
}
func (widget *Widget) showHelp() {
closeFunc := func() {
widget.pages.RemovePage("help")
widget.app.SetFocus(widget.View)
}
modal := wtf.NewBillboardModal(HelpText, closeFunc)
widget.pages.AddPage("help", modal, false, true)
widget.app.SetFocus(modal)
}

View File

@ -1,4 +1,4 @@
// Copyright 2014 Google Inc. All Rights Reserved.
// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -64,7 +64,7 @@ var (
)
var (
metaClient = &http.Client{
defaultClient = &Client{hc: &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
@ -72,15 +72,15 @@ var (
}).Dial,
ResponseHeaderTimeout: 2 * time.Second,
},
}
subscribeClient = &http.Client{
}}
subscribeClient = &Client{hc: &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
},
}
}}
)
// NotDefinedError is returned when requested metadata is not defined.
@ -95,74 +95,16 @@ func (suffix NotDefinedError) Error() string {
return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
}
// Get returns a value from the metadata service.
// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
//
// If the GCE_METADATA_HOST environment variable is not defined, a default of
// 169.254.169.254 will be used instead.
//
// If the requested metadata is not defined, the returned error will
// be of type NotDefinedError.
func Get(suffix string) (string, error) {
val, _, err := getETag(metaClient, suffix)
return val, err
}
// getETag returns a value from the metadata service as well as the associated
// ETag using the provided client. This func is otherwise equivalent to Get.
func getETag(client *http.Client, suffix string) (value, etag string, err error) {
// Using a fixed IP makes it very difficult to spoof the metadata service in
// a container, which is an important use-case for local testing of cloud
// deployments. To enable spoofing of the metadata service, the environment
// variable GCE_METADATA_HOST is first inspected to decide where metadata
// requests shall go.
host := os.Getenv(metadataHostEnv)
if host == "" {
// Using 169.254.169.254 instead of "metadata" here because Go
// binaries built with the "netgo" tag and without cgo won't
// know the search suffix for "metadata" is
// ".google.internal", and this IP address is documented as
// being stable anyway.
host = metadataIP
}
url := "http://" + host + "/computeMetadata/v1/" + suffix
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Metadata-Flavor", "Google")
req.Header.Set("User-Agent", userAgent)
res, err := client.Do(req)
if err != nil {
return "", "", err
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return "", "", NotDefinedError(suffix)
}
if res.StatusCode != 200 {
return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
}
all, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", "", err
}
return string(all), res.Header.Get("Etag"), nil
}
func getTrimmed(suffix string) (s string, err error) {
s, err = Get(suffix)
s = strings.TrimSpace(s)
return
}
func (c *cachedValue) get() (v string, err error) {
func (c *cachedValue) get(cl *Client) (v string, err error) {
defer c.mu.Unlock()
c.mu.Lock()
if c.v != "" {
return c.v, nil
}
if c.trim {
v, err = getTrimmed(c.k)
v, err = cl.getTrimmed(c.k)
} else {
v, err = Get(c.k)
v, err = cl.Get(c.k)
}
if err == nil {
c.v = v
@ -201,7 +143,7 @@ func testOnGCE() bool {
go func() {
req, _ := http.NewRequest("GET", "http://"+metadataIP, nil)
req.Header.Set("User-Agent", userAgent)
res, err := ctxhttp.Do(ctx, metaClient, req)
res, err := ctxhttp.Do(ctx, defaultClient.hc, req)
if err != nil {
resc <- false
return
@ -266,6 +208,255 @@ func systemInfoSuggestsGCE() bool {
return name == "Google" || name == "Google Compute Engine"
}
// Subscribe calls Client.Subscribe on a client designed for subscribing (one with no
// ResponseHeaderTimeout).
func Subscribe(suffix string, fn func(v string, ok bool) error) error {
return subscribeClient.Subscribe(suffix, fn)
}
// Get calls Client.Get on the default client.
func Get(suffix string) (string, error) { return defaultClient.Get(suffix) }
// ProjectID returns the current instance's project ID string.
func ProjectID() (string, error) { return defaultClient.ProjectID() }
// NumericProjectID returns the current instance's numeric project ID.
func NumericProjectID() (string, error) { return defaultClient.NumericProjectID() }
// InternalIP returns the instance's primary internal IP address.
func InternalIP() (string, error) { return defaultClient.InternalIP() }
// ExternalIP returns the instance's primary external (public) IP address.
func ExternalIP() (string, error) { return defaultClient.ExternalIP() }
// Hostname returns the instance's hostname. This will be of the form
// "<instanceID>.c.<projID>.internal".
func Hostname() (string, error) { return defaultClient.Hostname() }
// InstanceTags returns the list of user-defined instance tags,
// assigned when initially creating a GCE instance.
func InstanceTags() ([]string, error) { return defaultClient.InstanceTags() }
// InstanceID returns the current VM's numeric instance ID.
func InstanceID() (string, error) { return defaultClient.InstanceID() }
// InstanceName returns the current VM's instance ID string.
func InstanceName() (string, error) { return defaultClient.InstanceName() }
// Zone returns the current VM's zone, such as "us-central1-b".
func Zone() (string, error) { return defaultClient.Zone() }
// InstanceAttributes calls Client.InstanceAttributes on the default client.
func InstanceAttributes() ([]string, error) { return defaultClient.InstanceAttributes() }
// ProjectAttributes calls Client.ProjectAttributes on the default client.
func ProjectAttributes() ([]string, error) { return defaultClient.ProjectAttributes() }
// InstanceAttributeValue calls Client.InstanceAttributeValue on the default client.
func InstanceAttributeValue(attr string) (string, error) {
return defaultClient.InstanceAttributeValue(attr)
}
// ProjectAttributeValue calls Client.ProjectAttributeValue on the default client.
func ProjectAttributeValue(attr string) (string, error) {
return defaultClient.ProjectAttributeValue(attr)
}
// Scopes calls Client.Scopes on the default client.
func Scopes(serviceAccount string) ([]string, error) { return defaultClient.Scopes(serviceAccount) }
func strsContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}
// A Client provides metadata.
type Client struct {
hc *http.Client
}
// NewClient returns a Client that can be used to fetch metadata. All HTTP requests
// will use the given http.Client instead of the default client.
func NewClient(c *http.Client) *Client {
return &Client{hc: c}
}
// getETag returns a value from the metadata service as well as the associated ETag.
// This func is otherwise equivalent to Get.
func (c *Client) getETag(suffix string) (value, etag string, err error) {
// Using a fixed IP makes it very difficult to spoof the metadata service in
// a container, which is an important use-case for local testing of cloud
// deployments. To enable spoofing of the metadata service, the environment
// variable GCE_METADATA_HOST is first inspected to decide where metadata
// requests shall go.
host := os.Getenv(metadataHostEnv)
if host == "" {
// Using 169.254.169.254 instead of "metadata" here because Go
// binaries built with the "netgo" tag and without cgo won't
// know the search suffix for "metadata" is
// ".google.internal", and this IP address is documented as
// being stable anyway.
host = metadataIP
}
url := "http://" + host + "/computeMetadata/v1/" + suffix
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Metadata-Flavor", "Google")
req.Header.Set("User-Agent", userAgent)
res, err := c.hc.Do(req)
if err != nil {
return "", "", err
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return "", "", NotDefinedError(suffix)
}
if res.StatusCode != 200 {
return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
}
all, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", "", err
}
return string(all), res.Header.Get("Etag"), nil
}
// Get returns a value from the metadata service.
// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
//
// If the GCE_METADATA_HOST environment variable is not defined, a default of
// 169.254.169.254 will be used instead.
//
// If the requested metadata is not defined, the returned error will
// be of type NotDefinedError.
func (c *Client) Get(suffix string) (string, error) {
val, _, err := c.getETag(suffix)
return val, err
}
func (c *Client) getTrimmed(suffix string) (s string, err error) {
s, err = c.Get(suffix)
s = strings.TrimSpace(s)
return
}
func (c *Client) lines(suffix string) ([]string, error) {
j, err := c.Get(suffix)
if err != nil {
return nil, err
}
s := strings.Split(strings.TrimSpace(j), "\n")
for i := range s {
s[i] = strings.TrimSpace(s[i])
}
return s, nil
}
// ProjectID returns the current instance's project ID string.
func (c *Client) ProjectID() (string, error) { return projID.get(c) }
// NumericProjectID returns the current instance's numeric project ID.
func (c *Client) NumericProjectID() (string, error) { return projNum.get(c) }
// InstanceID returns the current VM's numeric instance ID.
func (c *Client) InstanceID() (string, error) { return instID.get(c) }
// InternalIP returns the instance's primary internal IP address.
func (c *Client) InternalIP() (string, error) {
return c.getTrimmed("instance/network-interfaces/0/ip")
}
// ExternalIP returns the instance's primary external (public) IP address.
func (c *Client) ExternalIP() (string, error) {
return c.getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip")
}
// Hostname returns the instance's hostname. This will be of the form
// "<instanceID>.c.<projID>.internal".
func (c *Client) Hostname() (string, error) {
return c.getTrimmed("instance/hostname")
}
// InstanceTags returns the list of user-defined instance tags,
// assigned when initially creating a GCE instance.
func (c *Client) InstanceTags() ([]string, error) {
var s []string
j, err := c.Get("instance/tags")
if err != nil {
return nil, err
}
if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil {
return nil, err
}
return s, nil
}
// InstanceName returns the current VM's instance ID string.
func (c *Client) InstanceName() (string, error) {
host, err := c.Hostname()
if err != nil {
return "", err
}
return strings.Split(host, ".")[0], nil
}
// Zone returns the current VM's zone, such as "us-central1-b".
func (c *Client) Zone() (string, error) {
zone, err := c.getTrimmed("instance/zone")
// zone is of the form "projects/<projNum>/zones/<zoneName>".
if err != nil {
return "", err
}
return zone[strings.LastIndex(zone, "/")+1:], nil
}
// InstanceAttributes returns the list of user-defined attributes,
// assigned when initially creating a GCE VM instance. The value of an
// attribute can be obtained with InstanceAttributeValue.
func (c *Client) InstanceAttributes() ([]string, error) { return c.lines("instance/attributes/") }
// ProjectAttributes returns the list of user-defined attributes
// applying to the project as a whole, not just this VM. The value of
// an attribute can be obtained with ProjectAttributeValue.
func (c *Client) ProjectAttributes() ([]string, error) { return c.lines("project/attributes/") }
// InstanceAttributeValue returns the value of the provided VM
// instance attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// InstanceAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func (c *Client) InstanceAttributeValue(attr string) (string, error) {
return c.Get("instance/attributes/" + attr)
}
// ProjectAttributeValue returns the value of the provided
// project attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// ProjectAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func (c *Client) ProjectAttributeValue(attr string) (string, error) {
return c.Get("project/attributes/" + attr)
}
// Scopes returns the service account scopes for the given account.
// The account may be empty or the string "default" to use the instance's
// main account.
func (c *Client) Scopes(serviceAccount string) ([]string, error) {
if serviceAccount == "" {
serviceAccount = "default"
}
return c.lines("instance/service-accounts/" + serviceAccount + "/scopes")
}
// Subscribe subscribes to a value from the metadata service.
// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
// The suffix may contain query parameters.
@ -275,11 +466,11 @@ func systemInfoSuggestsGCE() bool {
// and ok false. Subscribe blocks until fn returns a non-nil error or the value
// is deleted. Subscribe returns the error value returned from the last call to
// fn, which may be nil when ok == false.
func Subscribe(suffix string, fn func(v string, ok bool) error) error {
func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) error {
const failedSubscribeSleep = time.Second * 5
// First check to see if the metadata value exists at all.
val, lastETag, err := getETag(subscribeClient, suffix)
val, lastETag, err := c.getETag(suffix)
if err != nil {
return err
}
@ -295,7 +486,7 @@ func Subscribe(suffix string, fn func(v string, ok bool) error) error {
suffix += "?wait_for_change=true&last_etag="
}
for {
val, etag, err := getETag(subscribeClient, suffix+url.QueryEscape(lastETag))
val, etag, err := c.getETag(suffix + url.QueryEscape(lastETag))
if err != nil {
if _, deleted := err.(NotDefinedError); !deleted {
time.Sleep(failedSubscribeSleep)
@ -310,128 +501,3 @@ func Subscribe(suffix string, fn func(v string, ok bool) error) error {
}
}
}
// ProjectID returns the current instance's project ID string.
func ProjectID() (string, error) { return projID.get() }
// NumericProjectID returns the current instance's numeric project ID.
func NumericProjectID() (string, error) { return projNum.get() }
// InternalIP returns the instance's primary internal IP address.
func InternalIP() (string, error) {
return getTrimmed("instance/network-interfaces/0/ip")
}
// ExternalIP returns the instance's primary external (public) IP address.
func ExternalIP() (string, error) {
return getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip")
}
// Hostname returns the instance's hostname. This will be of the form
// "<instanceID>.c.<projID>.internal".
func Hostname() (string, error) {
return getTrimmed("instance/hostname")
}
// InstanceTags returns the list of user-defined instance tags,
// assigned when initially creating a GCE instance.
func InstanceTags() ([]string, error) {
var s []string
j, err := Get("instance/tags")
if err != nil {
return nil, err
}
if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil {
return nil, err
}
return s, nil
}
// InstanceID returns the current VM's numeric instance ID.
func InstanceID() (string, error) {
return instID.get()
}
// InstanceName returns the current VM's instance ID string.
func InstanceName() (string, error) {
host, err := Hostname()
if err != nil {
return "", err
}
return strings.Split(host, ".")[0], nil
}
// Zone returns the current VM's zone, such as "us-central1-b".
func Zone() (string, error) {
zone, err := getTrimmed("instance/zone")
// zone is of the form "projects/<projNum>/zones/<zoneName>".
if err != nil {
return "", err
}
return zone[strings.LastIndex(zone, "/")+1:], nil
}
// InstanceAttributes returns the list of user-defined attributes,
// assigned when initially creating a GCE VM instance. The value of an
// attribute can be obtained with InstanceAttributeValue.
func InstanceAttributes() ([]string, error) { return lines("instance/attributes/") }
// ProjectAttributes returns the list of user-defined attributes
// applying to the project as a whole, not just this VM. The value of
// an attribute can be obtained with ProjectAttributeValue.
func ProjectAttributes() ([]string, error) { return lines("project/attributes/") }
func lines(suffix string) ([]string, error) {
j, err := Get(suffix)
if err != nil {
return nil, err
}
s := strings.Split(strings.TrimSpace(j), "\n")
for i := range s {
s[i] = strings.TrimSpace(s[i])
}
return s, nil
}
// InstanceAttributeValue returns the value of the provided VM
// instance attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// InstanceAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func InstanceAttributeValue(attr string) (string, error) {
return Get("instance/attributes/" + attr)
}
// ProjectAttributeValue returns the value of the provided
// project attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// ProjectAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func ProjectAttributeValue(attr string) (string, error) {
return Get("project/attributes/" + attr)
}
// Scopes returns the service account scopes for the given account.
// The account may be empty or the string "default" to use the instance's
// main account.
func Scopes(serviceAccount string) ([]string, error) {
if serviceAccount == "" {
serviceAccount = "default"
}
return lines("instance/service-accounts/" + serviceAccount + "/scopes")
}
func strsContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}

View File

@ -5,6 +5,8 @@
package trello
import "fmt"
type Label struct {
ID string `json:"id"`
IDBoard string `json:"idBoard"`
@ -12,3 +14,15 @@ type Label struct {
Color string `json:"color"`
Uses int `json:"uses"`
}
func (c *Client) GetLabel(labelID string, args Arguments) (label *Label, err error) {
path := fmt.Sprintf("labels/%s", labelID)
err = c.Get(path, args, &label)
return
}
func (b *Board) GetLabels(args Arguments) (labels []*Label, err error) {
path := fmt.Sprintf("boards/%s/labels", b.ID)
err = b.client.Get(path, args, &labels)
return
}

1
vendor/github.com/andygrunwald/go-gerrit/.gitignore generated vendored Normal file
View File

@ -0,0 +1 @@
/coverage.txt

17
vendor/github.com/andygrunwald/go-gerrit/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,17 @@
language: go
sudo: false
go:
- "1.10.x"
- "1.9.x"
- "1.8.x"
before_install:
- make deps
script:
- make
after_success:
- bash <(curl -s https://codecov.io/bash)

105
vendor/github.com/andygrunwald/go-gerrit/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,105 @@
# Changelog
This is a high level log of changes, bugfixes, enhancements, etc
that have taken place between releases. Later versions are shown
first. For more complete details see
[the releases on GitHub.](https://github.com/andygrunwald/go-gerrit/releases)
## Versions
### Latest
### 0.5.2
* Fix panic in checkAuth() if Gerrit is down #42
* Implement ListVotes(), DeleteVotes() and add missing tests
### 0.5.1
* Added the `AbandonChange`, `RebaseChange`, `RestoreChange` and
`RevertChange` functions.
### 0.5.0
**WARNING**: This release includes breaking changes.
* [BREAKING CHANGE] The SetReview function was returning the wrong
entity type. (#40)
### 0.4.0
**WARNING**: This release includes breaking changes.
* [BREAKING CHANGE] - Added gometalinter to the build and fixed problems
discovered by the linters.
* Comment and error string fixes.
* Numerous lint and styling fixes.
* Ensured error values are being properly checked where appropriate.
* Addition of missing documentation
* Removed filePath parameter from DeleteChangeEdit which was unused and
unnecessary for the request.
* Fixed CherryPickRevision and IncludeGroups functions which didn't pass
along the provided input structs into the request.
* Go 1.5 has been removed from testing on Travis. The linters introduced in
0.4.0 do not support this version, Go 1.5 is lacking security updates and
most Linux distros have moved beyond Go 1.5 now.
* Add Go 1.9 to the Travis matrix.
* Fixed an issue where urls containing certain characters in the credentials
could cause NewClient() to use an invalid url. Something like `/`, which
Gerrit could use for generated passwords, for example would break url.Parse's
expectations.
### 0.3.0
**WARNING**: This release includes breaking changes.
* [BREAKING CHANGE] Fix Changes.PublishDraftChange to accept a notify parameter.
* [BREAKING CHANGE] Fix PublishChangeEdit to accept a notify parameter.
* [BREAKING CHANGE] Fix ChangeFileContentInChangeEdit to allow the file content
to be included in the request.
* Fix the url being used by CreateChange
* Fix type serialization of EventInfo.PatchSet.Number so it's consistent.
* Fix Changes.AddReviewer so it passes along the reviewer to the request.
* Simplify and optimize RemoveMagicPrefixLine
### 0.2.0
**WARNING**: This release includes breaking changes.
* [BREAKING CHANGE] Several bugfixes to GetEvents:
* Update EventInfo to handle the changeKey field and apply
the proper type for the Project field
* Provide a means to ignore marshaling errors
* Update GetEvents() to return the failed lines and remove
the pointer to the return value because it's unnecessary.
* [BREAKING CHANGE] In ec28f77 `ChangeInfo.Labels` has been changed to map
to fix #21.
### 0.1.1
* Minor fix to SubmitChange to use the `http.StatusConflict` constant
instead of a hard coded value when comparing response codes.
* Updated AccountInfo.AccountID to be omitted of empty (such as when
used in ApprovalInfo).
* + and : in url parameters for queries are no longer escaped. This was
causing `400 Bad Request` to be returned when the + symbol was
included as part of the query. To match behavior with Gerrit's search
handling, the : symbol was also excluded.
* Fixed documentation for NewClient and moved fmt.Errorf call from
inside the function to a `ErrNoInstanceGiven` variable so it's
easier to compare against.
* Updated internal function digestAuthHeader to return exported errors
(ErrWWWAuthenticateHeader*) rather than calling fmt.Errorf. This makes
it easier to test against externally and also fixes a lint issue too.
* Updated NewClient function to handle credentials in the url.
* Added the missing `Submitted` field to `ChangeInfo`.
* Added the missing `URL` field to `ChangeInfo` which is usually included
as part of an event from the events-log plugin.
### 0.1.0
* The first official release
* Implemented digest auth and several fixes for it.
* Ensured Content-Type is included in all requests
* Fixed several internal bugs as well as a few documentation issues

22
vendor/github.com/andygrunwald/go-gerrit/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Andy Grunwald
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

26
vendor/github.com/andygrunwald/go-gerrit/Makefile generated vendored Normal file
View File

@ -0,0 +1,26 @@
.PHONY: fmt vet check-vendor lint check clean test build
PACKAGES = $(shell go list ./...)
PACKAGE_DIRS = $(shell go list -f '{{ .Dir }}' ./...)
check: test vet lint
test:
go test -v -race -coverprofile=coverage.txt -covermode=atomic ./...
vet:
go vet $(PACKAGES) || (go clean $(PACKAGES); go vet $(PACKAGES))
lint:
gometalinter --config gometalinter.json ./...
fmt:
go fmt $(PACKAGES)
goimports -w $(PACKAGE_DIRS)
deps:
go get -t -v ./...
go get github.com/axw/gocov/gocov
go get golang.org/x/tools/cmd/cover
[ -f $(GOPATH)/bin/gometalinter ] || go get -u github.com/alecthomas/gometalinter
[ -f $(GOPATH)/bin/goimports ] || go get golang.org/x/tools/cmd/goimports
gometalinter --install

270
vendor/github.com/andygrunwald/go-gerrit/README.md generated vendored Normal file
View File

@ -0,0 +1,270 @@
# go-gerrit
[![GoDoc](https://godoc.org/github.com/andygrunwald/go-gerrit?status.svg)](https://godoc.org/github.com/andygrunwald/go-gerrit)
[![Build Status](https://travis-ci.org/andygrunwald/go-gerrit.svg?branch=master)](https://travis-ci.org/andygrunwald/go-gerrit)
[![Go Report Card](https://goreportcard.com/badge/github.com/andygrunwald/go-gerrit)](https://goreportcard.com/report/github.com/andygrunwald/go-gerrit)
[![codecov](https://codecov.io/gh/andygrunwald/go-gerrit/branch/master/graph/badge.svg)](https://codecov.io/gh/andygrunwald/go-gerrit)
go-gerrit is a [Go(lang)](https://golang.org/) client library for accessing the [Gerrit Code Review](https://www.gerritcodereview.com/) API.
![go-gerrit - Go(lang) client/library for Gerrit Code Review](./img/logo.png "go-gerrit - Go(lang) client/library for Gerrit Code Review")
## Features
* [Authentication](https://godoc.org/github.com/andygrunwald/go-gerrit#AuthenticationService) (HTTP Basic, HTTP Digest, HTTP Cookie)
* Every API Endpoint like Gerrit
* [/access/](https://godoc.org/github.com/andygrunwald/go-gerrit#AccessService)
* [/accounts/](https://godoc.org/github.com/andygrunwald/go-gerrit#AccountsService)
* [/changes/](https://godoc.org/github.com/andygrunwald/go-gerrit#ChangesService)
* [/config/](https://godoc.org/github.com/andygrunwald/go-gerrit#ConfigService)
* [/groups/](https://godoc.org/github.com/andygrunwald/go-gerrit#GroupsService)
* [/plugins/](https://godoc.org/github.com/andygrunwald/go-gerrit#PluginsService)
* [/projects/](https://godoc.org/github.com/andygrunwald/go-gerrit#ProjectsService)
* Supports optional plugin APIs such as
* events-log - [About](https://gerrit.googlesource.com/plugins/events-log/+/master/src/main/resources/Documentation/about.md), [REST API](https://gerrit.googlesource.com/plugins/events-log/+/master/src/main/resources/Documentation/rest-api-events.md)
## Installation
go-gerrit requires Go version 1.8 or greater.
It is go gettable ...
```sh
$ go get github.com/andygrunwald/go-gerrit
```
... (optional) to run checks and tests:
**Tests Only**
```sh
$ cd $GOPATH/src/github.com/andygrunwald/go-gerrit
$ go test -v
```
**Checks, Tests, Linters, etc**
```sh
$ cd $GOPATH/src/github.com/andygrunwald/go-gerrit
$ make
```
## API / Usage
Please have a look at the [GoDoc documentation](https://godoc.org/github.com/andygrunwald/go-gerrit) for a detailed API description.
The [Gerrit Code Review - REST API](https://gerrit-review.googlesource.com/Documentation/rest-api.html) was the base document.
### Authentication
Gerrit support multiple ways for [authentication](https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication).
#### HTTP Basic
Some Gerrit instances (like [TYPO3](https://review.typo3.org/)) has [auth.gitBasicAuth](https://gerrit-review.googlesource.com/Documentation/config-gerrit.html#auth.gitBasicAuth) activated.
With this you can authenticate with HTTP Basic like this:
```go
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 an `401 Unauthorized`, check your Account Settings and have a look at the `HTTP Password` configuration.
#### HTTP Digest
Some Gerrit instances (like [Wikimedia](https://gerrit.wikimedia.org/)) has [Digest access authentication](https://en.wikipedia.org/wiki/Digest_access_authentication) activated.
```go
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 digest auth is not supported by the choosen Gerrit instance, an error like `WWW-Authenticate header type is not Digest` is thrown.
If you get an `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(lang)](https://go-review.googlesource.com/), [Android](https://android-review.googlesource.com/) or [Gerrit](https://gerrit-review.googlesource.com/)) 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 `git-your@email.com=SomeHash...`.
```go
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.
```
### More more more
In the examples chapter below you will find a few more examples.
If you miss one or got a question how to do something please [open a new issue](https://github.com/andygrunwald/go-gerrit/issues/new) with your question.
We will be happy to answer them.
## Examples
Further a few examples how the API can be used.
A few more examples are available in the [GoDoc examples section](https://godoc.org/github.com/andygrunwald/go-gerrit#pkg-examples).
### Get version of Gerrit instance
Receive the version of the [Gerrit instance used by the Gerrit team](https://gerrit-review.googlesource.com/) for development:
```go
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()
fmt.Printf("Version: %s", v)
// Version: 2.12.2-2512-g0b1bccd
}
```
### Get all public projects
List all projects from [Chromium](https://chromium-review.googlesource.com/):
```go
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)
for name, p := range *projects {
fmt.Printf("%s - State: %s\n", name, p.State)
}
// chromiumos/platform/depthcharge - State: ACTIVE
// external/github.com/maruel/subcommands - State: ACTIVE
// external/junit - State: ACTIVE
// ...
}
```
### Query changes
Get some changes of the [kernel/common project](https://android-review.googlesource.com/#/q/project:kernel/common) from the [Android](http://source.android.com/) [Gerrit Review System](https://android-review.googlesource.com/).
```go
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)
for _, change := range *changes {
fmt.Printf("Project: %s -> %s -> %s%d\n", change.Project, change.Subject, instance, change.Number)
}
// Project: kernel/common -> android: binder: Fix BR_ERROR usage and change LSM denials to use it. -> https://android-review.googlesource.com/150839
// Project: kernel/common -> android: binder: fix duplicate error return. -> https://android-review.googlesource.com/155031
// Project: kernel/common -> dm-verity: Add modes and emit uevent on corrupted blocks -> https://android-review.googlesource.com/169572
// ...
}
```
## FAQ
### How is the source code organized?
The source code organisation was inspired by [go-github by Google](https://github.com/google/go-github).
Every REST API Endpoint (e.g. [/access/](https://gerrit-review.googlesource.com/Documentation/rest-api-access.html) or [/changes/](https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html)) is coupled in a service (e.g. [AccessService in access.go](./access.go) or [ChangesService in changes.go](./changes.go)).
Every service is part of [gerrit.Client](./gerrit.go) as a member variable.
gerrit.Client can provide basic helper functions to avoid unnecessary code duplications such as building a new request, parse responses and so on.
Based on this structure implementing a new API functionality is straight forwarded. Here is an example of *ChangeService.DeleteTopic* / [DELETE /changes/{change-id}/topic](https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-topic):
```go
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](https://github.com/andygrunwald/go-gerrit/issues/new) or try to fix it.
We welcome contribution!
### What about adding code to support the REST API of an optional plugin?
It will depend on the plugin, you are welcome to [open a new issue](https://github.com/andygrunwald/go-gerrit/issues/new) first to propose the idea if you wish.
As an example the addition of support for events-log plugin was supported because the plugin itself is fairly
popular and 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](http://en.wikipedia.org/wiki/MIT_License).

74
vendor/github.com/andygrunwald/go-gerrit/access.go generated vendored Normal file
View File

@ -0,0 +1,74 @@
package gerrit
// AccessService contains Access Right related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html
type AccessService struct {
client *Client
}
// AccessSectionInfo describes the access rights that are assigned on a ref.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#access-section-info
type AccessSectionInfo struct {
Permissions map[string]PermissionInfo `json:"permissions"`
}
// PermissionInfo entity contains information about an assigned permission.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#permission-info
type PermissionInfo struct {
Label string `json:"label,omitempty"`
Exclusive bool `json:"exclusive"`
Rules map[string]PermissionRuleInfo `json:"rules"`
}
// PermissionRuleInfo entity contains information about a permission rule that is assigned to group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#permission-rule-info
type PermissionRuleInfo struct {
// TODO Possible values for action: ALLOW, DENY or BLOCK, INTERACTIVE and BATCH
Action string `json:"action"`
Force bool `json:"force"`
Min int `json:"min"`
Max int `json:"max"`
}
// ProjectAccessInfo entity contains information about the access rights for a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#project-access-info
type ProjectAccessInfo struct {
Revision string `json:"revision"`
InheritsFrom ProjectInfo `json:"inherits_from"`
Local map[string]AccessSectionInfo `json:"local"`
IsOwner bool `json:"is_owner"`
OwnerOf []string `json:"owner_of"`
CanUpload bool `json:"can_upload"`
CanAdd bool `json:"can_add"`
ConfigVisible bool `json:"config_visible"`
}
// ListAccessRightsOptions specifies the parameters to the AccessService.ListAccessRights.
type ListAccessRightsOptions struct {
// The projects for which the access rights should be returned must be specified as project options.
// The project can be specified multiple times.
Project []string `url:"project,omitempty"`
}
// ListAccessRights lists the access rights for projects.
// As result a map is returned that maps the project name to ProjectAccessInfo entities.
// The entries in the map are sorted by project name.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#list-access
func (s *AccessService) ListAccessRights(opt *ListAccessRightsOptions) (*map[string]ProjectAccessInfo, *Response, error) {
u := "access/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
v := new(map[string]ProjectAccessInfo)
resp, err := s.client.Call("GET", u, nil, v)
return v, resp, err
}

874
vendor/github.com/andygrunwald/go-gerrit/accounts.go generated vendored Normal file
View File

@ -0,0 +1,874 @@
package gerrit
import (
"fmt"
)
// AccountsService contains Account related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html
type AccountsService struct {
client *Client
}
// AccountInfo entity contains information about an account.
type AccountInfo struct {
AccountID int `json:"_account_id,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Username string `json:"username,omitempty"`
// Avatars lists avatars of various sizes for the account.
// This field is only populated if the avatars plugin is enabled.
Avatars []struct {
URL string `json:"url,omitempty"`
Height int `json:"height,omitempty"`
} `json:"avatars,omitempty"`
}
// SSHKeyInfo entity contains information about an SSH key of a user.
type SSHKeyInfo struct {
Seq int `json:"seq"`
SSHPublicKey string `json:"ssh_public_key"`
EncodedKey string `json:"encoded_key"`
Algorithm string `json:"algorithm"`
Comment string `json:"comment,omitempty"`
Valid bool `json:"valid"`
}
// UsernameInput entity contains information for setting the username for an account.
type UsernameInput struct {
Username string `json:"username"`
}
// QueryLimitInfo entity contains information about the Query Limit of a user.
type QueryLimitInfo struct {
Min int `json:"min"`
Max int `json:"max"`
}
// HTTPPasswordInput entity contains information for setting/generating an HTTP password.
type HTTPPasswordInput struct {
Generate bool `json:"generate,omitempty"`
HTTPPassword string `json:"http_password,omitempty"`
}
// GpgKeysInput entity contains information for adding/deleting GPG keys.
type GpgKeysInput struct {
Add []string `json:"add"`
Delete []string `json:"delete"`
}
// GpgKeyInfo entity contains information about a GPG public key.
type GpgKeyInfo struct {
ID string `json:"id,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
UserIDs []string `json:"user_ids,omitempty"`
Key string `json:"key,omitempty"`
}
// EmailInput entity contains information for registering a new email address.
type EmailInput struct {
Email string `json:"email"`
Preferred bool `json:"preferred,omitempty"`
NoConfirmation bool `json:"no_confirmation,omitempty"`
}
// EmailInfo entity contains information about an email address of a user.
type EmailInfo struct {
Email string `json:"email"`
Preferred bool `json:"preferred,omitempty"`
PendingConfirmation bool `json:"pending_confirmation,omitempty"`
}
// AccountInput entity contains information for the creation of a new account.
type AccountInput struct {
Username string `json:"username,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
SSHKey string `json:"ssh_key,omitempty"`
HTTPPassword string `json:"http_password,omitempty"`
Groups []string `json:"groups,omitempty"`
}
// AccountDetailInfo entity contains detailed information about an account.
type AccountDetailInfo struct {
AccountInfo
RegisteredOn Timestamp `json:"registered_on"`
}
// AccountNameInput entity contains information for setting a name for an account.
type AccountNameInput struct {
Name string `json:"name,omitempty"`
}
// AccountCapabilityInfo entity contains information about the global capabilities of a user.
type AccountCapabilityInfo struct {
AccessDatabase bool `json:"accessDatabase,omitempty"`
AdministrateServer bool `json:"administrateServer,omitempty"`
CreateAccount bool `json:"createAccount,omitempty"`
CreateGroup bool `json:"createGroup,omitempty"`
CreateProject bool `json:"createProject,omitempty"`
EmailReviewers bool `json:"emailReviewers,omitempty"`
FlushCaches bool `json:"flushCaches,omitempty"`
KillTask bool `json:"killTask,omitempty"`
MaintainServer bool `json:"maintainServer,omitempty"`
Priority string `json:"priority,omitempty"`
QueryLimit QueryLimitInfo `json:"queryLimit"`
RunAs bool `json:"runAs,omitempty"`
RunGC bool `json:"runGC,omitempty"`
StreamEvents bool `json:"streamEvents,omitempty"`
ViewAllAccounts bool `json:"viewAllAccounts,omitempty"`
ViewCaches bool `json:"viewCaches,omitempty"`
ViewConnections bool `json:"viewConnections,omitempty"`
ViewPlugins bool `json:"viewPlugins,omitempty"`
ViewQueue bool `json:"viewQueue,omitempty"`
}
// DiffPreferencesInfo entity contains information about the diff preferences of a user.
type DiffPreferencesInfo struct {
Context int `json:"context"`
Theme string `json:"theme"`
ExpandAllComments bool `json:"expand_all_comments,omitempty"`
IgnoreWhitespace string `json:"ignore_whitespace"`
IntralineDifference bool `json:"intraline_difference,omitempty"`
LineLength int `json:"line_length"`
ManualReview bool `json:"manual_review,omitempty"`
RetainHeader bool `json:"retain_header,omitempty"`
ShowLineEndings bool `json:"show_line_endings,omitempty"`
ShowTabs bool `json:"show_tabs,omitempty"`
ShowWhitespaceErrors bool `json:"show_whitespace_errors,omitempty"`
SkipDeleted bool `json:"skip_deleted,omitempty"`
SkipUncommented bool `json:"skip_uncommented,omitempty"`
SyntaxHighlighting bool `json:"syntax_highlighting,omitempty"`
HideTopMenu bool `json:"hide_top_menu,omitempty"`
AutoHideDiffTableHeader bool `json:"auto_hide_diff_table_header,omitempty"`
HideLineNumbers bool `json:"hide_line_numbers,omitempty"`
TabSize int `json:"tab_size"`
HideEmptyPane bool `json:"hide_empty_pane,omitempty"`
}
// DiffPreferencesInput entity contains information for setting the diff preferences of a user.
// Fields which are not set will not be updated.
type DiffPreferencesInput struct {
Context int `json:"context,omitempty"`
ExpandAllComments bool `json:"expand_all_comments,omitempty"`
IgnoreWhitespace string `json:"ignore_whitespace,omitempty"`
IntralineDifference bool `json:"intraline_difference,omitempty"`
LineLength int `json:"line_length,omitempty"`
ManualReview bool `json:"manual_review,omitempty"`
RetainHeader bool `json:"retain_header,omitempty"`
ShowLineEndings bool `json:"show_line_endings,omitempty"`
ShowTabs bool `json:"show_tabs,omitempty"`
ShowWhitespaceErrors bool `json:"show_whitespace_errors,omitempty"`
SkipDeleted bool `json:"skip_deleted,omitempty"`
SkipUncommented bool `json:"skip_uncommented,omitempty"`
SyntaxHighlighting bool `json:"syntax_highlighting,omitempty"`
HideTopMenu bool `json:"hide_top_menu,omitempty"`
AutoHideDiffTableHeader bool `json:"auto_hide_diff_table_header,omitempty"`
HideLineNumbers bool `json:"hide_line_numbers,omitempty"`
TabSize int `json:"tab_size,omitempty"`
}
// PreferencesInfo entity contains information about a users preferences.
type PreferencesInfo struct {
ChangesPerPage int `json:"changes_per_page"`
ShowSiteHeader bool `json:"show_site_header,omitempty"`
UseFlashClipboard bool `json:"use_flash_clipboard,omitempty"`
DownloadScheme string `json:"download_scheme"`
DownloadCommand string `json:"download_command"`
CopySelfOnEmail bool `json:"copy_self_on_email,omitempty"`
DateFormat string `json:"date_format"`
TimeFormat string `json:"time_format"`
RelativeDateInChangeTable bool `json:"relative_date_in_change_table,omitempty"`
SizeBarInChangeTable bool `json:"size_bar_in_change_table,omitempty"`
LegacycidInChangeTable bool `json:"legacycid_in_change_table,omitempty"`
MuteCommonPathPrefixes bool `json:"mute_common_path_prefixes,omitempty"`
ReviewCategoryStrategy string `json:"review_category_strategy"`
DiffView string `json:"diff_view"`
My []TopMenuItemInfo `json:"my"`
URLAliases string `json:"url_aliases,omitempty"`
}
// PreferencesInput entity contains information for setting the user preferences.
// Fields which are not set will not be updated.
type PreferencesInput struct {
ChangesPerPage int `json:"changes_per_page,omitempty"`
ShowSiteHeader bool `json:"show_site_header,omitempty"`
UseFlashClipboard bool `json:"use_flash_clipboard,omitempty"`
DownloadScheme string `json:"download_scheme,omitempty"`
DownloadCommand string `json:"download_command,omitempty"`
CopySelfOnEmail bool `json:"copy_self_on_email,omitempty"`
DateFormat string `json:"date_format,omitempty"`
TimeFormat string `json:"time_format,omitempty"`
RelativeDateInChangeTable bool `json:"relative_date_in_change_table,omitempty"`
SizeBarInChangeTable bool `json:"size_bar_in_change_table,omitempty"`
LegacycidInChangeTable bool `json:"legacycid_in_change_table,omitempty"`
MuteCommonPathPrefixes bool `json:"mute_common_path_prefixes,omitempty"`
ReviewCategoryStrategy string `json:"review_category_strategy,omitempty"`
DiffView string `json:"diff_view,omitempty"`
My []TopMenuItemInfo `json:"my,omitempty"`
URLAliases string `json:"url_aliases,omitempty"`
}
// CapabilityOptions specifies the parameters to filter for capabilities.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-capabilities
type CapabilityOptions struct {
// To filter the set of global capabilities the q parameter can be used.
// Filtering may decrease the response time by avoiding looking at every possible alternative for the caller.
Filter []string `url:"q,omitempty"`
}
// GetAccount returns an account as an AccountInfo entity.
// If account is "self" the current authenticated account will be returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
func (s *AccountsService) GetAccount(account string) (*AccountInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s", account)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetAccountDetails retrieves the details of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-detail
func (s *AccountsService) GetAccountDetails(accountID string) (*AccountDetailInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/detail", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(AccountDetailInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetAccountName retrieves the full name of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-name
func (s *AccountsService) GetAccountName(accountID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/name", accountID)
return getStringResponseWithoutOptions(s.client, u)
}
// GetUsername retrieves the username of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-username
func (s *AccountsService) GetUsername(accountID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/username", accountID)
return getStringResponseWithoutOptions(s.client, u)
}
// GetHTTPPassword retrieves the HTTP password of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-http-password
func (s *AccountsService) GetHTTPPassword(accountID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/password.http", accountID)
return getStringResponseWithoutOptions(s.client, u)
}
// ListAccountEmails returns the email addresses that are configured for the specified user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-emails
func (s *AccountsService) ListAccountEmails(accountID string) (*[]EmailInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/emails", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]EmailInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetAccountEmail retrieves an email address of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-email
func (s *AccountsService) GetAccountEmail(accountID, emailID string) (*EmailInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/emails/%s", accountID, emailID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(EmailInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListSSHKeys returns the SSH keys of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-ssh-keys
func (s *AccountsService) ListSSHKeys(accountID string) (*[]SSHKeyInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/sshkeys", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]SSHKeyInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetSSHKey retrieves an SSH key of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-ssh-key
func (s *AccountsService) GetSSHKey(accountID, sshKeyID string) (*SSHKeyInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/sshkeys/%s", accountID, sshKeyID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(SSHKeyInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListGPGKeys returns the GPG keys of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-gpg-keys
func (s *AccountsService) ListGPGKeys(accountID string) (*map[string]GpgKeyInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/gpgkeys", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]GpgKeyInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetGPGKey retrieves a GPG key of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-gpg-key
func (s *AccountsService) GetGPGKey(accountID, gpgKeyID string) (*GpgKeyInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/gpgkeys/%s", accountID, gpgKeyID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GpgKeyInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListAccountCapabilities returns the global capabilities that are enabled for the specified user.
// If the global capabilities for the calling user should be listed, self can be used as account-id.
// This can be used by UI tools to discover if administrative features are available to the caller, so they can hide (or show) relevant UI actions.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-capabilities
func (s *AccountsService) ListAccountCapabilities(accountID string, opt *CapabilityOptions) (*AccountCapabilityInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/capabilities", accountID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(AccountCapabilityInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListGroups lists all groups that contain the specified user as a member.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-groups
func (s *AccountsService) ListGroups(accountID string) (*[]GroupInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/groups", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetUserPreferences retrieves the users preferences.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-user-preferences
func (s *AccountsService) GetUserPreferences(accountID string) (*PreferencesInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/preferences", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(PreferencesInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetDiffPreferences retrieves the diff preferences of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-diff-preferences
func (s *AccountsService) GetDiffPreferences(accountID string) (*DiffPreferencesInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/preferences.diff", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(DiffPreferencesInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetStarredChanges gets the changes starred by the identified user account.
// This URL endpoint is functionally identical to the changes query GET /changes/?q=is:starred.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-starred-changes
func (s *AccountsService) GetStarredChanges(accountID string) (*[]ChangeInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/starred.changes", accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SuggestAccount suggests users for a given query q and result limit n.
// If result limit is not passed, then the default 10 is used.
// Returns a list of matching AccountInfo entities.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#query-account
func (s *AccountsService) SuggestAccount(opt *QueryOptions) (*[]AccountInfo, *Response, error) {
u := "accounts/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateAccount creates a new account.
// In the request body additional data for the account can be provided as AccountInput.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#create-account
func (s *AccountsService) CreateAccount(username string, input *AccountInput) (*AccountInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s", username)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetAccountName sets the full name of an account.
// The new account name must be provided in the request body inside an AccountNameInput entity.
//
// As response the new account name is returned.
// If the name was deleted the response is “204 No Content”.
// Some realms may not allow to modify the account name.
// In this case the request is rejected with “405 Method Not Allowed”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-account-name
func (s *AccountsService) SetAccountName(accountID string, input *AccountNameInput) (*string, *Response, error) {
u := fmt.Sprintf("accounts/%s/name", accountID)
// TODO Use here the getStringResponseWithoutOptions (for PUT requests)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteAccountName deletes the name of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-account-name
func (s *AccountsService) DeleteAccountName(accountID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/name", accountID)
return s.client.DeleteRequest(u, nil)
}
// DeleteActive sets the account state to inactive.
// If the account was already inactive the response is “404 Not Found”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-active
func (s *AccountsService) DeleteActive(accountID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/active", accountID)
return s.client.DeleteRequest(u, nil)
}
// DeleteHTTPPassword deletes the HTTP password of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-http-password
func (s *AccountsService) DeleteHTTPPassword(accountID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/password.http", accountID)
return s.client.DeleteRequest(u, nil)
}
// DeleteAccountEmail deletes an email address of an account.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-account-email
func (s *AccountsService) DeleteAccountEmail(accountID, emailID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/emails/%s", accountID, emailID)
return s.client.DeleteRequest(u, nil)
}
// DeleteSSHKey deletes an SSH key of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-ssh-key
func (s *AccountsService) DeleteSSHKey(accountID, sshKeyID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/sshkeys/%s", accountID, sshKeyID)
return s.client.DeleteRequest(u, nil)
}
// DeleteGPGKey deletes a GPG key of a user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-gpg-key
func (s *AccountsService) DeleteGPGKey(accountID, gpgKeyID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/gpgkeys/%s", accountID, gpgKeyID)
return s.client.DeleteRequest(u, nil)
}
// SetUsername sets a new username.
// The new username must be provided in the request body inside a UsernameInput entity.
// Once set, the username cannot be changed or deleted.
// If attempted this fails with “405 Method Not Allowed”.
//
// As response the new username is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-username
func (s *AccountsService) SetUsername(accountID string, input *UsernameInput) (*string, *Response, error) {
u := fmt.Sprintf("accounts/%s/username", accountID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetActive checks if an account is active.
//
// If the account is active the string ok is returned.
// If the account is inactive the response is “204 No Content”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-active
func (s *AccountsService) GetActive(accountID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/active", accountID)
return getStringResponseWithoutOptions(s.client, u)
}
// SetActive sets the account state to active.
//
// If the account was already active the response is “200 OK”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-active
func (s *AccountsService) SetActive(accountID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/active", accountID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// SetHTTPPassword sets/Generates the HTTP password of an account.
// The options for setting/generating the HTTP password must be provided in the request body inside a HTTPPasswordInput entity.
//
// As response the new HTTP password is returned.
// If the HTTP password was deleted the response is “204 No Content”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-http-password
func (s *AccountsService) SetHTTPPassword(accountID string, input *HTTPPasswordInput) (*string, *Response, error) {
u := fmt.Sprintf("accounts/%s/password.http", accountID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateAccountEmail registers a new email address for the user.
// A verification email is sent with a link that needs to be visited to confirm the email address, unless DEVELOPMENT_BECOME_ANY_ACCOUNT is used as authentication type.
// For the development mode email addresses are directly added without confirmation.
// A Gerrit administrator may add an email address without confirmation by setting no_confirmation in the EmailInput.
// In the request body additional data for the email address can be provided as EmailInput.
//
// As response the new email address is returned as EmailInfo entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#create-account-email
func (s *AccountsService) CreateAccountEmail(accountID, emailID string, input *EmailInput) (*EmailInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/emails/%s", accountID, emailID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(EmailInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetPreferredEmail sets an email address as preferred email address for an account.
//
// If the email address was already the preferred email address of the account the response is “200 OK”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-preferred-email
func (s *AccountsService) SetPreferredEmail(accountID, emailID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/emails/%s/preferred", accountID, emailID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// GetAvatarChangeURL retrieves the URL where the user can change the avatar image.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-avatar-change-url
func (s *AccountsService) GetAvatarChangeURL(accountID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/avatar.change.url", accountID)
return getStringResponseWithoutOptions(s.client, u)
}
// AddGPGKeys Add or delete one or more GPG keys for a user.
// The changes must be provided in the request body as a GpgKeysInput entity.
// Each new GPG key is provided in ASCII armored format, and must contain a self-signed certification matching a registered email or other identity of the user.
//
// As a response, the modified GPG keys are returned as a map of GpgKeyInfo entities, keyed by ID. Deleted keys are represented by an empty object.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#add-delete-gpg-keys
func (s *AccountsService) AddGPGKeys(accountID string, input *GpgKeysInput) (*map[string]GpgKeyInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/gpgkeys", accountID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(map[string]GpgKeyInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CheckAccountCapability checks if a user has a certain global capability.
//
// If the user has the global capability the string ok is returned.
// If the user doesnt have the global capability the response is “404 Not Found”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#check-account-capability
func (s *AccountsService) CheckAccountCapability(accountID, capabilityID string) (string, *Response, error) {
u := fmt.Sprintf("accounts/%s/capabilities/%s", accountID, capabilityID)
return getStringResponseWithoutOptions(s.client, u)
}
// SetUserPreferences sets the users preferences.
// The new preferences must be provided in the request body as a PreferencesInput entity.
//
// As result the new preferences of the user are returned as a PreferencesInfo entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-user-preferences
func (s *AccountsService) SetUserPreferences(accountID string, input *PreferencesInput) (*PreferencesInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/preferences", accountID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(PreferencesInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetDiffPreferences sets the diff preferences of a user.
// The new diff preferences must be provided in the request body as a DiffPreferencesInput entity.
//
// As result the new diff preferences of the user are returned as a DiffPreferencesInfo entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-diff-preferences
func (s *AccountsService) SetDiffPreferences(accountID string, input *DiffPreferencesInput) (*DiffPreferencesInfo, *Response, error) {
u := fmt.Sprintf("accounts/%s/preferences.diff", accountID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(DiffPreferencesInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// StarChange star a change.
// Starred changes are returned for the search query is:starred or starredby:USER and automatically notify the user whenever updates are made to the change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#star-change
func (s *AccountsService) StarChange(accountID, changeID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/starred.changes/%s", accountID, changeID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// UnstarChange nstar a change.
// Removes the starred flag, stopping notifications.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#unstar-change
func (s *AccountsService) UnstarChange(accountID, changeID string) (*Response, error) {
u := fmt.Sprintf("accounts/%s/starred.changes/%s", accountID, changeID)
return s.client.DeleteRequest(u, nil)
}
/*
Missing Account Endpoints:
Add SSH Key
Get Avatar
*/

View File

@ -0,0 +1,187 @@
package gerrit
import (
"crypto/md5" // nolint: gas
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
var (
// ErrWWWAuthenticateHeaderMissing is returned by digestAuthHeader when the WWW-Authenticate header is missing
ErrWWWAuthenticateHeaderMissing = errors.New("WWW-Authenticate header is missing")
// ErrWWWAuthenticateHeaderInvalid is returned by digestAuthHeader when the WWW-Authenticate invalid
ErrWWWAuthenticateHeaderInvalid = errors.New("WWW-Authenticate header is invalid")
// ErrWWWAuthenticateHeaderNotDigest is returned by digestAuthHeader when the WWW-Authenticate header is not 'Digest'
ErrWWWAuthenticateHeaderNotDigest = errors.New("WWW-Authenticate header type is not Digest")
)
const (
// HTTP Basic Authentication
authTypeBasic = 1
// HTTP Digest Authentication
authTypeDigest = 2
// HTTP Cookie Authentication
authTypeCookie = 3
)
// AuthenticationService contains Authentication related functions.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication
type AuthenticationService struct {
client *Client
// Storage for authentication
// Username or name of cookie
name string
// Password or value of cookie
secret string
authType int
}
// SetBasicAuth sets basic parameters for HTTP Basic auth
func (s *AuthenticationService) SetBasicAuth(username, password string) {
s.name = username
s.secret = password
s.authType = authTypeBasic
}
// SetDigestAuth sets digest parameters for HTTP Digest auth.
func (s *AuthenticationService) SetDigestAuth(username, password string) {
s.name = username
s.secret = password
s.authType = authTypeDigest
}
// digestAuthHeader is called by gerrit.Client.Do in the event the server
// returns 401 Unauthorized and authType was set to authTypeDigest. The
// resulting string is used to set the Authorization header before retrying
// the request.
func (s *AuthenticationService) digestAuthHeader(response *http.Response) (string, error) {
authenticateHeader := response.Header.Get("WWW-Authenticate")
if authenticateHeader == "" {
return "", ErrWWWAuthenticateHeaderMissing
}
split := strings.SplitN(authenticateHeader, " ", 2)
if len(split) != 2 {
return "", ErrWWWAuthenticateHeaderInvalid
}
if split[0] != "Digest" {
return "", ErrWWWAuthenticateHeaderNotDigest
}
// Iterate over all the fields from the WWW-Authenticate header
// and create a map of keys and values.
authenticate := map[string]string{}
for _, value := range strings.Split(split[1], ",") {
kv := strings.SplitN(value, "=", 2)
if len(kv) != 2 {
continue
}
key := strings.Trim(strings.Trim(kv[0], " "), "\"")
value := strings.Trim(strings.Trim(kv[1], " "), "\"")
authenticate[key] = value
}
// Gerrit usually responds without providing the algorithm. According
// to RFC2617 if no algorithm is provided then the default is to use
// MD5. At the time this code was implemented Gerrit did not appear
// to support other algorithms or provide a means of changing the
// algorithm.
if value, ok := authenticate["algorithm"]; ok {
if value != "MD5" {
return "", fmt.Errorf(
"algorithm not implemented: %s", value)
}
}
realmHeader := authenticate["realm"]
qopHeader := authenticate["qop"]
nonceHeader := authenticate["nonce"]
// If the server does not inform us what the uri is supposed
// to be then use the last requests's uri instead.
if _, ok := authenticate["uri"]; !ok {
authenticate["uri"] = response.Request.URL.Path
}
uriHeader := authenticate["uri"]
// A1
h := md5.New() // nolint: gas
A1 := fmt.Sprintf("%s:%s:%s", s.name, realmHeader, s.secret)
if _, err := io.WriteString(h, A1); err != nil {
return "", err
}
HA1 := fmt.Sprintf("%x", h.Sum(nil))
// A2
h = md5.New() // nolint: gas
A2 := fmt.Sprintf("%s:%s", response.Request.Method, uriHeader)
if _, err := io.WriteString(h, A2); err != nil {
return "", err
}
HA2 := fmt.Sprintf("%x", h.Sum(nil))
k := make([]byte, 12)
for bytes := 0; bytes < len(k); {
n, err := rand.Read(k[bytes:])
if err != nil {
return "", fmt.Errorf("cnonce generation failed: %s", err)
}
bytes += n
}
cnonce := base64.StdEncoding.EncodeToString(k)
digest := md5.New() // nolint: gas
if _, err := digest.Write([]byte(strings.Join([]string{HA1, nonceHeader, "00000001", cnonce, qopHeader, HA2}, ":"))); err != nil {
return "", err
}
responseField := fmt.Sprintf("%x", digest.Sum(nil))
return fmt.Sprintf(
`Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=00000001, qop=%s, response="%s"`,
s.name, realmHeader, nonceHeader, uriHeader, cnonce, qopHeader, responseField), nil
}
// SetCookieAuth sets basic parameters for HTTP Cookie
func (s *AuthenticationService) SetCookieAuth(name, value string) {
s.name = name
s.secret = value
s.authType = authTypeCookie
}
// HasBasicAuth checks if the auth type is HTTP Basic auth
func (s *AuthenticationService) HasBasicAuth() bool {
return s.authType == authTypeBasic
}
// HasDigestAuth checks if the auth type is HTTP Digest based
func (s *AuthenticationService) HasDigestAuth() bool {
return s.authType == authTypeDigest
}
// HasCookieAuth checks if the auth type is HTTP Cookie based
func (s *AuthenticationService) HasCookieAuth() bool {
return s.authType == authTypeCookie
}
// HasAuth checks if an auth type is used
func (s *AuthenticationService) HasAuth() bool {
return s.authType > 0
}
// ResetAuth resets all former authentification settings
func (s *AuthenticationService) ResetAuth() {
s.name = ""
s.secret = ""
s.authType = 0
}

768
vendor/github.com/andygrunwald/go-gerrit/changes.go generated vendored Normal file
View File

@ -0,0 +1,768 @@
package gerrit
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
// ChangesService contains Change related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html
type ChangesService struct {
client *Client
}
// WebLinkInfo entity describes a link to an external site.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#web-link-info
type WebLinkInfo struct {
Name string `json:"name"`
URL string `json:"url"`
ImageURL string `json:"image_url"`
}
// GitPersonInfo entity contains information about the author/committer of a commit.
type GitPersonInfo struct {
Name string `json:"name"`
Email string `json:"email"`
Date Timestamp `json:"date"`
TZ int `json:"tz"`
}
// NotifyInfo entity contains detailed information about who should be
// notified about an update
type NotifyInfo struct {
Accounts []AccountInfo `json:"accounts"`
}
// AbandonInput entity contains information for abandoning a change.
type AbandonInput struct {
Message string `json:"message,omitempty"`
Notify string `json:"notify"`
NotifyDetails []NotifyInfo `json:"notify_details"`
}
// ApprovalInfo entity contains information about an approval from a user for a label on a change.
type ApprovalInfo struct {
AccountInfo
Value int `json:"value,omitempty"`
Date string `json:"date,omitempty"`
}
// ChangeEditInput entity contains information for restoring a path within change edit.
type ChangeEditInput struct {
RestorePath string `json:"restore_path,omitempty"`
OldPath string `json:"old_path,omitempty"`
NewPath string `json:"new_path,omitempty"`
}
// ChangeEditMessageInput entity contains information for changing the commit message within a change edit.
type ChangeEditMessageInput struct {
Message string `json:"message"`
}
// ChangeMessageInfo entity contains information about a message attached to a change.
type ChangeMessageInfo struct {
ID string `json:"id"`
Author AccountInfo `json:"author,omitempty"`
Date Timestamp `json:"date"`
Message string `json:"message"`
Tag string `json:"tag,omitempty"`
RevisionNumber int `json:"_revision_number,omitempty"`
}
// CherryPickInput entity contains information for cherry-picking a change to a new branch.
type CherryPickInput struct {
Message string `json:"message"`
Destination string `json:"destination"`
}
// CommentRange entity describes the range of an inline comment.
type CommentRange struct {
StartLine int `json:"start_line"`
StartCharacter int `json:"start_character"`
EndLine int `json:"end_line"`
EndCharacter int `json:"end_character"`
}
// DiffFileMetaInfo entity contains meta information about a file diff
type DiffFileMetaInfo struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
Lines int `json:"lines"`
WebLinks []WebLinkInfo `json:"web_links,omitempty"`
}
// DiffWebLinkInfo entity describes a link on a diff screen to an external site.
type DiffWebLinkInfo struct {
Name string `json:"name"`
URL string `json:"url"`
ImageURL string `json:"image_url"`
ShowOnSideBySideDiffView bool `json:"show_on_side_by_side_diff_view"`
ShowOnUnifiedDiffView bool `json:"show_on_unified_diff_view"`
}
// FetchInfo entity contains information about how to fetch a patch set via a certain protocol.
type FetchInfo struct {
URL string `json:"url"`
Ref string `json:"ref"`
Commands map[string]string `json:"commands,omitempty"`
}
// FixInput entity contains options for fixing commits using the fix change endpoint.
type FixInput struct {
DeletePatchSetIfCommitMissing bool `json:"delete_patch_set_if_commit_missing"`
ExpectMergedAs string `json:"expect_merged_as"`
}
// GroupBaseInfo entity contains base information about the group.
type GroupBaseInfo struct {
ID int `json:"id"`
Name string `json:"name"`
}
// IncludedInInfo entity contains information about the branches a change was merged into and tags it was tagged with.
type IncludedInInfo struct {
Branches []string `json:"branches"`
Tags []string `json:"tags"`
External map[string]string `json:"external,omitempty"`
}
// ProblemInfo entity contains a description of a potential consistency problem with a change.
// These are not related to the code review process, but rather indicate some inconsistency in Gerrits database or repository metadata related to the enclosing change.
type ProblemInfo struct {
Message string `json:"message"`
Status string `json:"status,omitempty"`
Outcome string `json:"outcome,omitempty"`
}
// RebaseInput entity contains information for changing parent when rebasing.
type RebaseInput struct {
Base string `json:"base,omitempty"`
}
// RestoreInput entity contains information for restoring a change.
type RestoreInput struct {
Message string `json:"message,omitempty"`
}
// RevertInput entity contains information for reverting a change.
type RevertInput struct {
Message string `json:"message,omitempty"`
}
// ReviewInfo entity contains information about a review.
type ReviewInfo struct {
Labels map[string]int `json:"labels"`
}
// ReviewResult entity contains information regarding the updates that were
// made to a review.
type ReviewResult struct {
ReviewInfo
Reviewers map[string]AddReviewerResult `json:"reviewers,omitempty"`
Ready bool `json:"ready,omitempty"`
}
// TopicInput entity contains information for setting a topic.
type TopicInput struct {
Topic string `json:"topic,omitempty"`
}
// SubmitRecord entity describes results from a submit_rule.
type SubmitRecord struct {
Status string `json:"status"`
Ok map[string]map[string]AccountInfo `json:"ok,omitempty"`
Reject map[string]map[string]AccountInfo `json:"reject,omitempty"`
Need map[string]interface{} `json:"need,omitempty"`
May map[string]map[string]AccountInfo `json:"may,omitempty"`
Impossible map[string]interface{} `json:"impossible,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
// SubmitInput entity contains information for submitting a change.
type SubmitInput struct {
WaitForMerge bool `json:"wait_for_merge"`
}
// SubmitInfo entity contains information about the change status after submitting.
type SubmitInfo struct {
Status string `json:"status"`
OnBehalfOf string `json:"on_behalf_of,omitempty"`
}
// RuleInput entity contains information to test a Prolog rule.
type RuleInput struct {
Rule string `json:"rule"`
Filters string `json:"filters,omitempty"`
}
// ReviewerInput entity contains information for adding a reviewer to a change.
type ReviewerInput struct {
Reviewer string `json:"reviewer"`
Confirmed bool `json:"confirmed,omitempty"`
}
// ReviewInput entity contains information for adding a review to a revision.
type ReviewInput struct {
Message string `json:"message,omitempty"`
Tag string `json:"tag,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Comments map[string][]CommentInput `json:"comments,omitempty"`
StrictLabels bool `json:"strict_labels,omitempty"`
Drafts string `json:"drafts,omitempty"`
Notify string `json:"notify,omitempty"`
OmitDuplicateComments bool `json:"omit_duplicate_comments,omitempty"`
OnBehalfOf string `json:"on_behalf_of,omitempty"`
}
// RelatedChangeAndCommitInfo entity contains information about a related change and commit.
type RelatedChangeAndCommitInfo struct {
ChangeID string `json:"change_id,omitempty"`
Commit CommitInfo `json:"commit"`
ChangeNumber int `json:"_change_number,omitempty"`
RevisionNumber int `json:"_revision_number,omitempty"`
CurrentRevisionNumber int `json:"_current_revision_number,omitempty"`
Status string `json:"status,omitempty"`
}
// DiffContent entity contains information about the content differences in a file.
type DiffContent struct {
A []string `json:"a,omitempty"`
B []string `json:"b,omitempty"`
AB []string `json:"ab,omitempty"`
EditA DiffIntralineInfo `json:"edit_a,omitempty"`
EditB DiffIntralineInfo `json:"edit_b,omitempty"`
Skip int `json:"skip,omitempty"`
Common bool `json:"common,omitempty"`
}
// CommentInput entity contains information for creating an inline comment.
type CommentInput struct {
ID string `json:"id,omitempty"`
Path string `json:"path,omitempty"`
Side string `json:"side,omitempty"`
Line int `json:"line,omitempty"`
Range *CommentRange `json:"range,omitempty"`
InReplyTo string `json:"in_reply_to,omitempty"`
Updated *Timestamp `json:"updated,omitempty"`
Message string `json:"message,omitempty"`
}
// DiffIntralineInfo entity contains information about intraline edits in a file.
//
// The information consists of a list of <skip length, mark length> pairs,
// where the skip length is the number of characters between the end of
// the previous edit and the start of this edit, and the mark length is the
// number of edited characters following the skip. The start of the edits
// is from the beginning of the related diff content lines.
//
// Note that the implied newline character at the end of each line
// is included in the length calculation, and thus it is possible for
// the edits to span newlines.
type DiffIntralineInfo [][2]int
// ChangeInfo entity contains information about a change.
type ChangeInfo struct {
ID string `json:"id"`
URL string `json:"url,omitempty"`
Project string `json:"project"`
Branch string `json:"branch"`
Topic string `json:"topic,omitempty"`
ChangeID string `json:"change_id"`
Subject string `json:"subject"`
Status string `json:"status"`
Created Timestamp `json:"created"`
Updated Timestamp `json:"updated"`
Submitted *Timestamp `json:"submitted,omitempty"`
Starred bool `json:"starred,omitempty"`
Reviewed bool `json:"reviewed,omitempty"`
Mergeable bool `json:"mergeable,omitempty"`
Insertions int `json:"insertions"`
Deletions int `json:"deletions"`
Number int `json:"_number"`
Owner AccountInfo `json:"owner"`
Actions map[string]ActionInfo `json:"actions,omitempty"`
Labels map[string]LabelInfo `json:"labels,omitempty"`
PermittedLabels map[string][]string `json:"permitted_labels,omitempty"`
RemovableReviewers []AccountInfo `json:"removable_reviewers,omitempty"`
Reviewers map[string][]AccountInfo `json:"removable_reviewers,omitempty"`
Messages []ChangeMessageInfo `json:"messages,omitempty"`
CurrentRevision string `json:"current_revision,omitempty"`
Revisions map[string]RevisionInfo `json:"revisions,omitempty"`
MoreChanges bool `json:"_more_changes,omitempty"`
Problems []ProblemInfo `json:"problems,omitempty"`
BaseChange string `json:"base_change,omitempty"`
}
// LabelInfo entity contains information about a label on a change, always corresponding to the current patch set.
type LabelInfo struct {
Optional bool `json:"optional,omitempty"`
// Fields set by LABELS
Approved AccountInfo `json:"approved,omitempty"`
Rejected AccountInfo `json:"rejected,omitempty"`
Recommended AccountInfo `json:"recommended,omitempty"`
Disliked AccountInfo `json:"disliked,omitempty"`
Blocking bool `json:"blocking,omitempty"`
Value int `json:"value,omitempty"`
DefaultValue int `json:"default_value,omitempty"`
// Fields set by DETAILED_LABELS
All []ApprovalInfo `json:"all,omitempty"`
Values map[string]string `json:"values,omitempty"`
}
// RevisionInfo entity contains information about a patch set.
type RevisionInfo struct {
Draft bool `json:"draft,omitempty"`
Number int `json:"_number"`
Created Timestamp `json:"created"`
Uploader AccountInfo `json:"uploader"`
Ref string `json:"ref"`
Fetch map[string]FetchInfo `json:"fetch"`
Commit CommitInfo `json:"commit,omitempty"`
Files map[string]FileInfo `json:"files,omitempty"`
Actions map[string]ActionInfo `json:"actions,omitempty"`
Reviewed bool `json:"reviewed,omitempty"`
MessageWithFooter string `json:"messageWithFooter,omitempty"`
}
// CommentInfo entity contains information about an inline comment.
type CommentInfo struct {
PatchSet int `json:"patch_set,omitempty"`
ID string `json:"id"`
Path string `json:"path,omitempty"`
Side string `json:"side,omitempty"`
Line int `json:"line,omitempty"`
Range CommentRange `json:"range,omitempty"`
InReplyTo string `json:"in_reply_to,omitempty"`
Message string `json:"message,omitempty"`
Updated Timestamp `json:"updated"`
Author AccountInfo `json:"author,omitempty"`
}
// QueryOptions specifies global parameters to query changes / reviewers.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
type QueryOptions struct {
// Query parameter
// Clients are allowed to specify more than one query by setting the q parameter multiple times.
// In this case the result is an array of arrays, one per query in the same order the queries were given in.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/user-search.html#_search_operators
Query []string `url:"q,omitempty"`
// The n parameter can be used to limit the returned results.
// If the n query parameter is supplied and additional changes exist that match the query beyond the end, the last change object has a _more_changes: true JSON field set.
Limit int `url:"n,omitempty"`
}
// QueryChangeOptions specifies the parameters to the ChangesService.QueryChanges.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
type QueryChangeOptions struct {
QueryOptions
// The S or start query parameter can be supplied to skip a number of changes from the list.
Skip int `url:"S,omitempty"`
Start int `url:"start,omitempty"`
ChangeOptions
}
// ChangeOptions specifies the parameters for Query changes.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
type ChangeOptions struct {
// Additional fields can be obtained by adding o parameters, each option requires more database lookups and slows down the query response time to the client so they are generally disabled by default.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
AdditionalFields []string `url:"o,omitempty"`
}
// QueryChanges lists changes visible to the caller.
// The query string must be provided by the q parameter.
// The n parameter can be used to limit the returned results.
//
// The change output is sorted by the last update time, most recently updated to oldest updated.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
func (s *ChangesService) QueryChanges(opt *QueryChangeOptions) (*[]ChangeInfo, *Response, error) {
u := "changes/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetChange retrieves a change.
// Additional fields can be obtained by adding o parameters, each option requires more database lookups and slows down the query response time to the client so they are generally disabled by default.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change
func (s *ChangesService) GetChange(changeID string, opt *ChangeOptions) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s", changeID)
return s.getChangeInfoResponse(u, opt)
}
// GetChangeDetail retrieves a change with labels, detailed labels, detailed accounts, and messages.
// Additional fields can be obtained by adding o parameters, each option requires more database lookups and slows down the query response time to the client so they are generally disabled by default.
//
// This response will contain all votes for each label and include one combined vote.
// The combined label vote is calculated in the following order (from highest to lowest): REJECTED > APPROVED > DISLIKED > RECOMMENDED.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change-detail
func (s *ChangesService) GetChangeDetail(changeID string, opt *ChangeOptions) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/detail", changeID)
return s.getChangeInfoResponse(u, opt)
}
// getChangeInfoResponse retrieved a single ChangeInfo Response for a GET request
func (s *ChangesService) getChangeInfoResponse(u string, opt *ChangeOptions) (*ChangeInfo, *Response, error) {
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetTopic retrieves the topic of a change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-topic
func (s *ChangesService) GetTopic(changeID string) (string, *Response, error) {
u := fmt.Sprintf("changes/%s/topic", changeID)
return getStringResponseWithoutOptions(s.client, u)
}
// ChangesSubmittedTogether returns a list of all changes which are submitted when {submit} is called for this change, including the current change itself.
// An empty list is returned if this change will be submitted by itself (no other changes).
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submitted_together
func (s *ChangesService) ChangesSubmittedTogether(changeID string) (*[]ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/submitted_together", changeID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetIncludedIn retrieves the branches and tags in which a change is included.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-included-in
func (s *ChangesService) GetIncludedIn(changeID string) (*IncludedInInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/in", changeID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(IncludedInInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListChangeComments lists the published comments of all revisions of the change.
// The entries in the map are sorted by file path, and the comments for each path are sorted by patch set number.
// Each comment has the patch_set and author fields set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-comments
func (s *ChangesService) ListChangeComments(changeID string) (*map[string][]CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/comments", changeID)
return s.getCommentInfoMapResponse(u)
}
// ListChangeDrafts lLists the draft comments of all revisions of the change that belong to the calling user.
// The entries in the map are sorted by file path, and the comments for each path are sorted by patch set number.
// Each comment has the patch_set field set, and no author.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-drafts
func (s *ChangesService) ListChangeDrafts(changeID string) (*map[string][]CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/drafts", changeID)
return s.getCommentInfoMapResponse(u)
}
// getCommentInfoMapResponse retrieved a map of CommentInfo Response for a GET request
func (s *ChangesService) getCommentInfoMapResponse(u string) (*map[string][]CommentInfo, *Response, error) {
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string][]CommentInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CheckChange performs consistency checks on the change, and returns a ChangeInfo entity with the problems field set to a list of ProblemInfo entities.
// Depending on the type of problem, some fields not marked optional may be missing from the result.
// At least id, project, branch, and _number will be present.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#check-change
func (s *ChangesService) CheckChange(changeID string) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/check", changeID)
return s.getChangeInfoResponse(u, nil)
}
// getCommentInfoResponse retrieved a CommentInfo Response for a GET request
func (s *ChangesService) getCommentInfoResponse(u string) (*CommentInfo, *Response, error) {
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(CommentInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// getCommentInfoMapSliceResponse retrieved a map with a slice of CommentInfo Response for a GET request
func (s *ChangesService) getCommentInfoMapSliceResponse(u string) (*map[string][]CommentInfo, *Response, error) {
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string][]CommentInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateChange creates a new change.
// The change info ChangeInfo entity must be provided in the request body.
// Only the following attributes are honored: project, branch, subject, status and topic.
// The first three attributes are mandatory.
// Valid values for status are: DRAFT and NEW.
//
// As response a ChangeInfo entity is returned that describes the resulting change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#create-change
func (s *ChangesService) CreateChange(input *ChangeInfo) (*ChangeInfo, *Response, error) {
u := "changes/"
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetTopic sets the topic of a change.
// The new topic must be provided in the request body inside a TopicInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-topic
func (s *ChangesService) SetTopic(changeID string, input *TopicInput) (*string, *Response, error) {
u := fmt.Sprintf("changes/%s/topic", changeID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteTopic deletes the topic of a change.
// The request body does not need to include a TopicInput entity if no review comment is added.
//
// Please note that some proxies prohibit request bodies for DELETE requests.
// In this case, if you want to specify a commit message, use PUT to delete the topic.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-topic
func (s *ChangesService) DeleteTopic(changeID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/topic", changeID)
return s.client.DeleteRequest(u, nil)
}
// DeleteDraftChange deletes a draft change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-draft-change
func (s *ChangesService) DeleteDraftChange(changeID string) (*Response, error) {
u := fmt.Sprintf("changes/%s", changeID)
return s.client.DeleteRequest(u, nil)
}
// PublishDraftChange publishes a draft change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-draft-change
func (s *ChangesService) PublishDraftChange(changeID, notify string) (*Response, error) {
u := fmt.Sprintf("changes/%s/publish", changeID)
req, err := s.client.NewRequest("POST", u, map[string]string{
"notify": notify,
})
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// IndexChange adds or updates the change in the secondary index.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#index-change
func (s *ChangesService) IndexChange(changeID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/index", changeID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// FixChange performs consistency checks on the change as with GET /check, and additionally fixes any problems that can be fixed automatically.
// The returned field values reflect any fixes.
//
// Some fixes have options controlling their behavior, which can be set in the FixInput entity body.
// Only the change owner, a project owner, or an administrator may fix changes.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#fix-change
func (s *ChangesService) FixChange(changeID string, input *FixInput) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/check", changeID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// change is an internal function to consolidate code used by SubmitChange,
// AbandonChange and other similar functions.
func (s *ChangesService) change(tail string, changeID string, input interface{}) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/%s", changeID, tail)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(ChangeInfo)
resp, err := s.client.Do(req, v)
if resp.StatusCode == http.StatusConflict {
body, _ := ioutil.ReadAll(resp.Body)
err = errors.New(string(body[:]))
}
return v, resp, err
}
// SubmitChange submits a change.
//
// The request body only needs to include a SubmitInput entity if submitting on behalf of another user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-change
func (s *ChangesService) SubmitChange(changeID string, input *SubmitInput) (*ChangeInfo, *Response, error) {
return s.change("submit", changeID, input)
}
// AbandonChange abandons a change.
//
// The request body does not need to include a AbandonInput entity if no review
// comment is added.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#abandon-change
func (s *ChangesService) AbandonChange(changeID string, input *AbandonInput) (*ChangeInfo, *Response, error) {
return s.change("abandon", changeID, input)
}
// RebaseChange rebases a change.
//
// Optionally, the parent revision can be changed to another patch set through
// the RebaseInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#rebase-change
func (s *ChangesService) RebaseChange(changeID string, input *RebaseInput) (*ChangeInfo, *Response, error) {
return s.change("rebase", changeID, input)
}
// RestoreChange restores a change.
//
// The request body does not need to include a RestoreInput entity if no review
// comment is added.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#restore-change
func (s *ChangesService) RestoreChange(changeID string, input *RestoreInput) (*ChangeInfo, *Response, error) {
return s.change("restore", changeID, input)
}
// RevertChange reverts a change.
//
// The request body does not need to include a RevertInput entity if no
// review comment is added.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#revert-change
func (s *ChangesService) RevertChange(changeID string, input *RevertInput) (*ChangeInfo, *Response, error) {
return s.change("revert", changeID, input)
}

View File

@ -0,0 +1,231 @@
package gerrit
import (
"fmt"
"net/url"
)
// EditInfo entity contains information about a change edit.
type EditInfo struct {
Commit CommitInfo `json:"commit"`
BaseRevision string `json:"baseRevision"`
Fetch map[string]FetchInfo `json:"fetch"`
Files map[string]FileInfo `json:"files,omitempty"`
}
// EditFileInfo entity contains additional information of a file within a change edit.
type EditFileInfo struct {
WebLinks []WebLinkInfo `json:"web_links,omitempty"`
}
// ChangeEditDetailOptions specifies the parameters to the ChangesService.GetChangeEditDetails.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-detail
type ChangeEditDetailOptions struct {
// When request parameter list is provided the response also includes the file list.
List bool `url:"list,omitempty"`
// When base request parameter is provided the file list is computed against this base revision.
Base bool `url:"base,omitempty"`
// When request parameter download-commands is provided fetch info map is also included.
DownloadCommands bool `url:"download-commands,omitempty"`
}
// GetChangeEditDetails retrieves a change edit details.
// As response an EditInfo entity is returned that describes the change edit, or “204 No Content” when change edit doesnt exist for this change.
// Change edits are stored on special branches and there can be max one edit per user per change.
// Edits arent tracked in the database.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-detail
func (s *ChangesService) GetChangeEditDetails(changeID string, opt *ChangeEditDetailOptions) (*EditInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/edit", changeID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(EditInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// RetrieveMetaDataOfAFileFromChangeEdit retrieves meta data of a file from a change edit.
// Currently only web links are returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-meta-data
func (s *ChangesService) RetrieveMetaDataOfAFileFromChangeEdit(changeID, filePath string) (*EditFileInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/edit/%s/meta", changeID, filePath)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(EditFileInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// RetrieveCommitMessageFromChangeEdit retrieves commit message from change edit.
// The commit message is returned as base64 encoded string.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-message
func (s *ChangesService) RetrieveCommitMessageFromChangeEdit(changeID string) (string, *Response, error) {
u := fmt.Sprintf("changes/%s/edit:message", changeID)
return getStringResponseWithoutOptions(s.client, u)
}
// ChangeFileContentInChangeEdit put content of a file to a change edit.
//
// When change edit doesnt exist for this change yet it is created.
// When file content isnt provided, it is wiped out for that file.
// As response “204 No Content” is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#put-edit-file
func (s *ChangesService) ChangeFileContentInChangeEdit(changeID, filePath, content string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit/%s", changeID, url.QueryEscape(filePath))
req, err := s.client.NewRawPutRequest(u, content)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// ChangeCommitMessageInChangeEdit modify commit message.
// The request body needs to include a ChangeEditMessageInput entity.
//
// If a change edit doesnt exist for this change yet, it is created.
// As response “204 No Content” is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#put-change-edit-message
func (s *ChangesService) ChangeCommitMessageInChangeEdit(changeID string, input *ChangeEditMessageInput) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit:message", changeID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// DeleteFileInChangeEdit deletes a file from a change edit.
// This deletes the file from the repository completely.
// This is not the same as reverting or restoring a file to its previous contents.
//
// When change edit doesnt exist for this change yet it is created.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-edit-file
func (s *ChangesService) DeleteFileInChangeEdit(changeID, filePath string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit/%s", changeID, filePath)
return s.client.DeleteRequest(u, nil)
}
// DeleteChangeEdit deletes change edit.
//
// As response “204 No Content” is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-edit
func (s *ChangesService) DeleteChangeEdit(changeID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit", changeID)
return s.client.DeleteRequest(u, nil)
}
// PublishChangeEdit promotes change edit to a regular patch set.
//
// As response “204 No Content” is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-edit
func (s *ChangesService) PublishChangeEdit(changeID, notify string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit:publish", changeID)
req, err := s.client.NewRequest("POST", u, map[string]string{
"notify": notify,
})
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// RebaseChangeEdit rebases change edit on top of latest patch set.
//
// When change was rebased on top of latest patch set, response “204 No Content” is returned.
// When change edit is already based on top of the latest patch set, the response “409 Conflict” is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#rebase-edit
func (s *ChangesService) RebaseChangeEdit(changeID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit:rebase", changeID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// RetrieveFileContentFromChangeEdit retrieves content of a file from a change edit.
//
// The content of the file is returned as text encoded inside base64.
// The Content-Type header will always be text/plain reflecting the outer base64 encoding.
// A Gerrit-specific X-FYI-Content-Type header can be examined to find the server detected content type of the file.
//
// When the specified file was deleted in the change edit “204 No Content” is returned.
// If only the content type is required, callers should use HEAD to avoid downloading the encoded file contents.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-file
func (s *ChangesService) RetrieveFileContentFromChangeEdit(changeID, filePath string) (*string, *Response, error) {
u := fmt.Sprintf("changes/%s/edit/%s", changeID, filePath)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// RetrieveFileContentTypeFromChangeEdit retrieves content type of a file from a change edit.
// This is nearly the same as RetrieveFileContentFromChangeEdit.
// But if only the content type is required, callers should use HEAD to avoid downloading the encoded file contents.
//
// For further documentation please have a look at RetrieveFileContentFromChangeEdit.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-file
func (s *ChangesService) RetrieveFileContentTypeFromChangeEdit(changeID, filePath string) (*Response, error) {
u := fmt.Sprintf("changes/%s/edit/%s", changeID, filePath)
req, err := s.client.NewRequest("HEAD", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
/*
Missing Change Edit Endpoints
Restore file content or rename files in Change Edit
*/

View File

@ -0,0 +1,163 @@
package gerrit
import (
"fmt"
)
// ReviewerInfo entity contains information about a reviewer and its votes on a change.
type ReviewerInfo struct {
AccountInfo
Approvals map[string]string `json:"approvals"`
}
// SuggestedReviewerInfo entity contains information about a reviewer that can be added to a change (an account or a group).
type SuggestedReviewerInfo struct {
Account AccountInfo `json:"account,omitempty"`
Group GroupBaseInfo `json:"group,omitempty"`
}
// AddReviewerResult entity describes the result of adding a reviewer to a change.
type AddReviewerResult struct {
Input string `json:"input,omitempty"`
Reviewers []ReviewerInfo `json:"reviewers,omitempty"`
CCS []ReviewerInfo `json:"ccs,omitempty"`
Error string `json:"error,omitempty"`
Confirm bool `json:"confirm,omitempty"`
}
// DeleteVoteInput entity contains options for the deletion of a vote.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-vote-input
type DeleteVoteInput struct {
Label string `json:"label,omitempty"`
Notify string `json:"notify,omitempty"`
NotifyDetails map[string]NotifyInfo `json:"notify_details"`
}
// ListReviewers lists the reviewers of a change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-reviewers
func (s *ChangesService) ListReviewers(changeID string) (*[]ReviewerInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/reviewers/", changeID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ReviewerInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SuggestReviewers suggest the reviewers for a given query q and result limit n.
// If result limit is not passed, then the default 10 is used.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#suggest-reviewers
func (s *ChangesService) SuggestReviewers(changeID string, opt *QueryOptions) (*[]SuggestedReviewerInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/suggest_reviewers", changeID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]SuggestedReviewerInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetReviewer retrieves a reviewer of a change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-reviewer
func (s *ChangesService) GetReviewer(changeID, accountID string) (*ReviewerInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/reviewers/%s", changeID, accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(ReviewerInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// AddReviewer adds one user or all members of one group as reviewer to the change.
// The reviewer to be added to the change must be provided in the request body as a ReviewerInput entity.
//
// As response an AddReviewerResult entity is returned that describes the newly added reviewers.
// If a group is specified, adding the group members as reviewers is an atomic operation.
// This means if an error is returned, none of the members are added as reviewer.
// If a group with many members is added as reviewer a confirmation may be required.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#add-reviewer
func (s *ChangesService) AddReviewer(changeID string, input *ReviewerInput) (*AddReviewerResult, *Response, error) {
u := fmt.Sprintf("changes/%s/reviewers", changeID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(AddReviewerResult)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteReviewer deletes a reviewer from a change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-reviewer
func (s *ChangesService) DeleteReviewer(changeID, accountID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/reviewers/%s", changeID, accountID)
return s.client.DeleteRequest(u, nil)
}
// ListVotes lists the votes for a specific reviewer of the change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-votes
func (s *ChangesService) ListVotes(changeID string, accountID string) (map[string]int, *Response, error) {
u := fmt.Sprintf("changes/%s/reviewers/%s/votes/", changeID, accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var v map[string]int
resp, err := s.client.Do(req, &v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteVote deletes a single vote from a change. Note, that even when the
// last vote of a reviewer is removed the reviewer itself is still listed on
// the change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-vote
func (s *ChangesService) DeleteVote(changeID string, accountID string, label string, input *DeleteVoteInput) (*Response, error) {
u := fmt.Sprintf("changes/%s/reviewers/%s/votes/%s", changeID, accountID, label)
return s.client.DeleteRequest(u, input)
}

View File

@ -0,0 +1,651 @@
package gerrit
import (
"fmt"
"net/url"
)
// DiffInfo entity contains information about the diff of a file in a revision.
type DiffInfo struct {
MetaA DiffFileMetaInfo `json:"meta_a,omitempty"`
MetaB DiffFileMetaInfo `json:"meta_b,omitempty"`
ChangeType string `json:"change_type"`
IntralineStatus string `json:"intraline_status,omitempty"`
DiffHeader []string `json:"diff_header"`
Content []DiffContent `json:"content"`
WebLinks []DiffWebLinkInfo `json:"web_links,omitempty"`
Binary bool `json:"binary,omitempty"`
}
// RelatedChangesInfo entity contains information about related changes.
type RelatedChangesInfo struct {
Changes []RelatedChangeAndCommitInfo `json:"changes"`
}
// FileInfo entity contains information about a file in a patch set.
type FileInfo struct {
Status string `json:"status,omitempty"`
Binary bool `json:"binary,omitempty"`
OldPath string `json:"old_path,omitempty"`
LinesInserted int `json:"lines_inserted,omitempty"`
LinesDeleted int `json:"lines_deleted,omitempty"`
SizeDelta int `json:"size_delta"`
Size int `json:"size"`
}
// ActionInfo entity describes a REST API call the client can make to manipulate a resource.
// These are frequently implemented by plugins and may be discovered at runtime.
type ActionInfo struct {
Method string `json:"method,omitempty"`
Label string `json:"label,omitempty"`
Title string `json:"title,omitempty"`
Enabled bool `json:"enabled,omitempty"`
}
// CommitInfo entity contains information about a commit.
type CommitInfo struct {
Commit string `json:"commit,omitempty"`
Parents []CommitInfo `json:"parents"`
Author GitPersonInfo `json:"author"`
Committer GitPersonInfo `json:"committer"`
Subject string `json:"subject"`
Message string `json:"message"`
WebLinks []WebLinkInfo `json:"web_links,omitempty"`
}
// MergeableInfo entity contains information about the mergeability of a change.
type MergeableInfo struct {
SubmitType string `json:"submit_type"`
Mergeable bool `json:"mergeable"`
MergeableInto []string `json:"mergeable_into,omitempty"`
}
// DiffOptions specifies the parameters for GetDiff call.
type DiffOptions struct {
// If the intraline parameter is specified, intraline differences are included in the diff.
Intraline bool `url:"intraline,omitempty"`
// The base parameter can be specified to control the base patch set from which the diff
// should be generated.
Base string `url:"base,omitempty"`
// The integer-valued request parameter parent can be specified to control the parent commit number
// against which the diff should be generated. This is useful for supporting review of merge commits.
// The value is the 1-based index of the parents position in the commit object.
Parent int `url:"parent,omitempty"`
// If the weblinks-only parameter is specified, only the diff web links are returned.
WeblinksOnly bool `url:"weblinks-only,omitempty"`
// The ignore-whitespace parameter can be specified to control how whitespace differences are reported in the result. Valid values are NONE, TRAILING, CHANGED or ALL.
IgnoreWhitespace string `url:"ignore-whitespace,omitempty"`
// The context parameter can be specified to control the number of lines of surrounding context in the diff.
// Valid values are ALL or number of lines.
Context string `url:"context,omitempty"`
}
// CommitOptions specifies the parameters for GetCommit call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-commit
type CommitOptions struct {
// Adding query parameter links (for example /changes/.../commit?links) returns a CommitInfo with the additional field web_links.
Weblinks bool `url:"links,omitempty"`
}
// MergableOptions specifies the parameters for GetMergable call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-mergeable
type MergableOptions struct {
// If the other-branches parameter is specified, the mergeability will also be checked for all other branches.
OtherBranches bool `url:"other-branches,omitempty"`
}
// FilesOptions specifies the parameters for ListFiles and ListFilesReviewed calls.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files
type FilesOptions struct {
// The request parameter q changes the response to return a list of all files (modified or unmodified)
// that contain that substring in the path name. This is useful to implement suggestion services
// finding a file by partial name.
Q string `url:"q,omitempty"`
// The base parameter can be specified to control the base patch set from which the list of files
// should be generated.
//
// Note: This option is undocumented.
Base string `url:"base,omitempty"`
// The integer-valued request parameter parent changes the response to return a list of the files
// which are different in this commit compared to the given parent commit. This is useful for
// supporting review of merge commits. The value is the 1-based index of the parents position
// in the commit object.
Parent int `url:"parent,omitempty"`
}
// PatchOptions specifies the parameters for GetPatch call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-patch
type PatchOptions struct {
// Adding query parameter zip (for example /changes/.../patch?zip) returns the patch as a single file inside of a ZIP archive.
// Clients can expand the ZIP to obtain the plain text patch, avoiding the need for a base64 decoding step.
// This option implies download.
Zip bool `url:"zip,omitempty"`
// Query parameter download (e.g. /changes/.../patch?download) will suggest the browser save the patch as commitsha1.diff.base64, for later processing by command line tools.
Download bool `url:"download,omitempty"`
// If the path parameter is set, the returned content is a diff of the single file that the path refers to.
Path string `url:"path,omitempty"`
}
// GetDiff gets the diff of a file from a certain revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-diff
func (s *ChangesService) GetDiff(changeID, revisionID, fileID string, opt *DiffOptions) (*DiffInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/diff", changeID, revisionID, url.PathEscape(fileID))
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(DiffInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetRelatedChanges retrieves related changes of a revision.
// Related changes are changes that either depend on, or are dependencies of the revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-related-changes
func (s *ChangesService) GetRelatedChanges(changeID, revisionID string) (*RelatedChangesInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/related", changeID, revisionID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(RelatedChangesInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetDraft retrieves a draft comment of a revision that belongs to the calling user.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-draft
func (s *ChangesService) GetDraft(changeID, revisionID, draftID string) (*CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/drafts/%s", changeID, revisionID, draftID)
return s.getCommentInfoResponse(u)
}
// GetComment retrieves a published comment of a revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-comment
func (s *ChangesService) GetComment(changeID, revisionID, commentID string) (*CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s//comments/%s", changeID, revisionID, commentID)
return s.getCommentInfoResponse(u)
}
// GetSubmitType gets the method the server will use to submit (merge) the change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-submit-type
func (s *ChangesService) GetSubmitType(changeID, revisionID string) (string, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/submit_type", changeID, revisionID)
return getStringResponseWithoutOptions(s.client, u)
}
// GetRevisionActions retrieves revision actions of the revision of a change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-revision-actions
func (s *ChangesService) GetRevisionActions(changeID, revisionID string) (*map[string]ActionInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/actions", changeID, revisionID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]ActionInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetCommit retrieves a parsed commit of a revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-commit
func (s *ChangesService) GetCommit(changeID, revisionID string, opt *CommitOptions) (*CommitInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/commit", changeID, revisionID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(CommitInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetReview retrieves a review of a revision.
//
// As response a ChangeInfo entity with detailed labels and detailed accounts is returned that describes the review of the revision.
// The revision for which the review is retrieved is contained in the revisions field.
// In addition the current_revision field is set if the revision for which the review is retrieved is the current revision of the change.
// Please note that the returned labels are always for the current patch set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-review
func (s *ChangesService) GetReview(changeID, revisionID string) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/review", changeID, revisionID)
return s.getChangeInfoResponse(u, nil)
}
// GetMergeable gets the method the server will use to submit (merge) the change and an indicator if the change is currently mergeable.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-mergeable
func (s *ChangesService) GetMergeable(changeID, revisionID string, opt *MergableOptions) (*MergeableInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/mergeable", changeID, revisionID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(MergeableInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListRevisionDrafts lists the draft comments of a revision that belong to the calling user.
// Returns a map of file paths to lists of CommentInfo entries.
// The entries in the map are sorted by file path.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-drafts
func (s *ChangesService) ListRevisionDrafts(changeID, revisionID string) (*map[string][]CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/drafts/", changeID, revisionID)
return s.getCommentInfoMapSliceResponse(u)
}
// ListRevisionComments lists the published comments of a revision.
// As result a map is returned that maps the file path to a list of CommentInfo entries.
// The entries in the map are sorted by file path and only include file (or inline) comments.
// Use the Get Change Detail endpoint to retrieve the general change message (or comment).
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-comments
func (s *ChangesService) ListRevisionComments(changeID, revisionID string) (*map[string][]CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/comments/", changeID, revisionID)
return s.getCommentInfoMapSliceResponse(u)
}
// ListFiles lists the files that were modified, added or deleted in a revision.
// As result a map is returned that maps the file path to a list of FileInfo entries.
// The entries in the map are sorted by file path.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files
func (s *ChangesService) ListFiles(changeID, revisionID string, opt *FilesOptions) (map[string]FileInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/", changeID, revisionID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var v map[string]FileInfo
resp, err := s.client.Do(req, &v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListFilesReviewed lists the files that were modified, added or deleted in a revision.
// Unlike ListFiles, the response of ListFilesReviewed is a list of the paths the caller
// has marked as reviewed. Clients that also need the FileInfo should make two requests.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files
func (s *ChangesService) ListFilesReviewed(changeID, revisionID string, opt *FilesOptions) ([]string, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/", changeID, revisionID)
o := struct {
// The request parameter reviewed changes the response to return a list of the paths the caller has marked as reviewed.
Reviewed bool `url:"reviewed,omitempty"`
FilesOptions
}{
Reviewed: true,
}
if opt != nil {
o.FilesOptions = *opt
}
u, err := addOptions(u, o)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var v []string
resp, err := s.client.Do(req, &v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetReview sets a review on a revision.
// The review must be provided in the request body as a ReviewInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-review
func (s *ChangesService) SetReview(changeID, revisionID string, input *ReviewInput) (*ReviewResult, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/review", changeID, revisionID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(ReviewResult)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// PublishDraftRevision publishes a draft revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-draft-revision
func (s *ChangesService) PublishDraftRevision(changeID, revisionID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/publish", changeID, revisionID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// DeleteDraftRevision deletes a draft revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-draft-revision
func (s *ChangesService) DeleteDraftRevision(changeID, revisionID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s", changeID, revisionID)
return s.client.DeleteRequest(u, nil)
}
// GetPatch gets the formatted patch for one revision.
//
// The formatted patch is returned as text encoded inside base64.
// Adding query parameter zip (for example /changes/.../patch?zip) returns the patch as a single file inside of a ZIP archive.
// Clients can expand the ZIP to obtain the plain text patch, avoiding the need for a base64 decoding step.
// This option implies download.
//
// Query parameter download (e.g. /changes/.../patch?download) will suggest the browser save the patch as commitsha1.diff.base64, for later processing by command line tools.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-patch
func (s *ChangesService) GetPatch(changeID, revisionID string, opt *PatchOptions) (*string, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/patch", changeID, revisionID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// TestSubmitType tests the submit_type Prolog rule in the project, or the one given.
//
// Request body may be either the Prolog code as text/plain or a RuleInput object.
// The query parameter filters may be set to SKIP to bypass parent project filters while testing a project-specific rule.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#test-submit-type
func (s *ChangesService) TestSubmitType(changeID, revisionID string, input *RuleInput) (*string, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/test.submit_type", changeID, revisionID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// TestSubmitRule tests the submit_rule Prolog rule in the project, or the one given.
//
// Request body may be either the Prolog code as text/plain or a RuleInput object.
// The query parameter filters may be set to SKIP to bypass parent project filters while testing a project-specific rule.
//
// The response is a list of SubmitRecord entries describing the permutations that satisfy the tested submit rule.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#test-submit-rule
func (s *ChangesService) TestSubmitRule(changeID, revisionID string, input *RuleInput) (*[]SubmitRecord, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/test.submit_rule", changeID, revisionID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new([]SubmitRecord)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateDraft creates a draft comment on a revision.
// The new draft comment must be provided in the request body inside a CommentInput entity.
//
// As response a CommentInfo entity is returned that describes the draft comment.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#create-draft
func (s *ChangesService) CreateDraft(changeID, revisionID string, input *CommentInput) (*CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/drafts", changeID, revisionID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(CommentInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// UpdateDraft updates a draft comment on a revision.
// The new draft comment must be provided in the request body inside a CommentInput entity.
//
// As response a CommentInfo entity is returned that describes the draft comment.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#update-draft
func (s *ChangesService) UpdateDraft(changeID, revisionID, draftID string, input *CommentInput) (*CommentInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/drafts/%s", changeID, revisionID, draftID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(CommentInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteDraft deletes a draft comment from a revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-draft
func (s *ChangesService) DeleteDraft(changeID, revisionID, draftID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/drafts/%s", changeID, revisionID, draftID)
return s.client.DeleteRequest(u, nil)
}
// DeleteReviewed deletes the reviewed flag of the calling user from a file of a revision.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-reviewed
func (s *ChangesService) DeleteReviewed(changeID, revisionID, fileID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/reviewed", changeID, revisionID, url.PathEscape(fileID))
return s.client.DeleteRequest(u, nil)
}
// GetContent gets the content of a file from a certain revision.
// The content is returned as base64 encoded string.
// The HTTP response Content-Type is always text/plain, reflecting the base64 wrapping.
// A Gerrit-specific X-FYI-Content-Type header is returned describing the server detected content type of the file.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-content
func (s *ChangesService) GetContent(changeID, revisionID, fileID string) (*string, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/content", changeID, revisionID, url.PathEscape(fileID))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetContentType gets the content type of a file from a certain revision.
// This is nearly the same as GetContent.
// But if only the content type is required, callers should use HEAD to avoid downloading the encoded file contents.
//
// For further documentation see GetContent.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-content
func (s *ChangesService) GetContentType(changeID, revisionID, fileID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/content", changeID, revisionID, url.PathEscape(fileID))
req, err := s.client.NewRequest("HEAD", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// SetReviewed marks a file of a revision as reviewed by the calling user.
//
// If the file was already marked as reviewed by the calling user the response is “200 OK”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-reviewed
func (s *ChangesService) SetReviewed(changeID, revisionID, fileID string) (*Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/files/%s/reviewed", changeID, revisionID, url.PathEscape(fileID))
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// CherryPickRevision cherry picks a revision to a destination branch.
// The commit message and destination branch must be provided in the request body inside a CherryPickInput entity.
//
// As response a ChangeInfo entity is returned that describes the resulting cherry picked change.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#cherry-pick
func (s *ChangesService) CherryPickRevision(changeID, revisionID string, input *CherryPickInput) (*ChangeInfo, *Response, error) {
u := fmt.Sprintf("changes/%s/revisions/%s/cherrypick", changeID, revisionID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new(ChangeInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
/*
TODO: Missing Revision Endpoints
Rebase Revision
Submit Revision
DownloadContent (https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-safe-content)
*/

529
vendor/github.com/andygrunwald/go-gerrit/config.go generated vendored Normal file
View File

@ -0,0 +1,529 @@
package gerrit
import (
"fmt"
)
// ConfigService contains Config related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html
type ConfigService struct {
client *Client
}
// TopMenuItemInfo entity contains information about a menu item in a top menu entry.
type TopMenuItemInfo struct {
URL string `json:"url"`
Name string `json:"name"`
Target string `json:"target"`
ID string `json:"id,omitempty"`
}
// AuthInfo entity contains information about the authentication configuration of the Gerrit server.
type AuthInfo struct {
Type string `json:"type"`
UseContributorAgreements bool `json:"use_contributor_agreements,omitempty"`
EditableAccountFields []string `json:"editable_account_fields"`
LoginURL string `json:"login_url,omitempty"`
LoginText string `json:"login_text,omitempty"`
SwitchAccountURL string `json:"switch_account_url,omitempty"`
RegisterURL string `json:"register_url,omitempty"`
RegisterText string `json:"register_text,omitempty"`
EditFullNameURL string `json:"edit_full_name_url,omitempty"`
HTTPPasswordURL string `json:"http_password_url,omitempty"`
IsGitBasicAuth bool `json:"is_git_basic_auth,omitempty"`
}
// CacheInfo entity contains information about a cache.
type CacheInfo struct {
Name string `json:"name,omitempty"`
Type string `json:"type"`
Entries EntriesInfo `json:"entries"`
AverageGet string `json:"average_get,omitempty"`
HitRatio HitRatioInfo `json:"hit_ratio"`
}
// CacheOperationInput entity contains information about an operation that should be executed on caches.
type CacheOperationInput struct {
Operation string `json:"operation"`
Caches []string `json:"caches,omitempty"`
}
// ConfigCapabilityInfo entity contains information about a capability.type
type ConfigCapabilityInfo struct {
ID string `json:"id"`
Name string `json:"name"`
}
// HitRatioInfo entity contains information about the hit ratio of a cache.
type HitRatioInfo struct {
Mem int `json:"mem"`
Disk int `json:"disk,omitempty"`
}
// EntriesInfo entity contains information about the entries in a cache.
type EntriesInfo struct {
Mem int `json:"mem,omitempty"`
Disk int `json:"disk,omitempty"`
Space string `json:"space,omitempty"`
}
// UserConfigInfo entity contains information about Gerrit configuration from the user section.
type UserConfigInfo struct {
AnonymousCowardName string `json:"anonymous_coward_name"`
}
// TopMenuEntryInfo entity contains information about a top menu entry.
type TopMenuEntryInfo struct {
Name string `json:"name"`
Items []TopMenuItemInfo `json:"items"`
}
// ThreadSummaryInfo entity contains information about the current threads.
type ThreadSummaryInfo struct {
CPUs int `json:"cpus"`
Threads int `json:"threads"`
Counts map[string]map[string]int `json:"counts"`
}
// TaskSummaryInfo entity contains information about the current tasks.
type TaskSummaryInfo struct {
Total int `json:"total,omitempty"`
Running int `json:"running,omitempty"`
Ready int `json:"ready,omitempty"`
Sleeping int `json:"sleeping,omitempty"`
}
// TaskInfo entity contains information about a task in a background work queue.
type TaskInfo struct {
ID string `json:"id"`
State string `json:"state"`
StartTime string `json:"start_time"`
Delay int `json:"delay"`
Command string `json:"command"`
RemoteName string `json:"remote_name,omitempty"`
Project string `json:"project,omitempty"`
}
// SummaryInfo entity contains information about the current state of the server.
type SummaryInfo struct {
TaskSummary TaskSummaryInfo `json:"task_summary"`
MemSummary MemSummaryInfo `json:"mem_summary"`
ThreadSummary ThemeInfo `json:"thread_summary"`
JVMSummary JvmSummaryInfo `json:"jvm_summary,omitempty"`
}
// SuggestInfo entity contains information about Gerrit configuration from the suggest section.
type SuggestInfo struct {
From int `json:"from"`
}
// SSHdInfo entity contains information about Gerrit configuration from the sshd section.
type SSHdInfo struct{}
// ServerInfo entity contains information about the configuration of the Gerrit server.
type ServerInfo struct {
Auth AuthInfo `json:"auth"`
Change ChangeConfigInfo `json:"change"`
Download DownloadInfo `json:"download"`
Gerrit Info `json:"gerrit"`
Gitweb map[string]string `json:"gitweb,omitempty"`
Plugin PluginConfigInfo `json:"plugin"`
Receive ReceiveInfo `json:"receive,omitempty"`
SSHd SSHdInfo `json:"sshd,omitempty"`
Suggest SuggestInfo `json:"suggest"`
URLAliases map[string]string `json:"url_aliases,omitempty"`
User UserConfigInfo `json:"user"`
}
// ReceiveInfo entity contains information about the configuration of git-receive-pack behavior on the server.
type ReceiveInfo struct {
EnableSignedPush bool `json:"enableSignedPush,omitempty"`
}
// PluginConfigInfo entity contains information about Gerrit extensions by plugins.
type PluginConfigInfo struct {
// HasAvatars reports whether an avatar provider is registered.
HasAvatars bool `json:"has_avatars,omitempty"`
}
// MemSummaryInfo entity contains information about the current memory usage.
type MemSummaryInfo struct {
Total string `json:"total"`
Used string `json:"used"`
Free string `json:"free"`
Buffers string `json:"buffers"`
Max string `json:"max"`
OpenFiles int `json:"open_files,omitempty"`
}
// JvmSummaryInfo entity contains information about the JVM.
type JvmSummaryInfo struct {
VMVendor string `json:"vm_vendor"`
VMName string `json:"vm_name"`
VMVersion string `json:"vm_version"`
OSName string `json:"os_name"`
OSVersion string `json:"os_version"`
OSArch string `json:"os_arch"`
User string `json:"user"`
Host string `json:"host,omitempty"`
CurrentWorkingDirectory string `json:"current_working_directory"`
Site string `json:"site"`
}
// Info entity contains information about Gerrit configuration from the gerrit section.
type Info struct {
AllProjectsName string `json:"all_projects_name"`
AllUsersName string `json:"all_users_name"`
DocURL string `json:"doc_url,omitempty"`
ReportBugURL string `json:"report_bug_url,omitempty"`
ReportBugText string `json:"report_bug_text,omitempty"`
}
// GitwebInfo entity contains information about the gitweb configuration.
type GitwebInfo struct {
URL string `json:"url"`
Type GitwebTypeInfo `json:"type"`
}
// GitwebTypeInfo entity contains information about the gitweb configuration.
type GitwebTypeInfo struct {
Name string `json:"name"`
Revision string `json:"revision,omitempty"`
Project string `json:"project,omitempty"`
Branch string `json:"branch,omitempty"`
RootTree string `json:"root_tree,omitempty"`
File string `json:"file,omitempty"`
FileHistory string `json:"file_history,omitempty"`
PathSeparator string `json:"path_separator"`
LinkDrafts bool `json:"link_drafts,omitempty"`
URLEncode bool `json:"url_encode,omitempty"`
}
// EmailConfirmationInput entity contains information for confirming an email address.
type EmailConfirmationInput struct {
Token string `json:"token"`
}
// DownloadSchemeInfo entity contains information about a supported download scheme and its commands.
type DownloadSchemeInfo struct {
URL string `json:"url"`
IsAuthRequired bool `json:"is_auth_required,omitempty"`
IsAuthSupported bool `json:"is_auth_supported,omitempty"`
Commands map[string]string `json:"commands"`
CloneCommands map[string]string `json:"clone_commands"`
}
// DownloadInfo entity contains information about supported download options.
type DownloadInfo struct {
Schemes map[string]DownloadSchemeInfo `json:"schemes"`
Archives []string `json:"archives"`
}
// ChangeConfigInfo entity contains information about Gerrit configuration from the change section.
type ChangeConfigInfo struct {
AllowDrafts bool `json:"allow_drafts,omitempty"`
LargeChange int `json:"large_change"`
ReplyLabel string `json:"reply_label"`
ReplyTooltip string `json:"reply_tooltip"`
UpdateDelay int `json:"update_delay"`
SubmitWholeTopic bool `json:"submit_whole_topic"`
}
// ListCachesOptions specifies the different output formats.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-caches
type ListCachesOptions struct {
// Format specifies the different output formats.
Format string `url:"format,omitempty"`
}
// SummaryOptions specifies the different options for the GetSummary call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-summary
type SummaryOptions struct {
// JVM includes a JVM summary.
JVM bool `url:"jvm,omitempty"`
// GC requests a Java garbage collection before computing the information about the Java memory heap.
GC bool `url:"gc,omitempty"`
}
// GetVersion returns the version of the Gerrit server.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-version
func (s *ConfigService) GetVersion() (string, *Response, error) {
u := "config/server/version"
return getStringResponseWithoutOptions(s.client, u)
}
// GetServerInfo returns the information about the Gerrit server configuration.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-info
func (s *ConfigService) GetServerInfo() (*ServerInfo, *Response, error) {
u := "config/server/info"
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(ServerInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListCaches lists the caches of the server. Caches defined by plugins are included.
// The caller must be a member of a group that is granted one of the following capabilities:
// * View Caches
// * Maintain Server
// * Administrate Server
// The entries in the map are sorted by cache name.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-caches
func (s *ConfigService) ListCaches(opt *ListCachesOptions) (*map[string]CacheInfo, *Response, error) {
u := "config/server/caches/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]CacheInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetCache retrieves information about a cache.
// The caller must be a member of a group that is granted one of the following capabilities:
// * View Caches
// * Maintain Server
// * Administrate Server
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-cache
func (s *ConfigService) GetCache(cacheName string) (*CacheInfo, *Response, error) {
u := fmt.Sprintf("config/server/caches/%s", cacheName)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(CacheInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetSummary retrieves a summary of the current server state.
// The caller must be a member of a group that is granted the Administrate Server capability.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-summary
func (s *ConfigService) GetSummary(opt *SummaryOptions) (*SummaryInfo, *Response, error) {
u := "config/server/summary"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(SummaryInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListCapabilities lists the capabilities that are available in the system.
// There are two kinds of capabilities: core and plugin-owned capabilities.
// The entries in the map are sorted by capability ID.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-capabilities
func (s *ConfigService) ListCapabilities() (*map[string]ConfigCapabilityInfo, *Response, error) {
u := "config/server/capabilities"
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]ConfigCapabilityInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ListTasks lists the tasks from the background work queues that the Gerrit daemon is currently performing, or will perform in the near future.
// Gerrit contains an internal scheduler, similar to cron, that it uses to queue and dispatch both short and long term tasks.
// Tasks that are completed or canceled exit the queue very quickly once they enter this state, but it can be possible to observe tasks in these states.
// End-users may see a task only if they can also see the project the task is associated with.
// Tasks operating on other projects, or that do not have a specific project, are hidden.
//
// The caller must be a member of a group that is granted one of the following capabilities:
// * View Queue
// * Maintain Server
// * Administrate Server
//
// The entries in the list are sorted by task state, remaining delay and command.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-tasks
func (s *ConfigService) ListTasks() (*[]TaskInfo, *Response, error) {
u := "config/server/tasks"
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]TaskInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetTask retrieves a task from the background work queue that the Gerrit daemon is currently performing, or will perform in the near future.
// End-users may see a task only if they can also see the project the task is associated with.
// Tasks operating on other projects, or that do not have a specific project, are hidden.
//
// The caller must be a member of a group that is granted one of the following capabilities:
// * View Queue
// * Maintain Server
// * Administrate Server
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-task
func (s *ConfigService) GetTask(taskID string) (*TaskInfo, *Response, error) {
u := fmt.Sprintf("config/server/tasks/%s", taskID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(TaskInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetTopMenus returns the list of additional top menu entries.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-top-menus
func (s *ConfigService) GetTopMenus() (*[]TopMenuEntryInfo, *Response, error) {
u := "config/server/top-menus"
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]TopMenuEntryInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// ConfirmEmail confirms that the user owns an email address.
// The email token must be provided in the request body inside an EmailConfirmationInput entity.
//
// The response is “204 No Content”.
// If the token is invalid or if its the token of another user the request fails and the response is “422 Unprocessable Entity”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#confirm-email
func (s *ConfigService) ConfirmEmail(input *EmailConfirmationInput) (*Response, error) {
u := "config/server/email.confirm"
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// CacheOperations executes a cache operation that is specified in the request body in a CacheOperationInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#cache-operations
func (s *ConfigService) CacheOperations(input *CacheOperationInput) (*Response, error) {
u := "config/server/caches/"
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// FlushCache flushes a cache.
// The caller must be a member of a group that is granted one of the following capabilities:
//
// * Flush Caches (any cache except "web_sessions")
// * Maintain Server (any cache including "web_sessions")
// * Administrate Server (any cache including "web_sessions")
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#flush-cache
func (s *ConfigService) FlushCache(cacheName string, input *CacheOperationInput) (*Response, error) {
u := fmt.Sprintf("config/server/caches/%s/flush", cacheName)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
// DeleteTask kills a task from the background work queue that the Gerrit daemon is currently performing, or will perform in the near future.
// The caller must be a member of a group that is granted one of the following capabilities:
//
// * Kill Task
// * Maintain Server
// * Administrate Server
//
// End-users may see a task only if they can also see the project the task is associated with.
// Tasks operating on other projects, or that do not have a specific project, are hidden.
// Members of a group granted one of the following capabilities may view all tasks:
//
// * View Queue
// * Maintain Server
// * Administrate Server
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#delete-task
func (s *ConfigService) DeleteTask(taskID string) (*Response, error) {
u := fmt.Sprintf("config/server/tasks/%s", taskID)
return s.client.DeleteRequest(u, nil)
}

68
vendor/github.com/andygrunwald/go-gerrit/doc.go generated vendored Normal file
View File

@ -0,0 +1,68 @@
/*
Package gerrit provides a client for using the Gerrit API.
Construct a new Gerrit client, then use the various services on the client to
access different parts of the Gerrit API. For example:
instance := "https://go-review.googlesource.com/"
client, _ := gerrit.NewClient(instance, nil)
// Get all public projects
projects, _, err := client.Projects.ListProjects(nil)
Set optional parameters for an API method by passing an Options object.
// Get all projects with descriptions
opt := &gerrit.ProjectOptions{
Description: true,
}
projects, _, err := client.Projects.ListProjects(opt)
The services of a client divide the API into logical chunks and correspond to
the structure of the Gerrit API documentation at
https://gerrit-review.googlesource.com/Documentation/rest-api.html#_endpoints.
Authentication
The go-gerrit library supports various methods to support the authentication.
This methods are combined in the AuthenticationService that is available at client.Authentication.
One way is an authentication via HTTP cookie.
Some Gerrit instances hosted like the one hosted googlesource.com (e.g. https://go-review.googlesource.com/,
https://android-review.googlesource.com/ or https://gerrit-review.googlesource.com/) 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 "git-your@email.com=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.
Some other Gerrit instances (like https://review.typo3.org/) 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
Additionally when creating a new client, pass an http.Client that supports further actions for you.
For more information regarding authentication have a look at the Gerrit documentation:
https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication
*/
package gerrit

166
vendor/github.com/andygrunwald/go-gerrit/events.go generated vendored Normal file
View File

@ -0,0 +1,166 @@
package gerrit
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/url"
"time"
)
// PatchSet contains detailed information about a specific patch set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#patchSet
type PatchSet struct {
Number Number `json:"number"`
Revision string `json:"revision"`
Parents []string `json:"parents"`
Ref string `json:"ref"`
Uploader AccountInfo `json:"uploader"`
Author AccountInfo `json:"author"`
CreatedOn int `json:"createdOn"`
IsDraft bool `json:"isDraft"`
Kind string `json:"kind"`
}
// RefUpdate contains data about a reference update.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#refUpdate
type RefUpdate struct {
OldRev string `json:"oldRev"`
NewRev string `json:"newRev"`
RefName string `json:"refName"`
Project string `json:"project"`
}
// EventInfo contains information about an event emitted by Gerrit. This
// structure can be used either when parsing streamed events or when reading
// the output of the events-log plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/cmd-stream-events.html#events
type EventInfo struct {
Type string `json:"type"`
Change ChangeInfo `json:"change,omitempty"`
ChangeKey ChangeInfo `json:"changeKey,omitempty"`
PatchSet PatchSet `json:"patchSet,omitempty"`
EventCreatedOn int `json:"eventCreatedOn,omitempty"`
Reason string `json:"reason,omitempty"`
Abandoner AccountInfo `json:"abandoner,omitempty"`
Restorer AccountInfo `json:"restorer,omitempty"`
Submitter AccountInfo `json:"submitter,omitempty"`
Author AccountInfo `json:"author,omitempty"`
Uploader AccountInfo `json:"uploader,omitempty"`
Approvals []AccountInfo `json:"approvals,omitempty"`
Comment string `json:"comment,omitempty"`
Editor AccountInfo `json:"editor,omitempty"`
Added []string `json:"added,omitempty"`
Removed []string `json:"removed,omitempty"`
Hashtags []string `json:"hashtags,omitempty"`
RefUpdate RefUpdate `json:"refUpdate,omitempty"`
Project ProjectInfo `json:"project,omitempty"`
Reviewer AccountInfo `json:"reviewer,omitempty"`
OldTopic string `json:"oldTopic,omitempty"`
Changer AccountInfo `json:"changer,omitempty"`
}
// EventsLogService contains functions for querying the API provided
// by the optional events-log plugin.
type EventsLogService struct {
client *Client
}
// EventsLogOptions contains options for querying events from the events-logs
// plugin.
type EventsLogOptions struct {
From time.Time
To time.Time
// IgnoreUnmarshalErrors will cause GetEvents to ignore any errors
// that come up when calling json.Unmarshal. This can be useful in
// cases where the events-log plugin was not kept up to date with
// the Gerrit version for some reason. In these cases the events-log
// plugin will return data structs that don't match the EventInfo
// struct which in turn causes issues for json.Unmarshal.
IgnoreUnmarshalErrors bool
}
// getURL returns the url that should be used in the request. This will vary
// depending on the options provided to GetEvents.
func (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) {
parsed, err := url.Parse("/plugins/events-log/events/")
if err != nil {
return "", err
}
query := parsed.Query()
if !options.From.IsZero() {
query.Set("t1", options.From.Format("2006-01-02 15:04:05"))
}
if !options.To.IsZero() {
query.Set("t2", options.To.Format("2006-01-02 15:04:05"))
}
encoded := query.Encode()
if len(encoded) > 0 {
parsed.RawQuery = encoded
}
return parsed.String(), nil
}
// GetEvents returns a list of events for the given input options. Use of this
// function requires an authenticated user and for the events-log plugin to be
// installed. This function returns the unmarshalled EventInfo structs, response,
// failed lines and errors. Marshaling errors will cause this function to return
// before processing is complete unless you set EventsLogOptions.IgnoreUnmarshalErrors
// to true. This can be useful in cases where the events-log plugin got out of sync
// with the Gerrit version which in turn produced events which can't be transformed
// unmarshalled into EventInfo.
//
// Gerrit API docs: https://<yourserver>/plugins/events-log/Documentation/rest-api-events.html
func (events *EventsLogService) GetEvents(options *EventsLogOptions) ([]EventInfo, *Response, [][]byte, error) {
info := []EventInfo{}
failures := [][]byte{}
requestURL, err := events.getURL(options)
if err != nil {
return info, nil, failures, err
}
request, err := events.client.NewRequest("GET", requestURL, nil)
if err != nil {
return info, nil, failures, err
}
// Perform the request but do not pass in a structure to unpack
// the response into. The format of the response is one EventInfo
// object per line so we need to manually handle the response here.
response, err := events.client.Do(request, nil)
if err != nil {
return info, response, failures, err
}
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close() // nolint: errcheck
if err != nil {
return info, response, failures, err
}
for _, line := range bytes.Split(body, []byte("\n")) {
if len(line) > 0 {
event := EventInfo{}
if err := json.Unmarshal(line, &event); err != nil { // nolint: vetshadow
failures = append(failures, line)
if !options.IgnoreUnmarshalErrors {
return info, response, failures, err
}
continue
}
info = append(info, event)
}
}
return info, response, failures, err
}

564
vendor/github.com/andygrunwald/go-gerrit/gerrit.go generated vendored Normal file
View File

@ -0,0 +1,564 @@
package gerrit
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"regexp"
"strings"
"github.com/google/go-querystring/query"
)
// TODO Try to reduce the code duplications of a std API req
// Maybe with http://play.golang.org/p/j-667shCCB
// and https://groups.google.com/forum/#!topic/golang-nuts/D-gIr24k5uY
// A Client manages communication with the Gerrit API.
type Client struct {
// client is the HTTP client used to communicate with the API.
client *http.Client
// baseURL is the base URL of the Gerrit instance for API requests.
// It must have a trailing slash.
baseURL *url.URL
// Gerrit service for authentication.
Authentication *AuthenticationService
// Services used for talking to different parts of the standard Gerrit API.
Access *AccessService
Accounts *AccountsService
Changes *ChangesService
Config *ConfigService
Groups *GroupsService
Plugins *PluginsService
Projects *ProjectsService
// Additional services used for talking to non-standard Gerrit APIs.
EventsLog *EventsLogService
}
// Response is a Gerrit API response.
// This wraps the standard http.Response returned from Gerrit.
type Response struct {
*http.Response
}
var (
// ErrNoInstanceGiven is returned by NewClient in the event the
// gerritURL argument was blank.
ErrNoInstanceGiven = errors.New("no Gerrit instance given")
// ErrUserProvidedWithoutPassword is returned by NewClient
// if a user name is provided without a password.
ErrUserProvidedWithoutPassword = errors.New("a username was provided without a password")
// 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.
ErrAuthenticationFailed = errors.New("failed to authenticate using the provided credentials")
// ReParseURL is used to parse the url provided to NewClient(). This
// regular expression contains five groups which capture the scheme,
// username, password, hostname and port. If we parse the url with this
// regular expression
ReParseURL = regexp.MustCompile(`^(http|https)://(.+):(.+)@(.+):(\d+)(.*)$`)
)
// NewClient returns a new Gerrit API client. gerritURL specifies the
// HTTP endpoint of the Gerrit instance. For example, "http://localhost:8080/".
// If gerritURL does not have a trailing slash, one is added automatically.
// If a nil httpClient is provided, http.DefaultClient will be used.
//
// The url may contain credentials, http://admin:secret@localhost:8081/ for
// example. These credentials may either be a user name and password or
// name and value as in the case of cookie based authentication. If the url contains
// credentials then this function will attempt to validate the credentials before
// returning the client. ErrAuthenticationFailed will be returned if the credentials
// cannot be validated. The process of validating the credentials is relatively simple and
// only requires that the provided user have permission to GET /a/accounts/self.
func NewClient(gerritURL string, httpClient *http.Client) (*Client, error) {
if httpClient == nil {
httpClient = http.DefaultClient
}
endpoint := gerritURL
if endpoint == "" {
return nil, ErrNoInstanceGiven
}
hasAuth := false
username := ""
password := ""
// Depending on the contents of the username and password the default
// url.Parse may not work. The below is an example URL that
// would end up being parsed incorrectly with url.Parse:
// http://admin:ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg@localhost:38607
// So instead of depending on url.Parse we'll try using a regular expression
// first to match a specific pattern. If that ends up working we modify
// the incoming endpoint to remove the username and password so the rest
// of this function will run as expected.
submatches := ReParseURL.FindAllStringSubmatch(endpoint, -1)
if len(submatches) > 0 && len(submatches[0]) > 5 {
submatch := submatches[0]
username = submatch[2]
password = submatch[3]
endpoint = fmt.Sprintf(
"%s://%s:%s%s", submatch[1], submatch[4], submatch[5], submatch[6])
hasAuth = true
}
baseURL, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
if !strings.HasSuffix(baseURL.Path, "/") {
baseURL.Path += "/"
}
// Note, if we retrieved the URL and password using the regular
// expression above then the below code will do nothing.
if baseURL.User != nil {
username = baseURL.User.Username()
parsedPassword, haspassword := baseURL.User.Password()
// Catches cases like http://user@localhost:8081/ where no password
// was at all. If a blank password is required
if !haspassword {
return nil, ErrUserProvidedWithoutPassword
}
password = parsedPassword
// Reconstruct the url but without the username and password.
baseURL, err = url.Parse(
fmt.Sprintf("%s://%s%s", baseURL.Scheme, baseURL.Host, baseURL.RequestURI()))
if err != nil {
return nil, err
}
hasAuth = true
}
c := &Client{
client: httpClient,
baseURL: baseURL,
}
c.Authentication = &AuthenticationService{client: c}
c.Access = &AccessService{client: c}
c.Accounts = &AccountsService{client: c}
c.Changes = &ChangesService{client: c}
c.Config = &ConfigService{client: c}
c.Groups = &GroupsService{client: c}
c.Plugins = &PluginsService{client: c}
c.Projects = &ProjectsService{client: c}
c.EventsLog = &EventsLogService{client: c}
if hasAuth {
// Digest auth (first since that's the default auth type)
c.Authentication.SetDigestAuth(username, password)
if success, err := checkAuth(c); success || err != nil {
return c, err
}
// Basic auth
c.Authentication.SetBasicAuth(username, password)
if success, err := checkAuth(c); success || err != nil {
return c, err
}
// Cookie auth
c.Authentication.SetCookieAuth(username, password)
if success, err := checkAuth(c); success || err != nil {
return c, err
}
// Reset auth in case the consumer needs to do something special.
c.Authentication.ResetAuth()
return c, ErrAuthenticationFailed
}
return c, nil
}
// checkAuth is used by NewClient to check if the current credentials are
// valid. If the response is 401 Unauthorized then the error will be discarded.
func checkAuth(client *Client) (bool, error) {
_, response, err := client.Accounts.GetAccount("self")
switch err {
case ErrWWWAuthenticateHeaderMissing:
return false, nil
case ErrWWWAuthenticateHeaderNotDigest:
return false, nil
default:
// Response could be nil if the connection outright failed
// or some other error occurred before we got a response.
if response == nil && err != nil {
return false, err
}
if err != nil && response.StatusCode == http.StatusUnauthorized {
err = nil
}
return response.StatusCode == http.StatusOK, err
}
}
// NewRequest creates an API request.
// A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client.
// Relative URLs should always be specified without a preceding slash.
// If specified, the value pointed to by body is JSON encoded and included as the request body.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
// Build URL for request
u, err := c.buildURLForRequest(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u, buf)
if err != nil {
return nil, err
}
// Apply Authentication
if err := c.addAuthentication(req); err != nil {
return nil, err
}
// Request compact JSON
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
// TODO: Add gzip encoding
// Accept-Encoding request header is set to gzip
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
return req, nil
}
// NewRawPutRequest creates a raw PUT request and makes no attempt to encode
// or marshal the body. Just passes it straight through.
func (c *Client) NewRawPutRequest(urlStr string, body string) (*http.Request, error) {
// Build URL for request
u, err := c.buildURLForRequest(urlStr)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer([]byte(body))
req, err := http.NewRequest("PUT", u, buf)
if err != nil {
return nil, err
}
// Apply Authentication
if err := c.addAuthentication(req); err != nil {
return nil, err
}
// Request compact JSON
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// TODO: Add gzip encoding
// Accept-Encoding request header is set to gzip
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
return req, nil
}
// Call is a combine function for Client.NewRequest and Client.Do.
//
// Most API methods are quite the same.
// Get the URL, apply options, make a request, and get the response.
// Without adding special headers or something.
// To avoid a big amount of code duplication you can Client.Call.
//
// method is the HTTP method you want to call.
// u is the URL you want to call.
// body is the HTTP body.
// v is the HTTP response.
//
// For more information read https://github.com/google/go-github/issues/234
func (c *Client) Call(method, u string, body interface{}, v interface{}) (*Response, error) {
req, err := c.NewRequest(method, u, body)
if err != nil {
return nil, err
}
resp, err := c.Do(req, v)
if err != nil {
return resp, err
}
return resp, err
}
// buildURLForRequest will build the URL (as string) that will be called.
// We need such a utility method, because the URL.Path needs to be escaped (partly).
//
// E.g. if a project is called via "projects/%s" and the project is named "plugin/delete-project"
// there has to be "projects/plugin%25Fdelete-project" instead of "projects/plugin/delete-project".
// The second url will return nothing.
func (c *Client) buildURLForRequest(urlStr string) (string, error) {
// If there is a "/" at the start, remove it.
// TODO: It can be arranged for all callers of buildURLForRequest to never have a "/" prefix,
// which can be ensured via tests. This is how it's done in go-github.
// Then, this run-time check becomes unnecessary and can be removed.
urlStr = strings.TrimPrefix(urlStr, "/")
// If we are authenticated, let's apply the "a/" prefix,
// but only if it has not already been applied.
if c.Authentication.HasAuth() && !strings.HasPrefix(urlStr, "a/") {
urlStr = "a/" + urlStr
}
rel, err := url.Parse(urlStr)
if err != nil {
return "", err
}
return c.baseURL.String() + rel.String(), nil
}
// Do sends an API request and returns the API response.
// The API response is JSON decoded and stored in the value pointed to by v,
// or returned as an error if an API error has occurred.
// If v implements the io.Writer interface, the raw response body will be written to v,
// without attempting to first decode it.
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
// Wrap response
response := &Response{Response: resp}
err = CheckResponse(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return response, err
}
if v != nil {
defer resp.Body.Close() // nolint: errcheck
if w, ok := v.(io.Writer); ok {
if _, err := io.Copy(w, resp.Body); err != nil { // nolint: vetshadow
return nil, err
}
} else {
var body []byte
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return response, err
}
body = RemoveMagicPrefixLine(body)
err = json.Unmarshal(body, v)
}
}
return response, err
}
func (c *Client) addAuthentication(req *http.Request) error {
// Apply HTTP Basic Authentication
if c.Authentication.HasBasicAuth() {
req.SetBasicAuth(c.Authentication.name, c.Authentication.secret)
return nil
}
// Apply HTTP Cookie
if c.Authentication.HasCookieAuth() {
req.AddCookie(&http.Cookie{
Name: c.Authentication.name,
Value: c.Authentication.secret,
})
return nil
}
// Apply Digest Authentication. If we're using digest based
// authentication we need to make a request, process the
// WWW-Authenticate header, then set the Authorization header on the
// incoming request. We do not need to send a body along because
// the request itself should fail first.
if c.Authentication.HasDigestAuth() {
uri, err := c.buildURLForRequest(req.URL.RequestURI())
if err != nil {
return err
}
// WARNING: Don't use c.NewRequest here unless you like
// infinite recursion.
digestRequest, err := http.NewRequest(req.Method, uri, nil)
digestRequest.Header.Set("Accept", "*/*")
digestRequest.Header.Set("Content-Type", "application/json")
if err != nil {
return err
}
response, err := c.client.Do(digestRequest)
if err != nil {
return err
}
// When the function exits discard the rest of the
// body and close it. This should cause go to
// reuse the connection.
defer io.Copy(ioutil.Discard, response.Body) // nolint: errcheck
defer response.Body.Close() // nolint: errcheck
if response.StatusCode == http.StatusUnauthorized {
authorization, err := c.Authentication.digestAuthHeader(response)
if err != nil {
return err
}
req.Header.Set("Authorization", authorization)
}
}
return nil
}
// DeleteRequest sends an DELETE API Request to urlStr with optional body.
// It is a shorthand combination for Client.NewRequest with Client.Do.
//
// Relative URLs should always be specified without a preceding slash.
// If specified, the value pointed to by body is JSON encoded and included as the request body.
func (c *Client) DeleteRequest(urlStr string, body interface{}) (*Response, error) {
req, err := c.NewRequest("DELETE", urlStr, body)
if err != nil {
return nil, err
}
return c.Do(req, nil)
}
// BaseURL returns the client's Gerrit instance HTTP endpoint.
func (c *Client) BaseURL() url.URL {
return *c.baseURL
}
// RemoveMagicPrefixLine removes the "magic prefix line" of Gerris JSON
// response if present. The JSON response body starts with a magic prefix line
// that must be stripped before feeding the rest of the response body to a JSON
// parser. The reason for this is to prevent against Cross Site Script
// Inclusion (XSSI) attacks. By default all standard Gerrit APIs include this
// prefix line though some plugins may not.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api.html#output
func RemoveMagicPrefixLine(body []byte) []byte {
if bytes.HasPrefix(body, magicPrefix) {
return body[5:]
}
return body
}
var magicPrefix = []byte(")]}'\n")
// CheckResponse checks the API response for errors, and returns them if present.
// A response is considered an error if it has a status code outside the 200 range.
// API error responses are expected to have no response body.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api.html#response-codes
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
// Some calls require an authentification
// In such cases errors like:
// API call to https://review.typo3.org/accounts/self failed: 403 Forbidden
// will be thrown.
err := fmt.Errorf("API call to %s failed: %s", r.Request.URL.String(), r.Status)
return err
}
// queryParameterReplacements are values in a url, specifically the query
// portion of the url, which should not be escaped before being sent to
// Gerrit. Note, Gerrit itself does not escape these values when using the
// search box so we shouldn't escape them either.
var queryParameterReplacements = map[string]string{
"+": "GOGERRIT_URL_PLACEHOLDER_PLUS",
":": "GOGERRIT_URL_PLACEHOLDER_COLON"}
// addOptions adds the parameters in opt as URL query parameters to s.
// opt must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
// If the url contained one or more query parameters (q) then we need
// to do some escaping on these values before Encode() is called. By
// doing so we're ensuring that : and + don't get encoded which means
// they'll be passed along to Gerrit as raw ascii. Without this Gerrit
// could return 400 Bad Request depending on the query parameters. For
// more complete information see this issue on GitHub:
// https://github.com/andygrunwald/go-gerrit/issues/18
_, hasQuery := qs["q"]
if hasQuery {
values := []string{}
for _, value := range qs["q"] {
for key, replacement := range queryParameterReplacements {
value = strings.Replace(value, key, replacement, -1)
}
values = append(values, value)
}
qs.Del("q")
for _, value := range values {
qs.Add("q", value)
}
}
encoded := qs.Encode()
if hasQuery {
for key, replacement := range queryParameterReplacements {
encoded = strings.Replace(encoded, replacement, key, -1)
}
}
u.RawQuery = encoded
return u.String(), nil
}
// getStringResponseWithoutOptions retrieved a single string Response for a GET request
func getStringResponseWithoutOptions(client *Client, u string) (string, *Response, error) {
v := new(string)
resp, err := client.Call("GET", u, nil, v)
return *v, resp, err
}

View File

@ -0,0 +1,24 @@
{
"DisableAll": true,
"Enable": [
"deadcode",
"unconvert",
"golint",
"vetshadow",
"vet",
"unused",
"gofmt",
"goimports",
"goconst",
"errcheck",
"interfacer",
"gas",
"unconvert",
"testify",
"unparam",
"varcheck",
"gotype",
"ineffassign",
"staticcheck"
]
}

360
vendor/github.com/andygrunwald/go-gerrit/groups.go generated vendored Normal file
View File

@ -0,0 +1,360 @@
package gerrit
import (
"fmt"
)
// GroupsService contains Group related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html
type GroupsService struct {
client *Client
}
// GroupAuditEventInfo entity contains information about an audit event of a group.
type GroupAuditEventInfo struct {
// TODO Member AccountInfo OR GroupInfo `json:"member"`
Type string `json:"type"`
User AccountInfo `json:"user"`
Date Timestamp `json:"date"`
}
// GroupInfo entity contains information about a group.
// This can be a Gerrit internal group, or an external group that is known to Gerrit.
type GroupInfo struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Options GroupOptionsInfo `json:"options"`
Description string `json:"description,omitempty"`
GroupID int `json:"group_id,omitempty"`
Owner string `json:"owner,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
CreatedOn *Timestamp `json:"created_on,omitempty"`
Members []AccountInfo `json:"members,omitempty"`
Includes []GroupInfo `json:"includes,omitempty"`
}
// GroupInput entity contains information for the creation of a new internal group.
type GroupInput struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
VisibleToAll bool `json:"visible_to_all,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
}
// GroupOptionsInfo entity contains options of the group.
type GroupOptionsInfo struct {
VisibleToAll bool `json:"visible_to_all,omitempty"`
}
// GroupOptionsInput entity contains new options for a group.
type GroupOptionsInput struct {
VisibleToAll bool `json:"visible_to_all,omitempty"`
}
// GroupsInput entity contains information about groups that should be included into a group or that should be deleted from a group.
type GroupsInput struct {
OneGroup string `json:"_one_group,omitempty"`
Groups []string `json:"groups,omitempty"`
}
// ListGroupsOptions specifies the different options for the ListGroups call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#list-groups
type ListGroupsOptions struct {
// Group Options
// Options fields can be obtained by adding o parameters, each option requires more lookups and slows down the query response time to the client so they are generally disabled by default.
// Optional fields are:
// INCLUDES: include list of directly included groups.
// MEMBERS: include list of direct group members.
Options []string `url:"o,omitempty"`
// Check if a group is owned by the calling user
// By setting the option owned and specifying a group to inspect with the option q, it is possible to find out, if this group is owned by the calling user.
// If the group is owned by the calling user, the returned map contains this group. If the calling user doesnt own this group an empty map is returned.
Owned string `url:"owned,omitempty"`
Group string `url:"q,omitempty"`
// Group Limit
// The /groups/ URL also accepts a limit integer in the n parameter. This limits the results to show n groups.
Limit int `url:"n,omitempty"`
// The /groups/ URL also accepts a start integer in the S parameter. The results will skip S groups from group list.
Skip int `url:"S,omitempty"`
}
// ListGroups lists the groups accessible by the caller.
// This is the same as using the ls-groups command over SSH, and accepts the same options as query parameters.
// The entries in the map are sorted by group name.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#list-groups
func (s *GroupsService) ListGroups(opt *ListGroupsOptions) (*map[string]GroupInfo, *Response, error) {
u := "groups/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetGroup retrieves a group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group
func (s *GroupsService) GetGroup(groupID string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s", groupID)
return s.getGroupInfoResponse(u)
}
// GetGroupDetail retrieves a group with the direct members and the directly included groups.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-detail
func (s *GroupsService) GetGroupDetail(groupID string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/detail", groupID)
return s.getGroupInfoResponse(u)
}
// getGroupInfoResponse retrieved a single GroupInfo Response for a GET request
func (s *GroupsService) getGroupInfoResponse(u string) (*GroupInfo, *Response, error) {
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetGroupName retrieves the name of a group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-name
func (s *GroupsService) GetGroupName(groupID string) (string, *Response, error) {
u := fmt.Sprintf("groups/%s/name", groupID)
return getStringResponseWithoutOptions(s.client, u)
}
// GetGroupDescription retrieves the description of a group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-description
func (s *GroupsService) GetGroupDescription(groupID string) (string, *Response, error) {
u := fmt.Sprintf("groups/%s/description", groupID)
return getStringResponseWithoutOptions(s.client, u)
}
// GetGroupOptions retrieves the options of a group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-options
func (s *GroupsService) GetGroupOptions(groupID string) (*GroupOptionsInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/options", groupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GroupOptionsInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetGroupOwner retrieves the owner group of a Gerrit internal group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-owner
func (s *GroupsService) GetGroupOwner(groupID string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/owner", groupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetAuditLog gets the audit log of a Gerrit internal group.
// The returned audit events are sorted by date in reverse order so that the newest audit event comes first.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-audit-log
func (s *GroupsService) GetAuditLog(groupID string) (*[]GroupAuditEventInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/log.audit", groupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]GroupAuditEventInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateGroup creates a new Gerrit internal group.
// In the request body additional data for the group can be provided as GroupInput.
//
// As response the GroupInfo entity is returned that describes the created group.
// If the group creation fails because the name is already in use the response is “409 Conflict”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#create-group
func (s *GroupsService) CreateGroup(groupID string, input *GroupInput) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s", groupID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// RenameGroup renames a Gerrit internal group.
// The new group name must be provided in the request body.
//
// As response the new group name is returned.
// If renaming the group fails because the new name is already in use the response is “409 Conflict”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#rename-group
func (s *GroupsService) RenameGroup(groupID, name string) (*string, *Response, error) {
u := fmt.Sprintf("groups/%s/name", groupID)
input := struct {
Name string `json:"name"`
}{
Name: name,
}
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetGroupDescription sets the description of a Gerrit internal group.
// The new group description must be provided in the request body.
//
// As response the new group description is returned.
// If the description was deleted the response is “204 No Content”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-description
func (s *GroupsService) SetGroupDescription(groupID, description string) (*string, *Response, error) {
u := fmt.Sprintf("groups/%s/description", groupID)
input := struct {
Description string `json:"description"`
}{
Description: description,
}
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteGroupDescription deletes the description of a Gerrit internal group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#delete-group-description
func (s *GroupsService) DeleteGroupDescription(groupID string) (*Response, error) {
u := fmt.Sprintf("groups/%s/description'", groupID)
return s.client.DeleteRequest(u, nil)
}
// SetGroupOptions sets the options of a Gerrit internal group.
// The new group options must be provided in the request body as a GroupOptionsInput entity.
//
// As response the new group options are returned as a GroupOptionsInfo entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-options
func (s *GroupsService) SetGroupOptions(groupID string, input *GroupOptionsInput) (*GroupOptionsInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/options", groupID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(GroupOptionsInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetGroupOwner sets the owner group of a Gerrit internal group.
// The new owner group must be provided in the request body.
// The new owner can be specified by name, by group UUID or by the legacy numeric group ID.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-owner
func (s *GroupsService) SetGroupOwner(groupID, owner string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/owner", groupID)
input := struct {
Owner string `json:"owner"`
}{
Owner: owner,
}
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}

View File

@ -0,0 +1,117 @@
package gerrit
import (
"fmt"
)
// ListIncludedGroups lists the directly included groups of a group.
// The entries in the list are sorted by group name and UUID.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#included-groups
func (s *GroupsService) ListIncludedGroups(groupID string) (*[]GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/groups/", groupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetIncludedGroup retrieves an included group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-included-group
func (s *GroupsService) GetIncludedGroup(groupID, includeGroupID string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/groups/%s", groupID, includeGroupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// IncludeGroup includes an internal or external group into a Gerrit internal group.
// External groups must be specified using the UUID.
//
// As response a GroupInfo entity is returned that describes the included group.
// The request also succeeds if the group is already included in this group, but then the HTTP response code is 200 OK.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#include-group
func (s *GroupsService) IncludeGroup(groupID, includeGroupID string) (*GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/groups/%s", groupID, includeGroupID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, nil, err
}
v := new(GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// IncludeGroups includes one or several groups into a Gerrit internal group.
// The groups to be included into the group must be provided in the request body as a GroupsInput entity.
//
// As response a list of GroupInfo entities is returned that describes the groups that were specified in the GroupsInput.
// A GroupInfo entity is returned for each group specified in the input, independently of whether the group was newly included into the group or whether the group was already included in the group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#include-groups
func (s *GroupsService) IncludeGroups(groupID string, input *GroupsInput) (*[]GroupInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/groups", groupID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new([]GroupInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteIncludedGroup deletes an included group from a Gerrit internal group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#include-group
func (s *GroupsService) DeleteIncludedGroup(groupID, includeGroupID string) (*Response, error) {
u := fmt.Sprintf("groups/%s/groups/%s", groupID, includeGroupID)
return s.client.DeleteRequest(u, nil)
}
// DeleteIncludedGroups delete one or several included groups from a Gerrit internal group.
// The groups to be deleted from the group must be provided in the request body as a GroupsInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#delete-included-groups
func (s *GroupsService) DeleteIncludedGroups(groupID string, input *GroupsInput) (*Response, error) {
u := fmt.Sprintf("groups/%s/groups.delete", groupID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}

View File

@ -0,0 +1,133 @@
package gerrit
import (
"fmt"
)
// ListGroupMembersOptions specifies the different options for the ListGroupMembers call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-members
type ListGroupMembersOptions struct {
// To resolve the included groups of a group recursively and to list all members the parameter recursive can be set.
// Members from included external groups and from included groups which are not visible to the calling user are ignored.
Recursive bool `url:"recursive,omitempty"`
}
// MembersInput entity contains information about accounts that should be added as members to a group or that should be deleted from the group
type MembersInput struct {
OneMember string `json:"_one_member,omitempty"`
Members []string `json:"members,omitempty"`
}
// ListGroupMembers lists the direct members of a Gerrit internal group.
// The entries in the list are sorted by full name, preferred email and id.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-members
func (s *GroupsService) ListGroupMembers(groupID string, opt *ListGroupMembersOptions) (*[]AccountInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/members/", groupID)
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetGroupMember retrieves a group member.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-member
func (s *GroupsService) GetGroupMember(groupID, accountID string) (*AccountInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/members/%s", groupID, accountID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// AddGroupMember adds a user as member to a Gerrit internal group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#add-group-member
func (s *GroupsService) AddGroupMember(groupID, accountID string) (*AccountInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/members/%s", groupID, accountID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, nil, err
}
v := new(AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// AddGroupMembers adds one or several users to a Gerrit internal group.
// The users to be added to the group must be provided in the request body as a MembersInput entity.
//
// As response a list of detailed AccountInfo entities is returned that describes the group members that were specified in the MembersInput.
// An AccountInfo entity is returned for each user specified in the input, independently of whether the user was newly added to the group or whether the user was already a member of the group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#_add_group_members
func (s *GroupsService) AddGroupMembers(groupID string, input *MembersInput) (*[]AccountInfo, *Response, error) {
u := fmt.Sprintf("groups/%s/members", groupID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, nil, err
}
v := new([]AccountInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteGroupMember deletes a user from a Gerrit internal group.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#delete-group-member
func (s *GroupsService) DeleteGroupMember(groupID, accountID string) (*Response, error) {
u := fmt.Sprintf("groups/%s/members/%s'", groupID, accountID)
return s.client.DeleteRequest(u, nil)
}
// DeleteGroupMembers delete one or several users from a Gerrit internal group.
// The users to be deleted from the group must be provided in the request body as a MembersInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#delete-group-members
func (s *GroupsService) DeleteGroupMembers(groupID string, input *MembersInput) (*Response, error) {
u := fmt.Sprintf("groups/%s/members.delete'", groupID)
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}

131
vendor/github.com/andygrunwald/go-gerrit/plugins.go generated vendored Normal file
View File

@ -0,0 +1,131 @@
package gerrit
import (
"fmt"
)
// PluginsService contains Plugin related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html
type PluginsService struct {
client *Client
}
// PluginInfo entity describes a plugin.
type PluginInfo struct {
ID string `json:"id"`
Version string `json:"version"`
IndexURL string `json:"index_url,omitempty"`
Disabled bool `json:"disabled,omitempty"`
}
// PluginInput entity describes a plugin that should be installed.
type PluginInput struct {
URL string `json:"url"`
}
// PluginOptions specifies the different options for the ListPlugins call.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#list-plugins
type PluginOptions struct {
// All enabled that all plugins are returned (enabled and disabled).
All bool `url:"all,omitempty"`
}
// ListPlugins lists the plugins installed on the Gerrit server.
// Only the enabled plugins are returned unless the all option is specified.
//
// To be allowed to see the installed plugins, a user must be a member of a group that is granted the 'View Plugins' capability or the 'Administrate Server' capability.
// The entries in the map are sorted by plugin ID.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#list-plugins
func (s *PluginsService) ListPlugins(opt *PluginOptions) (*map[string]PluginInfo, *Response, error) {
u := "plugins/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(map[string]PluginInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetPluginStatus retrieves the status of a plugin on the Gerrit server.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#get-plugin-status
func (s *PluginsService) GetPluginStatus(pluginID string) (*PluginInfo, *Response, error) {
u := fmt.Sprintf("plugins/%s/gerrit~status", pluginID)
return s.requestWithPluginInfoResponse("GET", u, nil)
}
// InstallPlugin installs a new plugin on the Gerrit server.
// If a plugin with the specified name already exists it is overwritten.
//
// Note: if the plugin provides its own name in the MANIFEST file, then the plugin name from the MANIFEST file has precedence over the {plugin-id} above.
//
// The plugin jar can either be sent as binary data in the request body or a URL to the plugin jar must be provided in the request body inside a PluginInput entity.
//
// As response a PluginInfo entity is returned that describes the plugin.
// If an existing plugin was overwritten the response is “200 OK”.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-dashboard
func (s *PluginsService) InstallPlugin(pluginID string, input *PluginInput) (*PluginInfo, *Response, error) {
u := fmt.Sprintf("plugins/%s", pluginID)
return s.requestWithPluginInfoResponse("PUT", u, input)
}
// EnablePlugin enables a plugin on the Gerrit server.
//
// As response a PluginInfo entity is returned that describes the plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#enable-plugin
func (s *PluginsService) EnablePlugin(pluginID string) (*PluginInfo, *Response, error) {
u := fmt.Sprintf("plugins/%s/gerrit~enable", pluginID)
return s.requestWithPluginInfoResponse("POST", u, nil)
}
// DisablePlugin disables a plugin on the Gerrit server.
//
// As response a PluginInfo entity is returned that describes the plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#disable-plugin
func (s *PluginsService) DisablePlugin(pluginID string) (*PluginInfo, *Response, error) {
u := fmt.Sprintf("plugins/%s/gerrit~disable", pluginID)
return s.requestWithPluginInfoResponse("POST", u, nil)
}
// ReloadPlugin reloads a plugin on the Gerrit server.
//
// As response a PluginInfo entity is returned that describes the plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#disable-plugin
func (s *PluginsService) ReloadPlugin(pluginID string) (*PluginInfo, *Response, error) {
u := fmt.Sprintf("plugins/%s/gerrit~reload", pluginID)
return s.requestWithPluginInfoResponse("POST", u, nil)
}
func (s *PluginsService) requestWithPluginInfoResponse(method, u string, input interface{}) (*PluginInfo, *Response, error) {
req, err := s.client.NewRequest(method, u, input)
if err != nil {
return nil, nil, err
}
v := new(PluginInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}

465
vendor/github.com/andygrunwald/go-gerrit/projects.go generated vendored Normal file
View File

@ -0,0 +1,465 @@
package gerrit
import (
"fmt"
"net/url"
)
// ProjectsService contains Project related REST endpoints
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html
type ProjectsService struct {
client *Client
}
// ProjectInfo entity contains information about a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#project-info
type ProjectInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Parent string `json:"parent,omitempty"`
Description string `json:"description,omitempty"`
State string `json:"state,omitempty"`
Branches map[string]string `json:"branches,omitempty"`
WebLinks []WebLinkInfo `json:"web_links,omitempty"`
}
// ProjectInput entity contains information for the creation of a new project.
type ProjectInput struct {
Name string `json:"name,omitempty"`
Parent string `json:"parent,omitempty"`
Description string `json:"description,omitempty"`
PermissionsOnly bool `json:"permissions_only"`
CreateEmptyCommit bool `json:"create_empty_commit"`
SubmitType string `json:"submit_type,omitempty"`
Branches []string `json:"branches,omitempty"`
Owners []string `json:"owners,omitempty"`
UseContributorAgreements string `json:"use_contributor_agreements"`
UseSignedOffBy string `json:"use_signed_off_by"`
CreateNewChangeForAllNotInTarget string `json:"create_new_change_for_all_not_in_target"`
UseContentMerge string `json:"use_content_merge"`
RequireChangeID string `json:"require_change_id"`
MaxObjectSizeLimit string `json:"max_object_size_limit,omitempty"`
PluginConfigValues map[string]map[string]string `json:"plugin_config_values,omitempty"`
}
// GCInput entity contains information to run the Git garbage collection.
type GCInput struct {
ShowProgress bool `json:"show_progress"`
Aggressive bool `json:"aggressive"`
}
// HeadInput entity contains information for setting HEAD for a project.
type HeadInput struct {
Ref string `json:"ref"`
}
// BanInput entity contains information for banning commits in a project.
type BanInput struct {
Commits []string `json:"commits"`
Reason string `json:"reason,omitempty"`
}
// BanResultInfo entity describes the result of banning commits.
type BanResultInfo struct {
NewlyBanned []string `json:"newly_banned,omitempty"`
AlreadyBanned []string `json:"already_banned,omitempty"`
Ignored []string `json:"ignored,omitempty"`
}
// ThemeInfo entity describes a theme.
type ThemeInfo struct {
CSS string `type:"css,omitempty"`
Header string `type:"header,omitempty"`
Footer string `type:"footer,omitempty"`
}
// ReflogEntryInfo entity describes an entry in a reflog.
type ReflogEntryInfo struct {
OldID string `json:"old_id"`
NewID string `json:"new_id"`
Who GitPersonInfo `json:"who"`
Comment string `json:"comment"`
}
// ProjectParentInput entity contains information for setting a project parent.
type ProjectParentInput struct {
Parent string `json:"parent"`
CommitMessage string `json:"commit_message,omitempty"`
}
// RepositoryStatisticsInfo entity contains information about statistics of a Git repository.
type RepositoryStatisticsInfo struct {
NumberOfLooseObjects int `json:"number_of_loose_objects"`
NumberOfLooseRefs int `json:"number_of_loose_refs"`
NumberOfPackFiles int `json:"number_of_pack_files"`
NumberOfPackedObjects int `json:"number_of_packed_objects"`
NumberOfPackedRefs int `json:"number_of_packed_refs"`
SizeOfLooseObjects int `json:"size_of_loose_objects"`
SizeOfPackedObjects int `json:"size_of_packed_objects"`
}
// InheritedBooleanInfo entity represents a boolean value that can also be inherited.
type InheritedBooleanInfo struct {
Value bool `json:"value"`
ConfiguredValue string `json:"configured_value"`
InheritedValue bool `json:"inherited_value,omitempty"`
}
// MaxObjectSizeLimitInfo entity contains information about the max object size limit of a project.
type MaxObjectSizeLimitInfo struct {
Value string `json:"value,omitempty"`
ConfiguredValue string `json:"configured_value,omitempty"`
InheritedValue string `json:"inherited_value,omitempty"`
}
// ConfigParameterInfo entity describes a project configuration parameter.
type ConfigParameterInfo struct {
DisplayName string `json:"display_name,omitempty"`
Description string `json:"description,omitempty"`
Warning string `json:"warning,omitempty"`
Type string `json:"type"`
Value string `json:"value,omitempty"`
Values []string `json:"values,omitempty"`
// TODO: 5 fields are missing here, because the documentation seems to be fucked up
// See https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#config-parameter-info
}
// ProjectDescriptionInput entity contains information for setting a project description.
type ProjectDescriptionInput struct {
Description string `json:"description,omitempty"`
CommitMessage string `json:"commit_message,omitempty"`
}
// ConfigInfo entity contains information about the effective project configuration.
type ConfigInfo struct {
Description string `json:"description,omitempty"`
UseContributorAgreements InheritedBooleanInfo `json:"use_contributor_agreements,omitempty"`
UseContentMerge InheritedBooleanInfo `json:"use_content_merge,omitempty"`
UseSignedOffBy InheritedBooleanInfo `json:"use_signed_off_by,omitempty"`
CreateNewChangeForAllNotInTarget InheritedBooleanInfo `json:"create_new_change_for_all_not_in_target,omitempty"`
RequireChangeID InheritedBooleanInfo `json:"require_change_id,omitempty"`
EnableSignedPush InheritedBooleanInfo `json:"enable_signed_push,omitempty"`
MaxObjectSizeLimit MaxObjectSizeLimitInfo `json:"max_object_size_limit"`
SubmitType string `json:"submit_type"`
State string `json:"state,omitempty"`
Commentlinks map[string]string `json:"commentlinks"`
Theme ThemeInfo `json:"theme,omitempty"`
PluginConfig map[string]ConfigParameterInfo `json:"plugin_config,omitempty"`
Actions map[string]ActionInfo `json:"actions,omitempty"`
}
// ConfigInput entity describes a new project configuration.
type ConfigInput struct {
Description string `json:"description,omitempty"`
UseContributorAgreements string `json:"use_contributor_agreements,omitempty"`
UseContentMerge string `json:"use_content_merge,omitempty"`
UseSignedOffBy string `json:"use_signed_off_by,omitempty"`
CreateNewChangeForAllNotInTarget string `json:"create_new_change_for_all_not_in_target,omitempty"`
RequireChangeID string `json:"require_change_id,omitempty"`
MaxObjectSizeLimit MaxObjectSizeLimitInfo `json:"max_object_size_limit,omitempty"`
SubmitType string `json:"submit_type,omitempty"`
State string `json:"state,omitempty"`
PluginConfigValues map[string]map[string]string `json:"plugin_config_values,omitempty"`
}
// ProjectBaseOptions specifies the really basic options for projects
// and sub functionality (e.g. Tags)
type ProjectBaseOptions struct {
// Limit the number of projects to be included in the results.
Limit int `url:"n,omitempty"`
// Skip the given number of branches from the beginning of the list.
Skip string `url:"s,omitempty"`
}
// ProjectOptions specifies the parameters to the ProjectsService.ListProjects.
type ProjectOptions struct {
ProjectBaseOptions
// Limit the results to the projects having the specified branch and include the sha1 of the branch in the results.
Branch string `url:"b,omitempty"`
// Include project description in the results.
Description bool `url:"d,omitempty"`
// Limit the results to those projects that start with the specified prefix.
Prefix string `url:"p,omitempty"`
// Limit the results to those projects that match the specified regex.
// Boundary matchers '^' and '$' are implicit.
// For example: the regex 'test.*' will match any projects that start with 'test' and regex '.*test' will match any project that end with 'test'.
Regex string `url:"r,omitempty"`
// Skip the given number of projects from the beginning of the list.
Skip string `url:"S,omitempty"`
// Limit the results to those projects that match the specified substring.
Substring string `url:"m,omitempty"`
// Get projects inheritance in a tree-like format.
// This option does not work together with the branch option.
Tree bool `url:"t,omitempty"`
// Get projects with specified type: ALL, CODE, PERMISSIONS.
Type string `url:"type,omitempty"`
}
// ListProjects lists the projects accessible by the caller.
// This is the same as using the ls-projects command over SSH, and accepts the same options as query parameters.
// The entries in the map are sorted by project name.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-projects
func (s *ProjectsService) ListProjects(opt *ProjectOptions) (*map[string]ProjectInfo, *Response, error) {
u := "projects/"
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
v := new(map[string]ProjectInfo)
resp, err := s.client.Call("GET", u, nil, v)
return v, resp, err
}
// GetProject retrieves a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project
func (s *ProjectsService) GetProject(projectName string) (*ProjectInfo, *Response, error) {
u := fmt.Sprintf("projects/%s", url.QueryEscape(projectName))
v := new(ProjectInfo)
resp, err := s.client.Call("GET", u, nil, v)
return v, resp, err
}
// CreateProject creates a new project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-project
func (s *ProjectsService) CreateProject(projectName string, input *ProjectInput) (*ProjectInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/", url.QueryEscape(projectName))
v := new(ProjectInfo)
resp, err := s.client.Call("PUT", u, input, v)
return v, resp, err
}
// GetProjectDescription retrieves the description of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project-description
func (s *ProjectsService) GetProjectDescription(projectName string) (string, *Response, error) {
u := fmt.Sprintf("projects/%s/description", url.QueryEscape(projectName))
return getStringResponseWithoutOptions(s.client, u)
}
// GetProjectParent retrieves the name of a projects parent project.
// For the All-Projects root project an empty string is returned.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project-parent
func (s *ProjectsService) GetProjectParent(projectName string) (string, *Response, error) {
u := fmt.Sprintf("projects/%s/parent", url.QueryEscape(projectName))
return getStringResponseWithoutOptions(s.client, u)
}
// GetHEAD retrieves for a project the name of the branch to which HEAD points.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
func (s *ProjectsService) GetHEAD(projectName string) (string, *Response, error) {
u := fmt.Sprintf("projects/%s/HEAD", url.QueryEscape(projectName))
return getStringResponseWithoutOptions(s.client, u)
}
// GetRepositoryStatistics return statistics for the repository of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-repository-statistics
func (s *ProjectsService) GetRepositoryStatistics(projectName string) (*RepositoryStatisticsInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/statistics.git", url.QueryEscape(projectName))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(RepositoryStatisticsInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetConfig gets some configuration information about a project.
// Note that this config info is not simply the contents of project.config;
// it generally contains fields that may have been inherited from parent projects.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-config
func (s *ProjectsService) GetConfig(projectName string) (*ConfigInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/config'", url.QueryEscape(projectName))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(ConfigInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetProjectDescription sets the description of a project.
// The new project description must be provided in the request body inside a ProjectDescriptionInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-project-description
func (s *ProjectsService) SetProjectDescription(projectName string, input *ProjectDescriptionInput) (*string, *Response, error) {
u := fmt.Sprintf("projects/%s/description'", url.QueryEscape(projectName))
// TODO Use here the getStringResponseWithoutOptions (for PUT requests)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteProjectDescription deletes the description of a project.
// The request body does not need to include a ProjectDescriptionInput entity if no commit message is specified.
//
// Please note that some proxies prohibit request bodies for DELETE requests.
// In this case, if you want to specify a commit message, use PUT to delete the description.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-project-description
func (s *ProjectsService) DeleteProjectDescription(projectName string) (*Response, error) {
u := fmt.Sprintf("projects/%s/description'", url.QueryEscape(projectName))
return s.client.DeleteRequest(u, nil)
}
// BanCommit marks commits as banned for the project.
// If a commit is banned Gerrit rejects every push that includes this commit with contains banned commit ...
//
// Note:
// This REST endpoint only marks the commits as banned, but it does not remove the commits from the history of any central branch.
// This needs to be done manually.
// The commits to be banned must be specified in the request body as a BanInput entity.
//
// The caller must be project owner.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#ban-commit
func (s *ProjectsService) BanCommit(projectName string, input *BanInput) (*BanResultInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/ban'", url.QueryEscape(projectName))
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(BanResultInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetConfig sets the configuration of a project.
// The new configuration must be provided in the request body as a ConfigInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-config
func (s *ProjectsService) SetConfig(projectName string, input *ConfigInput) (*ConfigInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/config'", url.QueryEscape(projectName))
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(ConfigInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetHEAD sets HEAD for a project.
// The new ref to which HEAD should point must be provided in the request body inside a HeadInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
func (s *ProjectsService) SetHEAD(projectName string, input *HeadInput) (*string, *Response, error) {
u := fmt.Sprintf("projects/%s/HEAD'", url.QueryEscape(projectName))
// TODO Use here the getStringResponseWithoutOptions (for PUT requests)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetProjectParent sets the parent project for a project.
// The new name of the parent project must be provided in the request body inside a ProjectParentInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-project-parent
func (s *ProjectsService) SetProjectParent(projectName string, input *ProjectParentInput) (*string, *Response, error) {
u := fmt.Sprintf("projects/%s/parent'", url.QueryEscape(projectName))
// TODO Use here the getStringResponseWithoutOptions (for PUT requests)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(string)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// RunGC runs the Git garbage collection for the repository of a project.
// The response is the streamed output of the garbage collection.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#run-gc
func (s *ProjectsService) RunGC(projectName string, input *GCInput) (*Response, error) {
u := fmt.Sprintf("projects/%s/gc'", url.QueryEscape(projectName))
req, err := s.client.NewRequest("POST", u, input)
if err != nil {
return nil, err
}
resp, err := s.client.Do(req, nil)
if err != nil {
return resp, err
}
return resp, err
}

View File

@ -0,0 +1,157 @@
package gerrit
import (
"fmt"
"net/url"
)
// BranchInfo entity contains information about a branch.
type BranchInfo struct {
Ref string `json:"ref"`
Revision string `json:"revision"`
CanDelete bool `json:"can_delete"`
WebLinks []WebLinkInfo `json:"web_links,omitempty"`
}
// BranchInput entity contains information for the creation of a new branch.
type BranchInput struct {
Ref string `json:"ref,omitempty"`
Revision string `json:"revision,omitempty"`
}
// DeleteBranchesInput entity contains information about branches that should be deleted.
type DeleteBranchesInput struct {
Branches []string `json:"DeleteBranchesInput"`
}
// BranchOptions specifies the parameters to the branch API endpoints.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#branch-options
type BranchOptions struct {
// Limit the number of branches to be included in the results.
Limit int `url:"n,omitempty"`
// Skip the given number of branches from the beginning of the list.
Skip string `url:"s,omitempty"`
// Substring limits the results to those projects that match the specified substring.
Substring string `url:"m,omitempty"`
// Limit the results to those branches that match the specified regex.
// Boundary matchers '^' and '$' are implicit.
// For example: the regex 't*' will match any branches that start with 'test' and regex '*t' will match any branches that end with 'test'.
Regex string `url:"r,omitempty"`
}
// ListBranches list the branches of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-branches
func (s *ProjectsService) ListBranches(projectName string, opt *BranchOptions) (*[]BranchInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/", url.QueryEscape(projectName))
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]BranchInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetBranch retrieves a branch of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
func (s *ProjectsService) GetBranch(projectName, branchID string) (*BranchInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s", url.QueryEscape(projectName), branchID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(BranchInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetReflog gets the reflog of a certain branch.
// The caller must be project owner.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-reflog
func (s *ProjectsService) GetReflog(projectName, branchID string) (*[]ReflogEntryInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s/reflog", url.QueryEscape(projectName), branchID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ReflogEntryInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// CreateBranch creates a new branch.
// In the request body additional data for the branch can be provided as BranchInput.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
func (s *ProjectsService) CreateBranch(projectName, branchID string, input *BranchInput) (*BranchInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s", url.QueryEscape(projectName), branchID)
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(BranchInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteBranch deletes a branch.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-branch
func (s *ProjectsService) DeleteBranch(projectName, branchID string) (*Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s", url.QueryEscape(projectName), branchID)
return s.client.DeleteRequest(u, nil)
}
// DeleteBranches delete one or more branches.
// If some branches could not be deleted, the response is “409 Conflict” and the error message is contained in the response body.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-branches
func (s *ProjectsService) DeleteBranches(projectName string, input *DeleteBranchesInput) (*Response, error) {
u := fmt.Sprintf("projects/%s/branches:delete", url.QueryEscape(projectName))
return s.client.DeleteRequest(u, input)
}
// GetBranchContent gets the content of a file from the HEAD revision of a certain branch.
// The content is returned as base64 encoded string.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content
func (s *ProjectsService) GetBranchContent(projectName, branchID, fileID string) (string, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s/files/%s/content", url.QueryEscape(projectName), branchID, fileID)
return getStringResponseWithoutOptions(s.client, u)
}

View File

@ -0,0 +1,66 @@
package gerrit
import (
"fmt"
"net/url"
)
// ChildProjectOptions specifies the parameters to the Child Project API endpoints.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-child-projects
type ChildProjectOptions struct {
// Recursive resolve the child projects of a project recursively.
// Child projects that are not visible to the calling user are ignored and are not resolved further.
Recursive int `url:"recursive,omitempty"`
}
// ListChildProjects lists the direct child projects of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-child-projects
func (s *ProjectsService) ListChildProjects(projectName string, opt *ChildProjectOptions) (*[]ProjectInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/children/", url.QueryEscape(projectName))
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]ProjectInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetChildProject retrieves a child project.
// If a non-direct child project should be retrieved the parameter recursive must be set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-child-project
func (s *ProjectsService) GetChildProject(projectName, childProjectName string, opt *ChildProjectOptions) (*ProjectInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/children/%s", url.QueryEscape(projectName), url.QueryEscape(childProjectName))
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(ProjectInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}

View File

@ -0,0 +1,36 @@
package gerrit
import (
"fmt"
"net/url"
)
// GetCommit retrieves a commit of a project.
// The commit must be visible to the caller.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit
func (s *ProjectsService) GetCommit(projectName, commitID string) (*CommitInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/commits/%s", url.QueryEscape(projectName), commitID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(CommitInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetCommitContent gets the content of a file from the HEAD revision of a certain branch.
// The content is returned as base64 encoded string.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content
func (s *ProjectsService) GetCommitContent(projectName, branchID, fileID string) (string, *Response, error) {
u := fmt.Sprintf("projects/%s/branches/%s/files/%s/content", url.QueryEscape(projectName), branchID, fileID)
return getStringResponseWithoutOptions(s.client, u)
}

View File

@ -0,0 +1,108 @@
package gerrit
import (
"fmt"
"net/url"
)
// DashboardSectionInfo entity contains information about a section in a dashboard.
type DashboardSectionInfo struct {
Name string `json:"name"`
Query string `json:"query"`
}
// DashboardInput entity contains information to create/update a project dashboard.
type DashboardInput struct {
ID string `json:"id,omitempty"`
CommitMessage string `json:"commit_message,omitempty"`
}
// DashboardInfo entity contains information about a project dashboard.
type DashboardInfo struct {
ID string `json:"id"`
Project string `json:"project"`
DefiningProject string `json:"defining_project"`
Ref string `json:"ref"`
Path string `json:"path"`
Description string `json:"description,omitempty"`
Foreach string `json:"foreach,omitempty"`
URL string `json:"url"`
Default bool `json:"default"`
Title string `json:"title,omitempty"`
Sections []DashboardSectionInfo `json:"sections"`
}
// ListDashboards list custom dashboards for a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-dashboards
func (s *ProjectsService) ListDashboards(projectName string) (*[]DashboardInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/dashboards/", url.QueryEscape(projectName))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]DashboardInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetDashboard list custom dashboards for a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-dashboard
func (s *ProjectsService) GetDashboard(projectName, dashboardName string) (*DashboardInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/dashboards/%s", url.QueryEscape(projectName), url.QueryEscape(dashboardName))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(DashboardInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// SetDashboard updates/Creates a project dashboard.
// Currently only supported for the default dashboard.
//
// The creation/update information for the dashboard must be provided in the request body as a DashboardInput entity.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-dashboard
func (s *ProjectsService) SetDashboard(projectName, dashboardID string, input *DashboardInput) (*DashboardInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/dashboards/%s", url.QueryEscape(projectName), url.QueryEscape(dashboardID))
req, err := s.client.NewRequest("PUT", u, input)
if err != nil {
return nil, nil, err
}
v := new(DashboardInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// DeleteDashboard deletes a project dashboard.
// Currently only supported for the default dashboard.
//
// The request body does not need to include a DashboardInput entity if no commit message is specified.
// Please note that some proxies prohibit request bodies for DELETE requests.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-dashboard
func (s *ProjectsService) DeleteDashboard(projectName, dashboardID string, input *DashboardInput) (*Response, error) {
u := fmt.Sprintf("projects/%s/dashboards/%s", url.QueryEscape(projectName), url.QueryEscape(dashboardID))
return s.client.DeleteRequest(u, input)
}

View File

@ -0,0 +1,60 @@
package gerrit
import (
"fmt"
"net/url"
)
// TagInfo entity contains information about a tag.
type TagInfo struct {
Ref string `json:"ref"`
Revision string `json:"revision"`
Object string `json:"object"`
Message string `json:"message"`
Tagger GitPersonInfo `json:"tagger"`
Created *Timestamp `json:"created,omitempty"`
}
// ListTags list the tags of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-tags
func (s *ProjectsService) ListTags(projectName string, opt *ProjectBaseOptions) (*[]TagInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/tags/", url.QueryEscape(projectName))
u, err := addOptions(u, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new([]TagInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}
// GetTag retrieves a tag of a project.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-tag
func (s *ProjectsService) GetTag(projectName, tagName string) (*TagInfo, *Response, error) {
u := fmt.Sprintf("projects/%s/tags/%s", url.QueryEscape(projectName), url.QueryEscape(tagName))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
v := new(TagInfo)
resp, err := s.client.Do(req, v)
if err != nil {
return nil, resp, err
}
return v, resp, err
}

88
vendor/github.com/andygrunwald/go-gerrit/types.go generated vendored Normal file
View File

@ -0,0 +1,88 @@
package gerrit
import (
"encoding/json"
"errors"
"strconv"
"time"
)
// Timestamp represents an instant in time with nanosecond precision, in UTC time zone.
// It encodes to and from JSON in Gerrit's timestamp format.
// All exported methods of time.Time can be called on Timestamp.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api.html#timestamp
type Timestamp struct {
// Time is an instant in time. Its time zone must be UTC.
time.Time
}
// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in Gerrit's timestamp format.
// An error is returned if t.Time time zone is not UTC.
func (t Timestamp) MarshalJSON() ([]byte, error) {
if t.Location() != time.UTC {
return nil, errors.New("Timestamp.MarshalJSON: time zone must be UTC")
}
if y := t.Year(); y < 0 || 9999 < y {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#issuecomment-66073163 for more discussion.
return nil, errors.New("Timestamp.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len(timeLayout)+2)
b = append(b, '"')
b = t.AppendFormat(b, timeLayout)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in Gerrit's timestamp format.
func (t *Timestamp) UnmarshalJSON(b []byte) error {
// Ignore null, like in the main JSON package.
if string(b) == "null" {
return nil
}
var err error
t.Time, err = time.Parse(`"`+timeLayout+`"`, string(b))
return err
}
// Gerrit's timestamp layout is like time.RFC3339Nano, but with a space instead
// of the "T", without a timezone (it's always in UTC), and always includes nanoseconds.
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html#timestamp.
const timeLayout = "2006-01-02 15:04:05.000000000"
// Number is a string representing a number. This type is only used in cases
// where the API being queried may return an inconsistent result.
type Number string
// String returns the string representing the current number.
func (n *Number) String() string {
return string(*n)
}
// Int returns the current number as an integer
func (n *Number) Int() (int, error) {
return strconv.Atoi(n.String())
}
// UnmarshalJSON will marshal the provided data into the current *Number struct.
func (n *Number) UnmarshalJSON(data []byte) error {
// `data` is a number represented as a string (ex. "5").
var stringNumber string
if err := json.Unmarshal(data, &stringNumber); err == nil {
*n = Number(stringNumber)
return nil
}
// `data` is a number represented as an integer (ex. 5). Here
// we're using json.Unmarshal to convert bytes -> number which
// we then convert to our own Number type.
var number int
if err := json.Unmarshal(data, &number); err == nil {
*n = Number(strconv.Itoa(number))
return nil
}
return errors.New("cannot convert data to number")
}

View File

@ -194,6 +194,7 @@ type TeamChange struct {
type InstallationEvent struct {
// The action that was performed. Can be either "created" or "deleted".
Action *string `json:"action,omitempty"`
Repositories []*Repository `json:"repositories,omitempty"`
Sender *User `json:"sender,omitempty"`
Installation *Installation `json:"installation,omitempty"`
}

View File

@ -6,7 +6,7 @@
Package config provides convenient access methods to configuration stored as
JSON or YAML.
Let's start with a simple YAML example:
Let's start with a simple YAML file config.yml:
development:
database:
@ -23,6 +23,12 @@ Let's start with a simple YAML example:
We can parse it using ParseYaml(), which will return a *Config instance on
success:
file, err := ioutil.ReadFile("config.yml")
if err != nil {
panic(err)
}
yamlString := string(file)
cfg, err := config.ParseYaml(yamlString)
An equivalent JSON configuration could be built using ParseJson():

View File

@ -12,6 +12,7 @@ Among these components are:
- __Input forms__ (include __input/password fields__, __drop-down selections__, __checkboxes__, and __buttons__)
- Navigable multi-color __text views__
- Sophisticated navigable __table views__
- Flexible __tree views__
- Selectable __lists__
- __Grid__, __Flexbox__ and __page layouts__
- Modal __message windows__
@ -64,6 +65,8 @@ Add your issue here on GitHub. Feel free to get in touch if you have any questio
(There are no corresponding tags in the project. I only keep such a history in this README.)
- v0.17 (2018-06-20)
- Added `TreeView`.
- v0.15 (2018-05-02)
- `Flex` and `Grid` don't clear their background per default, thus allowing for custom modals. See the [Wiki](https://github.com/rivo/tview/wiki/Modal) for an example.
- v0.14 (2018-04-13)

10
vendor/github.com/rivo/tview/doc.go generated vendored
View File

@ -7,10 +7,12 @@ Widgets
The package implements the following widgets:
- TextView: Scrollable windows that display multi-colored text. Text may also
- TextView: A scrollable window that display multi-colored text. Text may also
be highlighted.
- Table: Scrollable display of tabular data. Table cells, rows, or columns may
also be highlighted.
- Table: A scrollable display of tabular data. Table cells, rows, or columns
may also be highlighted.
- TreeView: A scrollable display for hierarchical data. Tree nodes can be
highlighted, collapsed, expanded, and more.
- List: A navigable text list with optional keyboard shortcuts.
- InputField: One-line input fields to enter text.
- DropDown: Drop-down selection fields.
@ -83,7 +85,7 @@ tag is as follows:
[<foreground>:<background>:<flags>]
Each of the three fields can be left blank and trailing fields can be ommitted.
Each of the three fields can be left blank and trailing fields can be omitted.
(Empty square brackets "[]", however, are not considered color tags.) Colors
that are not specified will be left unchanged. A field with just a dash ("-")
means "reset to default".

View File

@ -644,7 +644,6 @@ ColumnLoop:
}
expWidth := toDistribute * expansion / expansionTotal
widths[index] += expWidth
tableWidth += expWidth
toDistribute -= expWidth
expansionTotal -= expansion
}

View File

@ -104,6 +104,10 @@ type TextView struct {
// during re-indexing. Set to -1 if there is no current highlight.
fromHighlight, toHighlight int
// The screen space column of the highlight in its first line. Set to -1 if
// there is no current highlight.
posHighlight int
// A set of region IDs that are currently highlighted.
highlights map[string]struct{}
@ -171,6 +175,7 @@ func NewTextView() *TextView {
align: AlignLeft,
wrap: true,
textColor: Styles.PrimaryTextColor,
regions: false,
dynamicColors: false,
}
}
@ -503,7 +508,7 @@ func (t *TextView) reindexBuffer(width int) {
return // Nothing has changed. We can still use the current index.
}
t.index = nil
t.fromHighlight, t.toHighlight = -1, -1
t.fromHighlight, t.toHighlight, t.posHighlight = -1, -1, -1
// If there's no space, there's no index.
if width < 1 {
@ -522,8 +527,9 @@ func (t *TextView) reindexBuffer(width int) {
colorTags [][]string
escapeIndices [][]int
)
strippedStr := str
if t.dynamicColors {
colorTagIndices, colorTags, escapeIndices, str, _ = decomposeString(str)
colorTagIndices, colorTags, escapeIndices, strippedStr, _ = decomposeString(str)
}
// Find all regions in this line. Then remove them.
@ -534,14 +540,18 @@ func (t *TextView) reindexBuffer(width int) {
if t.regions {
regionIndices = regionPattern.FindAllStringIndex(str, -1)
regions = regionPattern.FindAllStringSubmatch(str, -1)
str = regionPattern.ReplaceAllString(str, "")
if !t.dynamicColors {
// We haven't detected escape tags yet. Do it now.
strippedStr = regionPattern.ReplaceAllString(strippedStr, "")
}
// Find all escape tags in this line. Escape them.
if t.dynamicColors || t.regions {
escapeIndices = escapePattern.FindAllStringIndex(str, -1)
str = escapePattern.ReplaceAllString(str, "[$1$2]")
}
strippedStr = escapePattern.ReplaceAllString(strippedStr, "[$1$2]")
}
// We don't need the original string anymore for now.
str = strippedStr
// Split the line if required.
var splitLines []string
if t.wrap && len(str) > 0 {
@ -585,15 +595,53 @@ func (t *TextView) reindexBuffer(width int) {
// Shift original position with tags.
lineLength := len(splitLine)
remainingLength := lineLength
tagEnd := originalPos
totalTagLength := 0
for {
if colorPos < len(colorTagIndices) && colorTagIndices[colorPos][0] <= originalPos+lineLength {
// Which tag comes next?
nextTag := make([][3]int, 0, 3)
if colorPos < len(colorTagIndices) {
nextTag = append(nextTag, [3]int{colorTagIndices[colorPos][0], colorTagIndices[colorPos][1], 0}) // 0 = color tag.
}
if regionPos < len(regionIndices) {
nextTag = append(nextTag, [3]int{regionIndices[regionPos][0], regionIndices[regionPos][1], 1}) // 1 = region tag.
}
if escapePos < len(escapeIndices) {
nextTag = append(nextTag, [3]int{escapeIndices[escapePos][0], escapeIndices[escapePos][1], 2}) // 2 = escape tag.
}
minPos := -1
tagIndex := -1
for index, pair := range nextTag {
if minPos < 0 || pair[0] < minPos {
minPos = pair[0]
tagIndex = index
}
}
// Is the next tag in range?
if tagIndex < 0 || minPos >= tagEnd+remainingLength {
break // No. We're done with this line.
}
// Advance.
strippedTagStart := nextTag[tagIndex][0] - originalPos - totalTagLength
tagEnd = nextTag[tagIndex][1]
tagLength := tagEnd - nextTag[tagIndex][0]
if nextTag[tagIndex][2] == 2 {
tagLength = 1
}
totalTagLength += tagLength
remainingLength = lineLength - (tagEnd - originalPos - totalTagLength)
// Process the tag.
switch nextTag[tagIndex][2] {
case 0:
// Process color tags.
originalPos += colorTagIndices[colorPos][1] - colorTagIndices[colorPos][0]
foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colorTags[colorPos])
colorPos++
} else if regionPos < len(regionIndices) && regionIndices[regionPos][0] <= originalPos+lineLength {
case 1:
// Process region tags.
originalPos += regionIndices[regionPos][1] - regionIndices[regionPos][0]
regionID = regions[regionPos][1]
_, highlighted = t.highlights[regionID]
@ -602,23 +650,21 @@ func (t *TextView) reindexBuffer(width int) {
line := len(t.index)
if t.fromHighlight < 0 {
t.fromHighlight, t.toHighlight = line, line
t.posHighlight = runewidth.StringWidth(splitLine[:strippedTagStart])
} else if line > t.toHighlight {
t.toHighlight = line
}
}
regionPos++
} else if escapePos < len(escapeIndices) && escapeIndices[escapePos][0] <= originalPos+lineLength {
case 2:
// Process escape tags.
originalPos++
escapePos++
} else {
break
}
}
// Advance to next line.
originalPos += lineLength
originalPos += lineLength + totalTagLength
// Append this line.
line.NextPos = originalPos
@ -683,6 +729,16 @@ func (t *TextView) Draw(screen tcell.Screen) {
// No, let's move to the start of the highlights.
t.lineOffset = t.fromHighlight
}
// If the highlight is too far to the right, move it to the middle.
if t.posHighlight-t.columnOffset > 3*width/4 {
t.columnOffset = t.posHighlight - width/2
}
// If the highlight is off-screen on the left, move it on-screen.
if t.posHighlight-t.columnOffset < 0 {
t.columnOffset = t.posHighlight - width/4
}
}
t.scrollToHighlights = false

665
vendor/github.com/rivo/tview/treeview.go generated vendored Normal file
View File

@ -0,0 +1,665 @@
package tview
import (
"github.com/gdamore/tcell"
)
// Tree navigation events.
const (
treeNone int = iota
treeHome
treeEnd
treeUp
treeDown
treePageUp
treePageDown
)
// TreeNode represents one node in a tree view.
type TreeNode struct {
// The reference object.
reference interface{}
// This node's child nodes.
children []*TreeNode
// The item's text.
text string
// The text color.
color tcell.Color
// Whether or not this node can be selected.
selectable bool
// Whether or not this node's children should be displayed.
expanded bool
// The additional horizontal indent of this node's text.
indent int
// An optional function which is called when the user selects this node.
selected func()
// Temporary member variables.
parent *TreeNode // The parent node (nil for the root).
level int // The hierarchy level (0 for the root, 1 for its children, and so on).
graphicsX int // The x-coordinate of the left-most graphics rune.
textX int // The x-coordinate of the first rune of the text.
}
// NewTreeNode returns a new tree node.
func NewTreeNode(text string) *TreeNode {
return &TreeNode{
text: text,
color: Styles.PrimaryTextColor,
indent: 2,
expanded: true,
selectable: true,
}
}
// Walk traverses this node's subtree in depth-first, pre-order (NLR) order and
// calls the provided callback function on each traversed node (which includes
// this node) with the traversed node and its parent node (nil for this node).
// The callback returns whether traversal should continue with the traversed
// node's child nodes (true) or not recurse any deeper (false).
func (n *TreeNode) Walk(callback func(node, parent *TreeNode) bool) *TreeNode {
n.parent = nil
nodes := []*TreeNode{n}
for len(nodes) > 0 {
// Pop the top node and process it.
node := nodes[len(nodes)-1]
nodes = nodes[:len(nodes)-1]
if !callback(node, node.parent) {
// Don't add any children.
continue
}
// Add children in reverse order.
for index := len(node.children) - 1; index >= 0; index-- {
node.children[index].parent = node
nodes = append(nodes, node.children[index])
}
}
return n
}
// SetReference allows you to store a reference of any type in this node. This
// will allow you to establish a mapping between the TreeView hierarchy and your
// internal tree structure.
func (n *TreeNode) SetReference(reference interface{}) *TreeNode {
n.reference = reference
return n
}
// GetReference returns this node's reference object.
func (n *TreeNode) GetReference() interface{} {
return n.reference
}
// SetChildren sets this node's child nodes.
func (n *TreeNode) SetChildren(childNodes []*TreeNode) *TreeNode {
n.children = childNodes
return n
}
// GetChildren returns this node's children.
func (n *TreeNode) GetChildren() []*TreeNode {
return n.children
}
// ClearChildren removes all child nodes from this node.
func (n *TreeNode) ClearChildren() *TreeNode {
n.children = nil
return n
}
// AddChild adds a new child node to this node.
func (n *TreeNode) AddChild(node *TreeNode) *TreeNode {
n.children = append(n.children, node)
return n
}
// SetSelectable sets a flag indicating whether this node can be selected by
// the user.
func (n *TreeNode) SetSelectable(selectable bool) *TreeNode {
n.selectable = selectable
return n
}
// SetSelectedFunc sets a function which is called when the user selects this
// node by hitting Enter when it is selected.
func (n *TreeNode) SetSelectedFunc(handler func()) *TreeNode {
n.selected = handler
return n
}
// SetExpanded sets whether or not this node's child nodes should be displayed.
func (n *TreeNode) SetExpanded(expanded bool) *TreeNode {
n.expanded = expanded
return n
}
// Expand makes the child nodes of this node appear.
func (n *TreeNode) Expand() *TreeNode {
n.expanded = true
return n
}
// Collapse makes the child nodes of this node disappear.
func (n *TreeNode) Collapse() *TreeNode {
n.expanded = false
return n
}
// ExpandAll expands this node and all descendent nodes.
func (n *TreeNode) ExpandAll() *TreeNode {
n.Walk(func(node, parent *TreeNode) bool {
node.expanded = true
return true
})
return n
}
// CollapseAll collapses this node and all descendent nodes.
func (n *TreeNode) CollapseAll() *TreeNode {
n.Walk(func(node, parent *TreeNode) bool {
n.expanded = false
return true
})
return n
}
// IsExpanded returns whether the child nodes of this node are visible.
func (n *TreeNode) IsExpanded() bool {
return n.expanded
}
// SetText sets the node's text which is displayed.
func (n *TreeNode) SetText(text string) *TreeNode {
n.text = text
return n
}
// SetColor sets the node's text color.
func (n *TreeNode) SetColor(color tcell.Color) *TreeNode {
n.color = color
return n
}
// SetIndent sets an additional indentation for this node's text. A value of 0
// keeps the text as far left as possible with a minimum of line graphics. Any
// value greater than that moves the text to the right.
func (n *TreeNode) SetIndent(indent int) *TreeNode {
n.indent = indent
return n
}
// TreeView displays tree structures. A tree consists of nodes (TreeNode
// objects) where each node has zero or more child nodes and exactly one parent
// node (except for the root node which has no parent node).
//
// The SetRoot() function is used to specify the root of the tree. Other nodes
// are added locally to the root node or any of its descendents. See the
// TreeNode documentation for details on node attributes. (You can use
// SetReference() to store a reference to nodes of your own tree structure.)
//
// Nodes can be selected by calling SetCurrentNode(). The user can navigate the
// selection or the tree by using the following keys:
//
// - j, down arrow, right arrow: Move (the selection) down by one node.
// - k, up arrow, left arrow: Move (the selection) up by one node.
// - g, home: Move (the selection) to the top.
// - G, end: Move (the selection) to the bottom.
// - Ctrl-F, page down: Move (the selection) down by one page.
// - Ctrl-B, page up: Move (the selection) up by one page.
//
// Selected nodes can trigger the "selected" callback when the user hits Enter.
//
// The root node corresponds to level 0, its children correspond to level 1,
// their children to level 2, and so on. Per default, the first level that is
// displayed is 0, i.e. the root node. You can call SetTopLevel() to hide
// levels.
//
// If graphics are turned on (see SetGraphics()), lines indicate the tree's
// hierarchy. Alternative (or additionally), you can set different prefixes
// using SetPrefixes() for different levels, for example to display hierarchical
// bullet point lists.
//
// See https://github.com/rivo/tview/wiki/TreeView for an example.
type TreeView struct {
*Box
// The root node.
root *TreeNode
// The currently selected node or nil if no node is selected.
currentNode *TreeNode
// The movement to be performed during the call to Draw(), one of the
// constants defined above.
movement int
// The top hierarchical level shown. (0 corresponds to the root level.)
topLevel int
// Strings drawn before the nodes, based on their level.
prefixes []string
// Vertical scroll offset.
offsetY int
// If set to true, all node texts will be aligned horizontally.
align bool
// If set to true, the tree structure is drawn using lines.
graphics bool
// The color of the lines.
graphicsColor tcell.Color
// An optional function which is called when the user has navigated to a new
// tree node.
changed func(node *TreeNode)
// An optional function which is called when a tree item was selected.
selected func(node *TreeNode)
}
// NewTreeView returns a new tree view.
func NewTreeView() *TreeView {
return &TreeView{
Box: NewBox(),
graphics: true,
graphicsColor: Styles.GraphicsColor,
}
}
// SetRoot sets the root node of the tree.
func (t *TreeView) SetRoot(root *TreeNode) *TreeView {
t.root = root
return t
}
// GetRoot returns the root node of the tree. If no such node was previously
// set, nil is returned.
func (t *TreeView) GetRoot() *TreeNode {
return t.root
}
// SetCurrentNode sets the currently selected node. Provide nil to clear all
// selections. Selected nodes must be visible and selectable, or else the
// selection will be changed to the top-most selectable and visible node.
//
// This function does NOT trigger the "changed" callback.
func (t *TreeView) SetCurrentNode(node *TreeNode) *TreeView {
t.currentNode = node
return t
}
// GetCurrentNode returns the currently selected node or nil of no node is
// currently selected.
func (t *TreeView) GetCurrentNode() *TreeNode {
return t.currentNode
}
// SetTopLevel sets the first tree level that is visible with 0 referring to the
// root, 1 to the root's child nodes, and so on. Nodes above the top level are
// not displayed.
func (t *TreeView) SetTopLevel(topLevel int) *TreeView {
t.topLevel = topLevel
return t
}
// SetPrefixes defines the strings drawn before the nodes' texts. This is a
// slice of strings where each element corresponds to a node's hierarchy level,
// i.e. 0 for the root, 1 for the root's children, and so on (levels will
// cycle).
//
// For example, to display a hierarchical list with bullet points:
//
// treeView.SetGraphics(false).
// SetPrefixes([]string{"* ", "- ", "x "})
func (t *TreeView) SetPrefixes(prefixes []string) *TreeView {
t.prefixes = prefixes
return t
}
// SetAlign controls the horizontal alignment of the node texts. If set to true,
// all texts except that of top-level nodes will be placed in the same column.
// If set to false, they will indent with the hierarchy.
func (t *TreeView) SetAlign(align bool) *TreeView {
t.align = align
return t
}
// SetGraphics sets a flag which determines whether or not line graphics are
// drawn to illustrate the tree's hierarchy.
func (t *TreeView) SetGraphics(showGraphics bool) *TreeView {
t.graphics = showGraphics
return t
}
// SetGraphicsColor sets the colors of the lines used to draw the tree structure.
func (t *TreeView) SetGraphicsColor(color tcell.Color) *TreeView {
t.graphicsColor = color
return t
}
// SetChangedFunc sets the function which is called when the user navigates to
// a new tree node.
func (t *TreeView) SetChangedFunc(handler func(node *TreeNode)) *TreeView {
t.changed = handler
return t
}
// SetSelectedFunc sets the function which is called when the user selects a
// node by pressing Enter on the current selection.
func (t *TreeView) SetSelectedFunc(handler func(node *TreeNode)) *TreeView {
t.selected = handler
return t
}
// Draw draws this primitive onto the screen.
func (t *TreeView) Draw(screen tcell.Screen) {
t.Box.Draw(screen)
if t.root == nil {
return
}
x, y, width, height := t.GetInnerRect()
// Determine visible nodes and their placement.
var graphicsOffset, maxTextX int
var nodes []*TreeNode
selectedIndex := -1
topLevelGraphicsX := -1
if t.graphics {
graphicsOffset = 1
}
t.root.Walk(func(node, parent *TreeNode) bool {
// Set node attributes.
node.parent = parent
if parent == nil {
node.level = 0
node.graphicsX = 0
node.textX = 0
} else {
node.level = parent.level + 1
node.graphicsX = parent.textX
node.textX = node.graphicsX + graphicsOffset + node.indent
}
if !t.graphics && t.align {
// Without graphics, we align nodes on the first column.
node.textX = 0
}
if node.level == t.topLevel {
// No graphics for top level nodes.
node.graphicsX = 0
node.textX = 0
}
if node.textX > maxTextX {
maxTextX = node.textX
}
if node == t.currentNode && node.selectable {
selectedIndex = len(nodes)
}
// Maybe we want to skip this level.
if t.topLevel == node.level && (topLevelGraphicsX < 0 || node.graphicsX < topLevelGraphicsX) {
topLevelGraphicsX = node.graphicsX
}
// Add and recurse (if desired).
if node.level >= t.topLevel {
nodes = append(nodes, node)
}
return node.expanded
})
// Post-process positions.
for _, node := range nodes {
// If text must align, we correct the positions.
if t.align && node.level > t.topLevel {
node.textX = maxTextX
}
// If we skipped levels, shift to the left.
if topLevelGraphicsX > 0 {
node.graphicsX -= topLevelGraphicsX
node.textX -= topLevelGraphicsX
}
}
// Process selection. (Also trigger events if necessary.)
if selectedIndex >= 0 {
// Move the selection.
newSelectedIndex := selectedIndex
MovementSwitch:
switch t.movement {
case treeUp:
for newSelectedIndex > 0 {
newSelectedIndex--
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
case treeDown:
for newSelectedIndex < len(nodes)-1 {
newSelectedIndex++
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
case treeHome:
for newSelectedIndex = 0; newSelectedIndex < len(nodes); newSelectedIndex++ {
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
case treeEnd:
for newSelectedIndex = len(nodes) - 1; newSelectedIndex >= 0; newSelectedIndex-- {
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
case treePageUp:
if newSelectedIndex+height < len(nodes) {
newSelectedIndex += height
} else {
newSelectedIndex = len(nodes) - 1
}
for ; newSelectedIndex < len(nodes); newSelectedIndex++ {
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
case treePageDown:
if newSelectedIndex >= height {
newSelectedIndex -= height
} else {
newSelectedIndex = 0
}
for ; newSelectedIndex >= 0; newSelectedIndex-- {
if nodes[newSelectedIndex].selectable {
break MovementSwitch
}
}
newSelectedIndex = selectedIndex
}
t.currentNode = nodes[newSelectedIndex]
if newSelectedIndex != selectedIndex {
t.movement = treeNone
if t.changed != nil {
t.changed(t.currentNode)
}
}
selectedIndex = newSelectedIndex
// Move selection into viewport.
if selectedIndex-t.offsetY >= height {
t.offsetY = selectedIndex - height + 1
}
if selectedIndex < t.offsetY {
t.offsetY = selectedIndex
}
} else {
// If selection is not visible or selectable, select the first candidate.
if t.currentNode != nil {
for index, node := range nodes {
if node.selectable {
selectedIndex = index
t.currentNode = node
break
}
}
}
if selectedIndex < 0 {
t.currentNode = nil
}
}
// Scroll the tree.
switch t.movement {
case treeUp:
t.offsetY--
case treeDown:
t.offsetY++
case treeHome:
t.offsetY = 0
case treeEnd:
t.offsetY = len(nodes)
case treePageUp:
t.offsetY -= height
case treePageDown:
t.offsetY += height
}
t.movement = treeNone
// Fix invalid offsets.
if t.offsetY >= len(nodes)-height {
t.offsetY = len(nodes) - height
}
if t.offsetY < 0 {
t.offsetY = 0
}
// Draw the tree.
posY := y
lineStyle := tcell.StyleDefault.Foreground(t.graphicsColor)
for index, node := range nodes {
// Skip invisible parts.
if posY >= y+height+1 {
break
}
if index < t.offsetY {
continue
}
// Draw the graphics.
if t.graphics {
// Draw ancestor branches.
ancestor := node.parent
for ancestor != nil && ancestor.parent != nil && ancestor.parent.level >= t.topLevel {
if ancestor.graphicsX >= width {
continue
}
// Draw a branch if this ancestor is not a last child.
if ancestor.parent.children[len(ancestor.parent.children)-1] != ancestor {
if posY-1 >= y && ancestor.textX > ancestor.graphicsX {
PrintJoinedSemigraphics(screen, x+ancestor.graphicsX, posY-1, Borders.Vertical, t.graphicsColor)
}
if posY < y+height {
screen.SetContent(x+ancestor.graphicsX, posY, Borders.Vertical, nil, lineStyle)
}
}
ancestor = ancestor.parent
}
if node.textX > node.graphicsX && node.graphicsX < width {
// Connect to the node above.
if posY-1 >= y && nodes[index-1].graphicsX <= node.graphicsX && nodes[index-1].textX > node.graphicsX {
PrintJoinedSemigraphics(screen, x+node.graphicsX, posY-1, Borders.TopLeft, t.graphicsColor)
}
// Join this node.
if posY < y+height {
screen.SetContent(x+node.graphicsX, posY, Borders.BottomLeft, nil, lineStyle)
for pos := node.graphicsX + 1; pos < node.textX && pos < width; pos++ {
screen.SetContent(x+pos, posY, Borders.Horizontal, nil, lineStyle)
}
}
}
}
// Draw the prefix and the text.
if node.textX < width && posY < y+height {
// Prefix.
var prefixWidth int
if len(t.prefixes) > 0 {
_, prefixWidth = Print(screen, t.prefixes[(node.level-t.topLevel)%len(t.prefixes)], x+node.textX, posY, width-node.textX, AlignLeft, node.color)
}
// Text.
if node.textX+prefixWidth < width {
style := tcell.StyleDefault.Foreground(node.color)
if index == selectedIndex {
style = tcell.StyleDefault.Background(node.color).Foreground(t.backgroundColor)
}
printWithStyle(screen, node.text, x+node.textX+prefixWidth, posY, width-node.textX-prefixWidth, AlignLeft, style)
}
}
// Advance.
posY++
}
}
// InputHandler returns the handler for this primitive.
func (t *TreeView) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive)) {
return t.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p Primitive)) {
// Because the tree is flattened into a list only at drawing time, we also
// postpone the (selection) movement to drawing time.
switch key := event.Key(); key {
case tcell.KeyTab, tcell.KeyDown, tcell.KeyRight:
t.movement = treeDown
case tcell.KeyBacktab, tcell.KeyUp, tcell.KeyLeft:
t.movement = treeUp
case tcell.KeyHome:
t.movement = treeHome
case tcell.KeyEnd:
t.movement = treeEnd
case tcell.KeyPgDn, tcell.KeyCtrlF:
t.movement = treePageDown
case tcell.KeyPgUp, tcell.KeyCtrlB:
t.movement = treePageUp
case tcell.KeyRune:
switch event.Rune() {
case 'g':
t.movement = treeHome
case 'G':
t.movement = treeEnd
case 'j':
t.movement = treeDown
case 'k':
t.movement = treeUp
}
case tcell.KeyEnter:
if t.currentNode != nil {
if t.selected != nil {
t.selected(t.currentNode)
}
if t.currentNode.selected != nil {
t.currentNode.selected()
}
}
}
})
}

View File

@ -120,13 +120,12 @@ func overlayStyle(background tcell.Color, defaultStyle tcell.Style, fgColor, bgC
defFg, defBg, defAttr := defaultStyle.Decompose()
style := defaultStyle.Background(background)
if fgColor == "-" {
style = style.Foreground(defFg)
} else if fgColor != "" {
if fgColor != "" {
style = style.Foreground(tcell.GetColor(fgColor))
}
if bgColor == "-" {
if bgColor == "-" || bgColor == "" && defBg != tcell.ColorDefault {
style = style.Background(defBg)
} else if bgColor != "" {
style = style.Background(tcell.GetColor(bgColor))

View File

@ -56,18 +56,18 @@ const (
awardSnippets = "snippets"
)
// ListEmojiAwardsOptions represents the available options for listing emoji
// ListAwardEmojiOptions represents the available options for listing emoji
// for each resources
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html
type ListEmojiAwardsOptions ListOptions
type ListAwardEmojiOptions ListOptions
// ListMergeRequestAwardEmoji gets a list of all award emoji on the merge request.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#list-an-awardable-39-s-award-emoji
func (s *AwardEmojiService) ListMergeRequestAwardEmoji(pid interface{}, mergeRequestIID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListMergeRequestAwardEmoji(pid interface{}, mergeRequestIID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmoji(pid, awardMergeRequest, mergeRequestIID, opt, options...)
}
@ -75,7 +75,7 @@ func (s *AwardEmojiService) ListMergeRequestAwardEmoji(pid interface{}, mergeReq
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#list-an-awardable-39-s-award-emoji
func (s *AwardEmojiService) ListIssueAwardEmoji(pid interface{}, issueIID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListIssueAwardEmoji(pid interface{}, issueIID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmoji(pid, awardIssue, issueIID, opt, options...)
}
@ -83,11 +83,11 @@ func (s *AwardEmojiService) ListIssueAwardEmoji(pid interface{}, issueIID int, o
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#list-an-awardable-39-s-award-emoji
func (s *AwardEmojiService) ListSnippetAwardEmoji(pid interface{}, snippetID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListSnippetAwardEmoji(pid interface{}, snippetID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmoji(pid, awardSnippets, snippetID, opt, options...)
}
func (s *AwardEmojiService) listAwardEmoji(pid interface{}, resource string, resourceID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) listAwardEmoji(pid interface{}, resource string, resourceID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
@ -162,43 +162,51 @@ func (s *AwardEmojiService) getAwardEmoji(pid interface{}, resource string, reso
return a, resp, err
}
// CreateAwardEmojiOptions represents the available options for awarding emoji
// for a resource
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji
type CreateAwardEmojiOptions struct {
Name string `json:"name"`
}
// CreateMergeRequestAwardEmoji get an award emoji from merge request.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji
func (s *AwardEmojiService) CreateMergeRequestAwardEmoji(pid interface{}, mergeRequestIID, awardID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardMergeRequest, mergeRequestIID, awardID, options...)
func (s *AwardEmojiService) CreateMergeRequestAwardEmoji(pid interface{}, mergeRequestIID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardMergeRequest, mergeRequestIID, opt, options...)
}
// CreateIssueAwardEmoji get an award emoji from issue.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji
func (s *AwardEmojiService) CreateIssueAwardEmoji(pid interface{}, issueIID, awardID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardIssue, issueIID, awardID, options...)
func (s *AwardEmojiService) CreateIssueAwardEmoji(pid interface{}, issueIID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardIssue, issueIID, opt, options...)
}
// CreateSnippetAwardEmoji get an award emoji from snippet.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji
func (s *AwardEmojiService) CreateSnippetAwardEmoji(pid interface{}, snippetID, awardID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardSnippets, snippetID, awardID, options...)
func (s *AwardEmojiService) CreateSnippetAwardEmoji(pid interface{}, snippetID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmoji(pid, awardSnippets, snippetID, opt, options...)
}
func (s *AwardEmojiService) createAwardEmoji(pid interface{}, resource string, resourceID, awardID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) createAwardEmoji(pid interface{}, resource string, resourceID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("projects/%s/%s/%d/award_emoji/%d",
u := fmt.Sprintf("projects/%s/%s/%d/award_emoji",
url.QueryEscape(project),
resource,
resourceID,
awardID,
)
req, err := s.client.NewRequest("POST", u, nil, options)
req, err := s.client.NewRequest("POST", u, opt, options)
if err != nil {
return nil, nil, err
}
@ -260,7 +268,7 @@ func (s *AwardEmojiService) deleteAwardEmoji(pid interface{}, resource string, r
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) ListIssuesAwardEmojiOnNote(pid interface{}, issueID, noteID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListIssuesAwardEmojiOnNote(pid interface{}, issueID, noteID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmojiOnNote(pid, awardIssue, issueID, noteID, opt, options...)
}
@ -269,7 +277,7 @@ func (s *AwardEmojiService) ListIssuesAwardEmojiOnNote(pid interface{}, issueID,
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) ListMergeRequestAwardEmojiOnNote(pid interface{}, mergeRequestIID, noteID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListMergeRequestAwardEmojiOnNote(pid interface{}, mergeRequestIID, noteID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmojiOnNote(pid, awardMergeRequest, mergeRequestIID, noteID, opt, options...)
}
@ -278,11 +286,11 @@ func (s *AwardEmojiService) ListMergeRequestAwardEmojiOnNote(pid interface{}, me
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) ListSnippetAwardEmojiOnNote(pid interface{}, snippetIID, noteID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) ListSnippetAwardEmojiOnNote(pid interface{}, snippetIID, noteID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
return s.listAwardEmojiOnNote(pid, awardSnippets, snippetIID, noteID, opt, options...)
}
func (s *AwardEmojiService) listAwardEmojiOnNote(pid interface{}, resources string, ressourceID, noteID int, opt *ListEmojiAwardsOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) listAwardEmojiOnNote(pid interface{}, resources string, ressourceID, noteID int, opt *ListAwardEmojiOptions, options ...OptionFunc) ([]*AwardEmoji, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
@ -361,8 +369,8 @@ func (s *AwardEmojiService) getSingleNoteAwardEmoji(pid interface{}, ressource s
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) CreateIssuesAwardEmojiOnNote(pid interface{}, issueID, noteID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardIssue, issueID, noteID, options...)
func (s *AwardEmojiService) CreateIssuesAwardEmojiOnNote(pid interface{}, issueID, noteID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardIssue, issueID, noteID, opt, options...)
}
// CreateMergeRequestAwardEmojiOnNote gets an award emoji on a note from a
@ -370,23 +378,23 @@ func (s *AwardEmojiService) CreateIssuesAwardEmojiOnNote(pid interface{}, issueI
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) CreateMergeRequestAwardEmojiOnNote(pid interface{}, mergeRequestIID, noteID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardMergeRequest, mergeRequestIID, noteID, options...)
func (s *AwardEmojiService) CreateMergeRequestAwardEmojiOnNote(pid interface{}, mergeRequestIID, noteID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardMergeRequest, mergeRequestIID, noteID, opt, options...)
}
// CreateSnippetAwardEmojiOnNote gets an award emoji on a note from a snippet.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-emoji-on-notes
func (s *AwardEmojiService) CreateSnippetAwardEmojiOnNote(pid interface{}, snippetIID, noteID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardSnippets, snippetIID, noteID, options...)
func (s *AwardEmojiService) CreateSnippetAwardEmojiOnNote(pid interface{}, snippetIID, noteID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
return s.createAwardEmojiOnNote(pid, awardSnippets, snippetIID, noteID, opt, options...)
}
// CreateAwardEmojiOnNote award emoji on a note.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/award_emoji.html#award-a-new-emoji-on-a-note
func (s *AwardEmojiService) createAwardEmojiOnNote(pid interface{}, resource string, resourceID, noteID int, options ...OptionFunc) (*AwardEmoji, *Response, error) {
func (s *AwardEmojiService) createAwardEmojiOnNote(pid interface{}, resource string, resourceID, noteID int, opt *CreateAwardEmojiOptions, options ...OptionFunc) (*AwardEmoji, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err

View File

@ -1,12 +1,18 @@
language: go
go:
- 1.6
- 1.7
- tip
ggo:
- "1.7"
- "1.8"
- "1.9"
- "1.10.x"
- "tip"
env:
- "PATH=/home/travis/gopath/bin:$PATH"
install:
- go get -v -t .
script:
- go get -u github.com/golang/lint/golint
- golint ./...

View File

@ -10,7 +10,7 @@ type AlertEvent struct {
EntityID int `json:"entity_id,omitempty"`
Priority string `json:"priority,omitempty"`
Description string `json:"description,omitempty"`
Timestamp int `json:"timestamp,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
IncidentID int `json:"incident_id"`
}

View File

@ -129,6 +129,7 @@ var brokenAuthHeaderProviders = []string{
"https://log.finalsurge.com/oauth/token",
"https://multisport.todaysplan.com.au/rest/oauth/access_token",
"https://whats.todaysplan.com.au/rest/oauth/access_token",
"https://stackoverflow.com/oauth/access_token",
}
// brokenAuthHeaderDomains lists broken providers that issue dynamic endpoints.

10
vendor/golang.org/x/oauth2/oauth2.go generated vendored
View File

@ -124,6 +124,8 @@ func SetAuthURLParam(key, value string) AuthCodeOption {
//
// Opts may include AccessTypeOnline or AccessTypeOffline, as well
// as ApprovalForce.
// It can also be used to pass the PKCE challange.
// See https://www.oauth.com/oauth2-servers/pkce/ for more info.
func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
var buf bytes.Buffer
buf.WriteString(c.Endpoint.AuthURL)
@ -186,7 +188,10 @@ func (c *Config) PasswordCredentialsToken(ctx context.Context, username, passwor
//
// The code will be in the *http.Request.FormValue("code"). Before
// calling Exchange, be sure to validate FormValue("state").
func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) {
//
// Opts may include the PKCE verifier code if previously used in AuthCodeURL.
// See https://www.oauth.com/oauth2-servers/pkce/ for more info.
func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error) {
v := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
@ -194,6 +199,9 @@ func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) {
if c.RedirectURL != "" {
v.Set("redirect_uri", c.RedirectURL)
}
for _, opt := range opts {
opt.setValue(v)
}
return retrieveToken(ctx, c, v)
}

3
wtf.go
View File

@ -21,6 +21,7 @@ import (
"github.com/senorprogrammer/wtf/cryptoexchanges/cryptolive"
"github.com/senorprogrammer/wtf/flags"
"github.com/senorprogrammer/wtf/gcal"
"github.com/senorprogrammer/wtf/gerrit"
"github.com/senorprogrammer/wtf/git"
"github.com/senorprogrammer/wtf/github"
"github.com/senorprogrammer/wtf/gitlab"
@ -179,6 +180,8 @@ func addWidget(app *tview.Application, pages *tview.Pages, widgetName string) {
Widgets = append(Widgets, cryptolive.NewWidget())
case "gcal":
Widgets = append(Widgets, gcal.NewWidget())
case "gerrit":
Widgets = append(Widgets, gerrit.NewWidget(app, pages))
case "git":
Widgets = append(Widgets, git.NewWidget(app, pages))
case "github":