Compare commits

...
Sign in to create a new pull request.

33 commits

Author SHA1 Message Date
Gabriel
26dfb7ab79
Merge pull request #465 from gabriel-samfira/fix-typo
Fix typo
2025-07-20 21:14:11 +03:00
Gabriel Adrian Samfira
87a13e377c Fix typo
Copy-paste typo.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-07-20 18:13:24 +00:00
Gabriel
0e2a12a44c
Merge pull request #464 from gabriel-samfira/bump-versions
Bump provider versions
2025-07-20 19:26:33 +03:00
Gabriel Adrian Samfira
e6919e36a5 Bump provider versions
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-07-20 16:18:13 +00:00
Gabriel
50d2546055
Merge pull request #461 from gabriel-samfira/update-docs
Update docs to reflect new release
2025-07-20 04:06:53 +03:00
Gabriel Adrian Samfira
03aa14c912 Update docs to reflect new release
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-07-20 01:05:27 +00:00
Gabriel
d2babb767d
Merge pull request #460 from gabriel-samfira/update-dependencies
Update dependencies
2025-07-20 03:40:57 +03:00
Gabriel Adrian Samfira
5addd8d50a Update dependencies
Update all dependencies.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-07-20 00:35:38 +00:00
Gabriel
d83b4ff9cf
Merge pull request #439 from gabriel-samfira/set-transport-options
Set http transport config
2025-06-27 11:17:47 +03:00
Gabriel Adrian Samfira
9279fb66cf Set http transport config
This change sets the github client http transport options to mirror those
of the default transport from Go, with the addition of the TLSClientConfig.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-06-27 07:31:43 +00:00
Gabriel
ace965daa0
Merge pull request #435 from gabriel-samfira/fixes
Fix show webhooks.
2025-06-20 01:08:14 +03:00
Gabriel Adrian Samfira
e07befbea5 Fix show webhooks.
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-06-19 21:53:09 +00:00
Gabriel
77b3ec3cdd
Merge pull request #434 from gabriel-samfira/update-deps
Update dependencies.
2025-06-19 23:49:51 +03:00
Gabriel Adrian Samfira
584bd73553 Update dependencies.
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-06-19 20:40:34 +00:00
Gabriel
a4e13f957f
Merge pull request #415 from gabriel-samfira/add-write-lock
Add write lock for sqlite3
2025-05-29 20:30:41 +03:00
Gabriel Adrian Samfira
ef3402bf17 Add write lock for sqlite3
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-29 17:22:14 +00:00
Gabriel
f925a7e66d
Merge pull request #420 from gabriel-samfira/enable-tests
Trigger tests on release branches
2025-05-29 20:22:00 +03:00
Gabriel Adrian Samfira
913388ed3b Trigger tests on release branches
This change triggers tests for PRs created against release/* branches.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-29 17:16:48 +00:00
Gabriel
14b253b9ce
Merge pull request #414 from gabriel-samfira/relax-validation
Relax update endpoint validation
2025-05-26 18:17:34 +03:00
Gabriel Adrian Samfira
4c9f78f81b Relax update endpoint validation
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-26 15:09:21 +00:00
Gabriel
7651671377
Merge pull request #410 from gabriel-samfira/make-default-ep-mutable
Make the default github.com endpoint mutable
2025-05-24 16:47:25 +03:00
Gabriel Adrian Samfira
750446acec Make the default github.com endpoint mutable
The k8s operator seems to want to define its own endpoint. This change
allows the removal of the default gh endpoint if no credentials are tied
to it.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-24 13:35:17 +00:00
Gabriel
1e0cb72aa3
Merge pull request #409 from gabriel-samfira/fix-backoff-logic
Fix deadline check logic
2025-05-23 15:44:40 +03:00
Gabriel Adrian Samfira
9f3b651184 Fix deadline check logic
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-23 12:40:57 +00:00
Gabriel Adrian Samfira
99ba233da7 Merge commit 'cc1470fe08' into release/v0.1 2025-05-23 12:32:20 +00:00
Gabriel Adrian Samfira
c31ae7868c Merge branch 'up-main' into release/v0.1 2024-08-08 12:34:34 +00:00
Gabriel Adrian Samfira
747604ebfa Merge branch 'up-main' into release/v0.1 2024-02-12 19:17:10 +00:00
Gabriel Adrian Samfira
c44f02c90f Merge branch 'up-main' into release/v0.1 2024-02-12 15:36:59 +00:00
Gabriel Adrian Samfira
50f691e67e Merge remote-tracking branch 'upstream/main' into release/v0.1 2023-12-18 17:16:41 +00:00
Gabriel Adrian Samfira
d2fb5e3955
Merge branch 'main' into release/v0.1 2023-07-25 22:25:17 +03:00
Gabriel Adrian Samfira
a0a561155a
Merge branch 'main' into release/v0.1 2023-07-06 09:15:01 +03:00
Gabriel Adrian Samfira
481ce343bc
Merge branch 'main' into release/v0.1 2023-06-16 17:36:40 +03:00
Gabriel Adrian Samfira
31b3d07dcf
properly set version
Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2023-06-11 15:18:57 +03:00
556 changed files with 19124 additions and 62523 deletions

View file

@ -4,9 +4,11 @@ on:
push: push:
branches: branches:
- main - main
- 'release/**'
pull_request: pull_request:
branches: branches:
- main - main
- 'release/**'
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }} group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }}

View file

@ -1,5 +1,14 @@
FROM docker.io/golang:alpine AS builder FROM docker.io/golang:alpine AS builder
ARG GARM_REF ARG GARM_REF
ARG AZURE_REF=v0.1.2
ARG OPENSTACK_REF=v0.1.2
ARG LXD_REF=v0.1.2
ARG INCUS_REF=v0.1.2
ARG AWS_REF=v0.1.3
ARG GCP_REF=v0.1.2
ARG EQUINIX_REF=v0.1.2
ARG K8S_REF=v0.3.2
ARG LINODE_REF=v0.2.0
LABEL stage=builder LABEL stage=builder
@ -8,13 +17,14 @@ RUN git config --global --add safe.directory /build
ADD . /build/garm ADD . /build/garm
RUN cd /build/garm && git checkout ${GARM_REF} RUN cd /build/garm && git checkout ${GARM_REF}
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-azure /build/garm-provider-azure RUN git clone --depth 1 --branch ${AZURE_REF} https://github.com/cloudbase/garm-provider-azure /build/garm-provider-azure
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-openstack /build/garm-provider-openstack RUN git clone --depth 1 --branch ${OPENSTACK_REF} https://github.com/cloudbase/garm-provider-openstack /build/garm-provider-openstack
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-lxd /build/garm-provider-lxd RUN git clone --depth 1 --branch ${LXD_REF} https://github.com/cloudbase/garm-provider-lxd /build/garm-provider-lxd
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-incus /build/garm-provider-incus RUN git clone --depth 1 --branch ${INCUS_REF} https://github.com/cloudbase/garm-provider-incus /build/garm-provider-incus
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-aws /build/garm-provider-aws RUN git clone --depth 1 --branch ${AWS_REF} https://github.com/cloudbase/garm-provider-aws /build/garm-provider-aws
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-gcp /build/garm-provider-gcp RUN git clone --depth 1 --branch ${GCP_REF} https://github.com/cloudbase/garm-provider-gcp /build/garm-provider-gcp
RUN git clone --depth 1 --branch v0.1.0 https://github.com/cloudbase/garm-provider-equinix /build/garm-provider-equinix RUN git clone --depth 1 --branch ${EQUINIX_REF} https://github.com/cloudbase/garm-provider-equinix /build/garm-provider-equinix
RUN git clone --depth 1 --branch ${LINODE_REF} https://github.com/flatcar/garm-provider-linode /build/garm-provider-linode
RUN git clone --depth 1 --branch v0.3.1 https://github.com/mercedes-benz/garm-provider-k8s /build/garm-provider-k8s RUN git clone --depth 1 --branch v0.3.1 https://github.com/mercedes-benz/garm-provider-k8s /build/garm-provider-k8s
@ -23,13 +33,14 @@ RUN cd /build/garm && go build -o /bin/garm \
-ldflags "-linkmode external -extldflags '-static' -s -w -X github.com/cloudbase/garm/util/appdefaults.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" \ -ldflags "-linkmode external -extldflags '-static' -s -w -X github.com/cloudbase/garm/util/appdefaults.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" \
/build/garm/cmd/garm && upx /bin/garm /build/garm/cmd/garm && upx /bin/garm
RUN mkdir -p /opt/garm/providers.d RUN mkdir -p /opt/garm/providers.d
RUN cd /build/garm-provider-azure && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-azure . && upx /opt/garm/providers.d/garm-provider-azure RUN cd /build/garm-provider-azure && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${AZURE_REF}" -o /opt/garm/providers.d/garm-provider-azure . && upx /opt/garm/providers.d/garm-provider-azure
RUN cd /build/garm-provider-openstack && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-openstack . && upx /opt/garm/providers.d/garm-provider-openstack RUN cd /build/garm-provider-openstack && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${OPENSTACK_REF}" -o /opt/garm/providers.d/garm-provider-openstack . && upx /opt/garm/providers.d/garm-provider-openstack
RUN cd /build/garm-provider-lxd && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-lxd . && upx /opt/garm/providers.d/garm-provider-lxd RUN cd /build/garm-provider-lxd && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${LXD_REF}" -o /opt/garm/providers.d/garm-provider-lxd . && upx /opt/garm/providers.d/garm-provider-lxd
RUN cd /build/garm-provider-incus && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-incus . && upx /opt/garm/providers.d/garm-provider-incus RUN cd /build/garm-provider-incus && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${INCUS_REF}" -o /opt/garm/providers.d/garm-provider-incus . && upx /opt/garm/providers.d/garm-provider-incus
RUN cd /build/garm-provider-aws && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-aws . && upx /opt/garm/providers.d/garm-provider-aws RUN cd /build/garm-provider-aws && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${AWS_REF}" -o /opt/garm/providers.d/garm-provider-aws . && upx /opt/garm/providers.d/garm-provider-aws
RUN cd /build/garm-provider-gcp && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-gcp . && upx /opt/garm/providers.d/garm-provider-gcp RUN cd /build/garm-provider-gcp && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${GCP_REF}" -o /opt/garm/providers.d/garm-provider-gcp . && upx /opt/garm/providers.d/garm-provider-gcp
RUN cd /build/garm-provider-equinix && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=v0.1.0" -o /opt/garm/providers.d/garm-provider-equinix . && upx /opt/garm/providers.d/garm-provider-equinix RUN cd /build/garm-provider-equinix && go build -ldflags="-linkmode external -extldflags '-static' -s -w -X main.Version=${EQUINIX_REF}" -o /opt/garm/providers.d/garm-provider-equinix . && upx /opt/garm/providers.d/garm-provider-equinix
RUN cd /build/garm-provider-linode && go build -ldflags="-linkmode external -extldflags '-static' -s -w" -o /opt/garm/providers.d/garm-provider-linode . && upx /opt/garm/providers.d/garm-provider-linode
RUN cd /build/garm-provider-k8s/cmd/garm-provider-k8s && go build -ldflags="-linkmode external -extldflags '-static' -s -w" -o /opt/garm/providers.d/garm-provider-k8s . && upx /opt/garm/providers.d/garm-provider-k8s RUN cd /build/garm-provider-k8s/cmd/garm-provider-k8s && go build -ldflags="-linkmode external -extldflags '-static' -s -w" -o /opt/garm/providers.d/garm-provider-k8s . && upx /opt/garm/providers.d/garm-provider-k8s
@ -43,6 +54,7 @@ COPY --from=builder /opt/garm/providers.d/garm-provider-azure /opt/garm/provider
COPY --from=builder /opt/garm/providers.d/garm-provider-aws /opt/garm/providers.d/garm-provider-aws COPY --from=builder /opt/garm/providers.d/garm-provider-aws /opt/garm/providers.d/garm-provider-aws
COPY --from=builder /opt/garm/providers.d/garm-provider-gcp /opt/garm/providers.d/garm-provider-gcp COPY --from=builder /opt/garm/providers.d/garm-provider-gcp /opt/garm/providers.d/garm-provider-gcp
COPY --from=builder /opt/garm/providers.d/garm-provider-equinix /opt/garm/providers.d/garm-provider-equinix COPY --from=builder /opt/garm/providers.d/garm-provider-equinix /opt/garm/providers.d/garm-provider-equinix
COPY --from=builder /opt/garm/providers.d/garm-provider-linode /opt/garm/providers.d/garm-provider-linode
COPY --from=builder /opt/garm/providers.d/garm-provider-k8s /opt/garm/providers.d/garm-provider-k8s COPY --from=builder /opt/garm/providers.d/garm-provider-k8s /opt/garm/providers.d/garm-provider-k8s
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

View file

@ -67,7 +67,7 @@ lint-fix: golangci-lint $(GOLANGCI_LINT) ## Lint the codebase and run auto-fixer
verify-vendor: ## verify if all the go.mod/go.sum files are up-to-date verify-vendor: ## verify if all the go.mod/go.sum files are up-to-date
$(eval TMPDIR := $(shell mktemp -d)) $(eval TMPDIR := $(shell mktemp -d))
@cp -R ${ROOTDIR} ${TMPDIR} @cp -R ${ROOTDIR} ${TMPDIR}/.
@(cd ${TMPDIR}/garm && ${GO} mod tidy) @(cd ${TMPDIR}/garm && ${GO} mod tidy)
@diff -r -u -q ${ROOTDIR} ${TMPDIR}/garm >/dev/null 2>&1; if [ "$$?" -ne 0 ];then echo "please run: go mod tidy && go mod vendor"; exit 1; fi @diff -r -u -q ${ROOTDIR} ${TMPDIR}/garm >/dev/null 2>&1; if [ "$$?" -ne 0 ];then echo "please run: go mod tidy && go mod vendor"; exit 1; fi
@rm -rf ${TMPDIR} @rm -rf ${TMPDIR}
@ -106,7 +106,7 @@ $(LOCALBIN):
GOLANGCI_LINT ?= $(LOCALBIN)/golangci-lint GOLANGCI_LINT ?= $(LOCALBIN)/golangci-lint
## Tool Versions ## Tool Versions
GOLANGCI_LINT_VERSION ?= v1.61.0 GOLANGCI_LINT_VERSION ?= v1.64.8
.PHONY: golangci-lint .PHONY: golangci-lint
golangci-lint: $(GOLANGCI_LINT) ## Download golangci-lint locally if necessary. If wrong version is installed, it will be overwritten. golangci-lint: $(GOLANGCI_LINT) ## Download golangci-lint locally if necessary. If wrong version is installed, it will be overwritten.

View file

@ -1,19 +1,18 @@
# GitHub Actions Runner Manager (GARM) # GitHub Actions Runner Manager (GARM)
[![Go Tests](https://github.com/cloudbase/garm/actions/workflows/go-tests.yml/badge.svg)](https://github.com/cloudbase/garm/actions/workflows/go-tests.yml)
<!-- TOC --> <!-- TOC -->
- [About GARM](#about-garm) - [GitHub Actions Runner Manager GARM](#github-actions-runner-manager-garm)
- [Join us on slack](#join-us-on-slack) - [About GARM](#about-garm)
- [Installing](#installing) - [Join us on slack](#join-us-on-slack)
- [Quickstart](#quickstart) - [Installing](#installing)
- [Installing on Kubernetes](#installing-on-kubernetes) - [Quickstart](#quickstart)
- [Using GARM](#using-garm) - [Installing on Kubernetes](#installing-on-kubernetes)
- [Supported providers](#supported-providers) - [Using GARM](#using-garm)
- [Installing external providers](#installing-external-providers) - [Supported providers](#supported-providers)
- [Optimizing your runners](#optimizing-your-runners) - [Installing external providers](#installing-external-providers)
- [Write your own provider](#write-your-own-provider) - [Optimizing your runners](#optimizing-your-runners)
- [Write your own provider](#write-your-own-provider)
<!-- /TOC --> <!-- /TOC -->
@ -34,7 +33,7 @@ Here is a brief architectural diagram of how GARM reacts to workflows triggered
![GARM architecture diagram](/doc/images/garm-light.drawio.svg?raw=true#gh-light-mode-only) ![GARM architecture diagram](/doc/images/garm-light.drawio.svg?raw=true#gh-light-mode-only)
![GARM architecture diagram](/doc/images/garm-dark.drawio.svg?raw=true#gh-dark-mode-only) ![GARM architecture diagram](/doc/images/garm-dark.drawio.svg?raw=true#gh-dark-mode-only)
:warning: **Important note**: The README and documentation in the `main` branch are relevant to the not yet released code that is present in `main`. Following the documentation from the `main` branch for a stable release of GARM, may lead to errors. To view the documentation for the latest stable release, please switch to the appropriate tag. For information about setting up `v0.1.5`, please refer to the [v0.1.5 tag](https://github.com/cloudbase/garm/tree/v0.1.5). :warning: **Important note**: The README and documentation in the `main` branch are relevant to the not yet released code that is present in `main`. Following the documentation from the `main` branch for a stable release of GARM, may lead to errors. To view the documentation for the latest stable release, please switch to the appropriate tag. For information about setting up `v0.1.6`, please refer to the [v0.1.6 tag](https://github.com/cloudbase/garm/tree/v0.1.6).
## Join us on slack ## Join us on slack

View file

@ -1,4 +1,4 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
@ -50,7 +50,7 @@ func (_m *Store) BreakLockJobIsQueued(ctx context.Context, jobID int64) error {
return r0 return r0
} }
// ControllerInfo provides a mock function with given fields: // ControllerInfo provides a mock function with no fields
func (_m *Store) ControllerInfo() (params.ControllerInfo, error) { func (_m *Store) ControllerInfo() (params.ControllerInfo, error) {
ret := _m.Called() ret := _m.Called()
@ -1034,7 +1034,7 @@ func (_m *Store) HasAdminUser(ctx context.Context) bool {
return r0 return r0
} }
// InitController provides a mock function with given fields: // InitController provides a mock function with no fields
func (_m *Store) InitController() (params.ControllerInfo, error) { func (_m *Store) InitController() (params.ControllerInfo, error) {
ret := _m.Called() ret := _m.Called()

View file

@ -63,6 +63,9 @@ func (s *sqlDatabase) ControllerInfo() (params.ControllerInfo, error) {
} }
func (s *sqlDatabase) InitController() (params.ControllerInfo, error) { func (s *sqlDatabase) InitController() (params.ControllerInfo, error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
if _, err := s.ControllerInfo(); err == nil { if _, err := s.ControllerInfo(); err == nil {
return params.ControllerInfo{}, runnerErrors.NewConflictError("controller already initialized") return params.ControllerInfo{}, runnerErrors.NewConflictError("controller already initialized")
} }
@ -88,6 +91,9 @@ func (s *sqlDatabase) InitController() (params.ControllerInfo, error) {
} }
func (s *sqlDatabase) UpdateController(info params.UpdateControllerParams) (paramInfo params.ControllerInfo, err error) { func (s *sqlDatabase) UpdateController(info params.UpdateControllerParams) (paramInfo params.ControllerInfo, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.ControllerEntityType, common.UpdateOperation, paramInfo) s.sendNotify(common.ControllerEntityType, common.UpdateOperation, paramInfo)

View file

@ -29,6 +29,9 @@ import (
) )
func (s *sqlDatabase) CreateEnterprise(ctx context.Context, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (paramEnt params.Enterprise, err error) { func (s *sqlDatabase) CreateEnterprise(ctx context.Context, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (paramEnt params.Enterprise, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
if webhookSecret == "" { if webhookSecret == "" {
return params.Enterprise{}, errors.New("creating enterprise: missing secret") return params.Enterprise{}, errors.New("creating enterprise: missing secret")
} }
@ -132,6 +135,9 @@ func (s *sqlDatabase) ListEnterprises(_ context.Context) ([]params.Enterprise, e
} }
func (s *sqlDatabase) DeleteEnterprise(ctx context.Context, enterpriseID string) error { func (s *sqlDatabase) DeleteEnterprise(ctx context.Context, enterpriseID string) error {
s.writeMux.Lock()
defer s.writeMux.Unlock()
enterprise, err := s.getEnterpriseByID(ctx, s.conn, enterpriseID, "Endpoint", "Credentials", "Credentials.Endpoint") enterprise, err := s.getEnterpriseByID(ctx, s.conn, enterpriseID, "Endpoint", "Credentials", "Credentials.Endpoint")
if err != nil { if err != nil {
return errors.Wrap(err, "fetching enterprise") return errors.Wrap(err, "fetching enterprise")
@ -157,6 +163,9 @@ func (s *sqlDatabase) DeleteEnterprise(ctx context.Context, enterpriseID string)
} }
func (s *sqlDatabase) UpdateEnterprise(ctx context.Context, enterpriseID string, param params.UpdateEntityParams) (newParams params.Enterprise, err error) { func (s *sqlDatabase) UpdateEnterprise(ctx context.Context, enterpriseID string, param params.UpdateEntityParams) (newParams params.Enterprise, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.EnterpriseEntityType, common.UpdateOperation, newParams) s.sendNotify(common.EnterpriseEntityType, common.UpdateOperation, newParams)

View file

@ -28,10 +28,6 @@ import (
"github.com/cloudbase/garm/params" "github.com/cloudbase/garm/params"
) )
const (
defaultGithubEndpoint string = "github.com"
)
func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (params.GithubCredentials, error) { func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (params.GithubCredentials, error) {
if len(creds.Payload) == 0 { if len(creds.Payload) == 0 {
return params.GithubCredentials{}, errors.New("empty credentials payload") return params.GithubCredentials{}, errors.New("empty credentials payload")
@ -115,6 +111,9 @@ func getUIDFromContext(ctx context.Context) (uuid.UUID, error) {
} }
func (s *sqlDatabase) CreateGithubEndpoint(_ context.Context, param params.CreateGithubEndpointParams) (ghEndpoint params.GithubEndpoint, err error) { func (s *sqlDatabase) CreateGithubEndpoint(_ context.Context, param params.CreateGithubEndpointParams) (ghEndpoint params.GithubEndpoint, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.GithubEndpointEntityType, common.CreateOperation, ghEndpoint) s.sendNotify(common.GithubEndpointEntityType, common.CreateOperation, ghEndpoint)
@ -168,9 +167,8 @@ func (s *sqlDatabase) ListGithubEndpoints(_ context.Context) ([]params.GithubEnd
} }
func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param params.UpdateGithubEndpointParams) (ghEndpoint params.GithubEndpoint, err error) { func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param params.UpdateGithubEndpointParams) (ghEndpoint params.GithubEndpoint, err error) {
if name == defaultGithubEndpoint { s.writeMux.Lock()
return params.GithubEndpoint{}, errors.Wrap(runnerErrors.ErrBadRequest, "cannot update default github endpoint") defer s.writeMux.Unlock()
}
defer func() { defer func() {
if err == nil { if err == nil {
@ -185,6 +183,7 @@ func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param
} }
return errors.Wrap(err, "fetching github endpoint") return errors.Wrap(err, "fetching github endpoint")
} }
if param.APIBaseURL != nil { if param.APIBaseURL != nil {
endpoint.APIBaseURL = *param.APIBaseURL endpoint.APIBaseURL = *param.APIBaseURL
} }
@ -236,9 +235,8 @@ func (s *sqlDatabase) GetGithubEndpoint(_ context.Context, name string) (params.
} }
func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err error) { func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err error) {
if name == defaultGithubEndpoint { s.writeMux.Lock()
return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete default github endpoint") defer s.writeMux.Unlock()
}
defer func() { defer func() {
if err == nil { if err == nil {
@ -283,7 +281,7 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err
} }
if credsCount > 0 || repoCnt > 0 || orgCnt > 0 || entCnt > 0 { if credsCount > 0 || repoCnt > 0 || orgCnt > 0 || entCnt > 0 {
return errors.New("cannot delete endpoint with associated entities") return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete endpoint with associated entities")
} }
if err := tx.Unscoped().Delete(&endpoint).Error; err != nil { if err := tx.Unscoped().Delete(&endpoint).Error; err != nil {
@ -298,6 +296,9 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err
} }
func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) { func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
userID, err := getUIDFromContext(ctx) userID, err := getUIDFromContext(ctx)
if err != nil { if err != nil {
return params.GithubCredentials{}, errors.Wrap(err, "creating github credentials") return params.GithubCredentials{}, errors.Wrap(err, "creating github credentials")
@ -461,6 +462,9 @@ func (s *sqlDatabase) ListGithubCredentials(ctx context.Context) ([]params.Githu
} }
func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) { func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.GithubCredentialsEntityType, common.UpdateOperation, ghCreds) s.sendNotify(common.GithubCredentialsEntityType, common.UpdateOperation, ghCreds)
@ -540,6 +544,9 @@ func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, para
} }
func (s *sqlDatabase) DeleteGithubCredentials(ctx context.Context, id uint) (err error) { func (s *sqlDatabase) DeleteGithubCredentials(ctx context.Context, id uint) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
var name string var name string
defer func() { defer func() {
if err == nil { if err == nil {

View file

@ -40,6 +40,7 @@ const (
testEndpointDescription string = "test description" testEndpointDescription string = "test description"
testCredsName string = "test-creds" testCredsName string = "test-creds"
testCredsDescription string = "test creds" testCredsDescription string = "test creds"
defaultGithubEndpoint string = "github.com"
) )
type GithubTestSuite struct { type GithubTestSuite struct {
@ -56,20 +57,13 @@ func (s *GithubTestSuite) SetupTest() {
s.db = db s.db = db
} }
func (s *GithubTestSuite) TestDefaultEndpointGetsCreatedAutomatically() { func (s *GithubTestSuite) TestDefaultEndpointGetsCreatedAutomaticallyIfNoOtherEndpointExists() {
ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T()) ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T())
endpoint, err := s.db.GetGithubEndpoint(ctx, defaultGithubEndpoint) endpoint, err := s.db.GetGithubEndpoint(ctx, defaultGithubEndpoint)
s.Require().NoError(err) s.Require().NoError(err)
s.Require().NotNil(endpoint) s.Require().NotNil(endpoint)
} }
func (s *GithubTestSuite) TestDeletingDefaultEndpointFails() {
ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T())
err := s.db.DeleteGithubEndpoint(ctx, defaultGithubEndpoint)
s.Require().Error(err)
s.Require().ErrorIs(err, runnerErrors.ErrBadRequest)
}
func (s *GithubTestSuite) TestCreatingEndpoint() { func (s *GithubTestSuite) TestCreatingEndpoint() {
ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T()) ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T())
@ -153,6 +147,39 @@ func (s *GithubTestSuite) TestDeletingEndpoint() {
s.Require().ErrorIs(err, runnerErrors.ErrNotFound) s.Require().ErrorIs(err, runnerErrors.ErrNotFound)
} }
func (s *GithubTestSuite) TestDeleteGithubEndpointFailsWhenCredentialsExist() {
ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T())
createEpParams := params.CreateGithubEndpointParams{
Name: testEndpointName,
Description: testEndpointDescription,
APIBaseURL: testAPIBaseURL,
UploadBaseURL: testUploadBaseURL,
BaseURL: testBaseURL,
}
endpoint, err := s.db.CreateGithubEndpoint(ctx, createEpParams)
s.Require().NoError(err)
s.Require().NotNil(endpoint)
credParams := params.CreateGithubCredentialsParams{
Name: testCredsName,
Description: testCredsDescription,
Endpoint: testEndpointName,
AuthType: params.GithubAuthTypePAT,
PAT: params.GithubPAT{
OAuth2Token: "test",
},
}
_, err = s.db.CreateGithubCredentials(ctx, credParams)
s.Require().NoError(err)
err = s.db.DeleteGithubEndpoint(ctx, testEndpointName)
s.Require().Error(err)
s.Require().ErrorIs(err, runnerErrors.ErrBadRequest)
}
func (s *GithubTestSuite) TestUpdateEndpoint() { func (s *GithubTestSuite) TestUpdateEndpoint() {
ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T()) ctx := garmTesting.ImpersonateAdminContext(context.Background(), s.db, s.T())
@ -168,7 +195,7 @@ func (s *GithubTestSuite) TestUpdateEndpoint() {
s.Require().NoError(err) s.Require().NoError(err)
s.Require().NotNil(endpoint) s.Require().NotNil(endpoint)
newDescription := "new description" newDescription := "the new description"
newAPIBaseURL := "https://new-api.example.com" newAPIBaseURL := "https://new-api.example.com"
newUploadBaseURL := "https://new-uploads.example.com" newUploadBaseURL := "https://new-uploads.example.com"
newBaseURL := "https://new.example.com" newBaseURL := "https://new.example.com"

View file

@ -31,6 +31,9 @@ import (
) )
func (s *sqlDatabase) CreateInstance(_ context.Context, poolID string, param params.CreateInstanceParams) (instance params.Instance, err error) { func (s *sqlDatabase) CreateInstance(_ context.Context, poolID string, param params.CreateInstanceParams) (instance params.Instance, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
pool, err := s.getPoolByID(s.conn, poolID) pool, err := s.getPoolByID(s.conn, poolID)
if err != nil { if err != nil {
return params.Instance{}, errors.Wrap(err, "fetching pool") return params.Instance{}, errors.Wrap(err, "fetching pool")
@ -143,6 +146,9 @@ func (s *sqlDatabase) GetInstanceByName(ctx context.Context, instanceName string
} }
func (s *sqlDatabase) DeleteInstance(_ context.Context, poolID string, instanceName string) (err error) { func (s *sqlDatabase) DeleteInstance(_ context.Context, poolID string, instanceName string) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
instance, err := s.getPoolInstanceByName(poolID, instanceName) instance, err := s.getPoolInstanceByName(poolID, instanceName)
if err != nil { if err != nil {
return errors.Wrap(err, "deleting instance") return errors.Wrap(err, "deleting instance")
@ -176,6 +182,9 @@ func (s *sqlDatabase) DeleteInstance(_ context.Context, poolID string, instanceN
} }
func (s *sqlDatabase) AddInstanceEvent(ctx context.Context, instanceName string, event params.EventType, eventLevel params.EventLevel, statusMessage string) error { func (s *sqlDatabase) AddInstanceEvent(ctx context.Context, instanceName string, event params.EventType, eventLevel params.EventLevel, statusMessage string) error {
s.writeMux.Lock()
defer s.writeMux.Unlock()
instance, err := s.getInstanceByName(ctx, instanceName) instance, err := s.getInstanceByName(ctx, instanceName)
if err != nil { if err != nil {
return errors.Wrap(err, "updating instance") return errors.Wrap(err, "updating instance")
@ -194,6 +203,9 @@ func (s *sqlDatabase) AddInstanceEvent(ctx context.Context, instanceName string,
} }
func (s *sqlDatabase) UpdateInstance(ctx context.Context, instanceName string, param params.UpdateInstanceParams) (params.Instance, error) { func (s *sqlDatabase) UpdateInstance(ctx context.Context, instanceName string, param params.UpdateInstanceParams) (params.Instance, error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
instance, err := s.getInstanceByName(ctx, instanceName) instance, err := s.getInstanceByName(ctx, instanceName)
if err != nil { if err != nil {
return params.Instance{}, errors.Wrap(err, "updating instance") return params.Instance{}, errors.Wrap(err, "updating instance")

View file

@ -95,6 +95,9 @@ func (s *sqlDatabase) paramsJobToWorkflowJob(ctx context.Context, job params.Job
} }
func (s *sqlDatabase) DeleteJob(_ context.Context, jobID int64) (err error) { func (s *sqlDatabase) DeleteJob(_ context.Context, jobID int64) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
if notifyErr := s.sendNotify(common.JobEntityType, common.DeleteOperation, params.Job{ID: jobID}); notifyErr != nil { if notifyErr := s.sendNotify(common.JobEntityType, common.DeleteOperation, params.Job{ID: jobID}); notifyErr != nil {
@ -113,6 +116,9 @@ func (s *sqlDatabase) DeleteJob(_ context.Context, jobID int64) (err error) {
} }
func (s *sqlDatabase) LockJob(_ context.Context, jobID int64, entityID string) error { func (s *sqlDatabase) LockJob(_ context.Context, jobID int64, entityID string) error {
s.writeMux.Lock()
defer s.writeMux.Unlock()
entityUUID, err := uuid.Parse(entityID) entityUUID, err := uuid.Parse(entityID)
if err != nil { if err != nil {
return errors.Wrap(err, "parsing entity id") return errors.Wrap(err, "parsing entity id")
@ -152,6 +158,9 @@ func (s *sqlDatabase) LockJob(_ context.Context, jobID int64, entityID string) e
} }
func (s *sqlDatabase) BreakLockJobIsQueued(_ context.Context, jobID int64) (err error) { func (s *sqlDatabase) BreakLockJobIsQueued(_ context.Context, jobID int64) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
var workflowJob WorkflowJob var workflowJob WorkflowJob
q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Preload("Instance").Where("id = ? and status = ?", jobID, params.JobStatusQueued).First(&workflowJob) q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Preload("Instance").Where("id = ? and status = ?", jobID, params.JobStatusQueued).First(&workflowJob)
@ -180,6 +189,9 @@ func (s *sqlDatabase) BreakLockJobIsQueued(_ context.Context, jobID int64) (err
} }
func (s *sqlDatabase) UnlockJob(_ context.Context, jobID int64, entityID string) error { func (s *sqlDatabase) UnlockJob(_ context.Context, jobID int64, entityID string) error {
s.writeMux.Lock()
defer s.writeMux.Unlock()
var workflowJob WorkflowJob var workflowJob WorkflowJob
q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", jobID).First(&workflowJob) q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", jobID).First(&workflowJob)
@ -213,6 +225,9 @@ func (s *sqlDatabase) UnlockJob(_ context.Context, jobID int64, entityID string)
} }
func (s *sqlDatabase) CreateOrUpdateJob(ctx context.Context, job params.Job) (params.Job, error) { func (s *sqlDatabase) CreateOrUpdateJob(ctx context.Context, job params.Job) (params.Job, error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
var workflowJob WorkflowJob var workflowJob WorkflowJob
var err error var err error
q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Preload("Instance").Where("id = ?", job.ID).First(&workflowJob) q := s.conn.Clauses(clause.Locking{Strength: "UPDATE"}).Preload("Instance").Where("id = ?", job.ID).First(&workflowJob)
@ -381,6 +396,9 @@ func (s *sqlDatabase) GetJobByID(_ context.Context, jobID int64) (params.Job, er
// DeleteCompletedJobs deletes all completed jobs. // DeleteCompletedJobs deletes all completed jobs.
func (s *sqlDatabase) DeleteCompletedJobs(_ context.Context) error { func (s *sqlDatabase) DeleteCompletedJobs(_ context.Context) error {
s.writeMux.Lock()
defer s.writeMux.Unlock()
query := s.conn.Model(&WorkflowJob{}).Where("status = ?", params.JobStatusCompleted) query := s.conn.Model(&WorkflowJob{}).Where("status = ?", params.JobStatusCompleted)
if err := query.Unscoped().Delete(&WorkflowJob{}); err.Error != nil { if err := query.Unscoped().Delete(&WorkflowJob{}); err.Error != nil {

View file

@ -30,6 +30,9 @@ import (
) )
func (s *sqlDatabase) CreateOrganization(ctx context.Context, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (org params.Organization, err error) { func (s *sqlDatabase) CreateOrganization(ctx context.Context, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (org params.Organization, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
if webhookSecret == "" { if webhookSecret == "" {
return params.Organization{}, errors.New("creating org: missing secret") return params.Organization{}, errors.New("creating org: missing secret")
} }
@ -123,6 +126,9 @@ func (s *sqlDatabase) ListOrganizations(_ context.Context) ([]params.Organizatio
} }
func (s *sqlDatabase) DeleteOrganization(ctx context.Context, orgID string) (err error) { func (s *sqlDatabase) DeleteOrganization(ctx context.Context, orgID string) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
org, err := s.getOrgByID(ctx, s.conn, orgID, "Endpoint", "Credentials", "Credentials.Endpoint") org, err := s.getOrgByID(ctx, s.conn, orgID, "Endpoint", "Credentials", "Credentials.Endpoint")
if err != nil { if err != nil {
return errors.Wrap(err, "fetching org") return errors.Wrap(err, "fetching org")
@ -148,6 +154,9 @@ func (s *sqlDatabase) DeleteOrganization(ctx context.Context, orgID string) (err
} }
func (s *sqlDatabase) UpdateOrganization(ctx context.Context, orgID string, param params.UpdateEntityParams) (paramOrg params.Organization, err error) { func (s *sqlDatabase) UpdateOrganization(ctx context.Context, orgID string, param params.UpdateEntityParams) (paramOrg params.Organization, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.OrganizationEntityType, common.UpdateOperation, paramOrg) s.sendNotify(common.OrganizationEntityType, common.UpdateOperation, paramOrg)

View file

@ -68,6 +68,9 @@ func (s *sqlDatabase) GetPoolByID(_ context.Context, poolID string) (params.Pool
} }
func (s *sqlDatabase) DeletePoolByID(_ context.Context, poolID string) (err error) { func (s *sqlDatabase) DeletePoolByID(_ context.Context, poolID string) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
pool, err := s.getPoolByID(s.conn, poolID) pool, err := s.getPoolByID(s.conn, poolID)
if err != nil { if err != nil {
return errors.Wrap(err, "fetching pool by ID") return errors.Wrap(err, "fetching pool by ID")
@ -255,6 +258,9 @@ func (s *sqlDatabase) FindPoolsMatchingAllTags(_ context.Context, entityType par
} }
func (s *sqlDatabase) CreateEntityPool(_ context.Context, entity params.GithubEntity, param params.CreatePoolParams) (pool params.Pool, err error) { func (s *sqlDatabase) CreateEntityPool(_ context.Context, entity params.GithubEntity, param params.CreatePoolParams) (pool params.Pool, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
if len(param.Tags) == 0 { if len(param.Tags) == 0 {
return params.Pool{}, runnerErrors.NewBadRequestError("no tags specified") return params.Pool{}, runnerErrors.NewBadRequestError("no tags specified")
} }
@ -343,6 +349,9 @@ func (s *sqlDatabase) GetEntityPool(_ context.Context, entity params.GithubEntit
} }
func (s *sqlDatabase) DeleteEntityPool(_ context.Context, entity params.GithubEntity, poolID string) (err error) { func (s *sqlDatabase) DeleteEntityPool(_ context.Context, entity params.GithubEntity, poolID string) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
entityID, err := uuid.Parse(entity.ID) entityID, err := uuid.Parse(entity.ID)
if err != nil { if err != nil {
return errors.Wrap(runnerErrors.ErrBadRequest, "parsing id") return errors.Wrap(runnerErrors.ErrBadRequest, "parsing id")
@ -380,6 +389,9 @@ func (s *sqlDatabase) DeleteEntityPool(_ context.Context, entity params.GithubEn
} }
func (s *sqlDatabase) UpdateEntityPool(_ context.Context, entity params.GithubEntity, poolID string, param params.UpdatePoolParams) (updatedPool params.Pool, err error) { func (s *sqlDatabase) UpdateEntityPool(_ context.Context, entity params.GithubEntity, poolID string, param params.UpdatePoolParams) (updatedPool params.Pool, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.PoolEntityType, common.UpdateOperation, updatedPool) s.sendNotify(common.PoolEntityType, common.UpdateOperation, updatedPool)

View file

@ -30,6 +30,9 @@ import (
) )
func (s *sqlDatabase) CreateRepository(ctx context.Context, owner, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (param params.Repository, err error) { func (s *sqlDatabase) CreateRepository(ctx context.Context, owner, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (param params.Repository, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.RepositoryEntityType, common.CreateOperation, param) s.sendNotify(common.RepositoryEntityType, common.CreateOperation, param)
@ -122,6 +125,9 @@ func (s *sqlDatabase) ListRepositories(_ context.Context) ([]params.Repository,
} }
func (s *sqlDatabase) DeleteRepository(ctx context.Context, repoID string) (err error) { func (s *sqlDatabase) DeleteRepository(ctx context.Context, repoID string) (err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
repo, err := s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint") repo, err := s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint")
if err != nil { if err != nil {
return errors.Wrap(err, "fetching repo") return errors.Wrap(err, "fetching repo")
@ -147,6 +153,9 @@ func (s *sqlDatabase) DeleteRepository(ctx context.Context, repoID string) (err
} }
func (s *sqlDatabase) UpdateRepository(ctx context.Context, repoID string, param params.UpdateEntityParams) (newParams params.Repository, err error) { func (s *sqlDatabase) UpdateRepository(ctx context.Context, repoID string, param params.UpdateEntityParams) (newParams params.Repository, err error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
defer func() { defer func() {
if err == nil { if err == nil {
s.sendNotify(common.RepositoryEntityType, common.UpdateOperation, newParams) s.sendNotify(common.RepositoryEntityType, common.UpdateOperation, newParams)

View file

@ -20,6 +20,7 @@ import (
"log/slog" "log/slog"
"net/url" "net/url"
"strings" "strings"
"sync"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
@ -91,6 +92,11 @@ type sqlDatabase struct {
ctx context.Context ctx context.Context
cfg config.Database cfg config.Database
producer common.Producer producer common.Producer
// while busy_timeout helps, in situations of high contention, we can still
// end up with multiple threads trying to write to the database. SQLite does now
// support row level locking.
writeMux sync.Mutex
} }
var renameTemplate = ` var renameTemplate = `
@ -212,9 +218,18 @@ func (s *sqlDatabase) ensureGithubEndpoint() error {
UploadBaseURL: appdefaults.GithubDefaultUploadBaseURL, UploadBaseURL: appdefaults.GithubDefaultUploadBaseURL,
} }
if _, err := s.CreateGithubEndpoint(context.Background(), createEndpointParams); err != nil { var epCount int64
if !errors.Is(err, runnerErrors.ErrDuplicateEntity) { if err := s.conn.Model(&GithubEndpoint{}).Count(&epCount).Error; err != nil {
return errors.Wrap(err, "creating default github endpoint") if !errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrap(err, "counting github endpoints")
}
}
if epCount == 0 {
if _, err := s.CreateGithubEndpoint(context.Background(), createEndpointParams); err != nil {
if !errors.Is(err, runnerErrors.ErrDuplicateEntity) {
return errors.Wrap(err, "creating default github endpoint")
}
} }
} }

View file

@ -57,6 +57,9 @@ func (s *sqlDatabase) getUserByID(tx *gorm.DB, userID string) (User, error) {
} }
func (s *sqlDatabase) CreateUser(_ context.Context, user params.NewUserParams) (params.User, error) { func (s *sqlDatabase) CreateUser(_ context.Context, user params.NewUserParams) (params.User, error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
if user.Username == "" || user.Email == "" || user.Password == "" { if user.Username == "" || user.Email == "" || user.Password == "" {
return params.User{}, runnerErrors.NewBadRequestError("missing username, password or email") return params.User{}, runnerErrors.NewBadRequestError("missing username, password or email")
} }
@ -119,6 +122,9 @@ func (s *sqlDatabase) GetUserByID(_ context.Context, userID string) (params.User
} }
func (s *sqlDatabase) UpdateUser(_ context.Context, user string, param params.UpdateUserParams) (params.User, error) { func (s *sqlDatabase) UpdateUser(_ context.Context, user string, param params.UpdateUserParams) (params.User, error) {
s.writeMux.Lock()
defer s.writeMux.Unlock()
var err error var err error
var dbUser User var dbUser User
err = s.conn.Transaction(func(tx *gorm.DB) error { err = s.conn.Transaction(func(tx *gorm.DB) error {

View file

@ -2,18 +2,19 @@
<!-- TOC --> <!-- TOC -->
- [Create the config folder](#create-the-config-folder) - [Quick start](#quick-start)
- [The config file](#the-config-file) - [Create the config folder](#create-the-config-folder)
- [The provider section](#the-provider-section) - [The config file](#the-config-file)
- [Starting the service](#starting-the-service) - [The provider section](#the-provider-section)
- [Using Docker](#using-docker) - [Starting the service](#starting-the-service)
- [Setting up GARM as a system service](#setting-up-garm-as-a-system-service) - [Using Docker](#using-docker)
- [Initializing GARM](#initializing-garm) - [Setting up GARM as a system service](#setting-up-garm-as-a-system-service)
- [Setting up the webhook](#setting-up-the-webhook) - [Initializing GARM](#initializing-garm)
- [Creating a GitHub endpoint Optional](#creating-a-github-endpoint-optional) - [Setting up the webhook](#setting-up-the-webhook)
- [Adding credentials](#adding-credentials) - [Creating a GitHub endpoint Optional](#creating-a-github-endpoint-optional)
- [Define a repo](#define-a-repo) - [Adding credentials](#adding-credentials)
- [Create a pool](#create-a-pool) - [Define a repo](#define-a-repo)
- [Create a pool](#create-a-pool)
<!-- /TOC --> <!-- /TOC -->
@ -133,7 +134,7 @@ docker run -d \
-p 80:80 \ -p 80:80 \
-v /etc/garm:/etc/garm:rw \ -v /etc/garm:/etc/garm:rw \
-v /var/snap/lxd/common/lxd/unix.socket:/var/snap/lxd/common/lxd/unix.socket:rw \ -v /var/snap/lxd/common/lxd/unix.socket:/var/snap/lxd/common/lxd/unix.socket:rw \
ghcr.io/cloudbase/garm:v0.1.4 ghcr.io/cloudbase/garm:v0.1.6
``` ```
You will notice that we also mounted the LXD unix socket from the host inside the container where the config you pasted expects to find it. If you plan to use an external provider that does not need to connect to LXD over a unix socket, feel free to remove that mount. You will notice that we also mounted the LXD unix socket from the host inside the container where the config you pasted expects to find it. If you plan to use an external provider that does not need to connect to LXD over a unix socket, feel free to remove that mount.
@ -166,7 +167,7 @@ Adding the `garm` user to the LXD group will allow it to connect to the LXD unix
Next, download the latest release from the [releases page](https://github.com/cloudbase/garm/releases). Next, download the latest release from the [releases page](https://github.com/cloudbase/garm/releases).
```bash ```bash
wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.5/garm-linux-amd64.tgz | tar xzf - -C /usr/local/bin/ wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.6/garm-linux-amd64.tgz | tar xzf - -C /usr/local/bin/
``` ```
We'll be running under an unprivileged user. If we want to be able to listen on any port under `1024`, we'll have to set some capabilities on the binary: We'll be running under an unprivileged user. If we want to be able to listen on any port under `1024`, we'll have to set some capabilities on the binary:
@ -199,7 +200,7 @@ Copy the sample `systemd` service file:
```bash ```bash
wget -O /etc/systemd/system/garm.service \ wget -O /etc/systemd/system/garm.service \
https://raw.githubusercontent.com/cloudbase/garm/v0.1.5/contrib/garm.service https://raw.githubusercontent.com/cloudbase/garm/v0.1.6/contrib/garm.service
``` ```
Reload the `systemd` daemon and start the service: Reload the `systemd` daemon and start the service:
@ -234,7 +235,7 @@ Before we can start using GARM, we need initialize it. This will create the `adm
To initialize GARM, we'll use the `garm-cli` tool. You can download the latest release from the [releases page](https://github.com/cloudbase/garm/releases): To initialize GARM, we'll use the `garm-cli` tool. You can download the latest release from the [releases page](https://github.com/cloudbase/garm/releases):
```bash ```bash
wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.5/garm-cli-linux-amd64.tgz | tar xzf - -C /usr/local/bin/ wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.6/garm-cli-linux-amd64.tgz | tar xzf - -C /usr/local/bin/
``` ```
Now we can initialize GARM: Now we can initialize GARM:

View file

@ -66,7 +66,7 @@ garm-cli controller show
| Webhook Base URL | https://garm.example.com/webhooks | | Webhook Base URL | https://garm.example.com/webhooks |
| Controller Webhook URL | https://garm.example.com/webhooks/a4dd5f41-8e1e-42a7-af53-c0ba5ff6b0b3 | | Controller Webhook URL | https://garm.example.com/webhooks/a4dd5f41-8e1e-42a7-af53-c0ba5ff6b0b3 |
| Minimum Job Age Backoff | 30 | | Minimum Job Age Backoff | 30 |
| Version | v0.1.5 | | Version | v0.1.6 |
+-------------------------+----------------------------------------------------------------------------+ +-------------------------+----------------------------------------------------------------------------+
``` ```

47
go.mod
View file

@ -6,15 +6,15 @@ toolchain go1.23.6
require ( require (
github.com/BurntSushi/toml v1.5.0 github.com/BurntSushi/toml v1.5.0
github.com/bradleyfalzon/ghinstallation/v2 v2.15.0 github.com/bradleyfalzon/ghinstallation/v2 v2.16.0
github.com/cloudbase/garm-provider-common v0.1.4 github.com/cloudbase/garm-provider-common v0.1.6
github.com/felixge/httpsnoop v1.0.4 github.com/felixge/httpsnoop v1.0.4
github.com/go-openapi/errors v0.22.1 github.com/go-openapi/errors v0.22.1
github.com/go-openapi/runtime v0.28.0 github.com/go-openapi/runtime v0.28.0
github.com/go-openapi/strfmt v0.23.0 github.com/go-openapi/strfmt v0.23.0
github.com/go-openapi/swag v0.23.1 github.com/go-openapi/swag v0.23.1
github.com/golang-jwt/jwt/v5 v5.2.2 github.com/golang-jwt/jwt/v5 v5.2.3
github.com/google/go-github/v57 v57.0.0 github.com/google/go-github/v72 v72.0.0
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gorilla/handlers v1.5.2 github.com/gorilla/handlers v1.5.2
github.com/gorilla/mux v1.8.1 github.com/gorilla/mux v1.8.1
@ -28,15 +28,15 @@ require (
github.com/prometheus/client_golang v1.22.0 github.com/prometheus/client_golang v1.22.0
github.com/spf13/cobra v1.9.1 github.com/spf13/cobra v1.9.1
github.com/stretchr/testify v1.10.0 github.com/stretchr/testify v1.10.0
golang.org/x/crypto v0.37.0 golang.org/x/crypto v0.40.0
golang.org/x/oauth2 v0.29.0 golang.org/x/oauth2 v0.30.0
golang.org/x/sync v0.13.0 golang.org/x/sync v0.16.0
gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0 gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/datatypes v1.2.5 gorm.io/datatypes v1.2.6
gorm.io/driver/mysql v1.5.7 gorm.io/driver/mysql v1.6.0
gorm.io/driver/sqlite v1.5.7 gorm.io/driver/sqlite v1.6.0
gorm.io/gorm v1.25.12 gorm.io/gorm v1.30.0
) )
require ( require (
@ -46,7 +46,7 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chzyer/readline v1.5.1 // indirect github.com/chzyer/readline v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/analysis v0.23.0 // indirect github.com/go-openapi/analysis v0.23.0 // indirect
github.com/go-openapi/jsonpointer v0.21.1 // indirect github.com/go-openapi/jsonpointer v0.21.1 // indirect
@ -54,9 +54,8 @@ require (
github.com/go-openapi/loads v0.22.0 // indirect github.com/go-openapi/loads v0.22.0 // indirect
github.com/go-openapi/spec v0.21.0 // indirect github.com/go-openapi/spec v0.21.0 // indirect
github.com/go-openapi/validate v0.24.0 // indirect github.com/go-openapi/validate v0.24.0 // indirect
github.com/go-sql-driver/mysql v1.9.2 // indirect github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/google/go-github/v71 v71.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect github.com/google/go-querystring v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
@ -76,20 +75,20 @@ require (
github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.63.0 // indirect github.com/prometheus/common v0.65.0 // indirect
github.com/prometheus/procfs v0.16.0 // indirect github.com/prometheus/procfs v0.17.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.6 // indirect github.com/spf13/pflag v1.0.7 // indirect
github.com/stretchr/objx v0.5.2 // indirect github.com/stretchr/objx v0.5.2 // indirect
github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 // indirect github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 // indirect
go.mongodb.org/mongo-driver v1.17.3 // indirect go.mongodb.org/mongo-driver v1.17.4 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel v1.35.0 // indirect go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect go.opentelemetry.io/otel/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect go.opentelemetry.io/otel/trace v1.37.0 // indirect
golang.org/x/net v0.39.0 // indirect golang.org/x/net v0.42.0 // indirect
golang.org/x/sys v0.32.0 // indirect golang.org/x/sys v0.34.0 // indirect
golang.org/x/text v0.24.0 // indirect golang.org/x/text v0.27.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

99
go.sum
View file

@ -6,8 +6,8 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bradleyfalzon/ghinstallation/v2 v2.15.0 h1:7r2rPUM04rgszMP0U1UZ1M5VoVVIlsaBSnpABfYxcQY= github.com/bradleyfalzon/ghinstallation/v2 v2.16.0 h1:B91r9bHtXp/+XRgS5aZm6ZzTdz3ahgJYmkt4xZkgDz8=
github.com/bradleyfalzon/ghinstallation/v2 v2.15.0/go.mod h1:PoH9Vhy82OeRFZfxsVrk3mfQhVkEzou9OOwPOsEhiXE= github.com/bradleyfalzon/ghinstallation/v2 v2.16.0/go.mod h1:OeVe5ggFzoBnmgitZe/A+BqGOnv1DvU/0uiLQi1wutM=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
@ -19,8 +19,8 @@ github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObk
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/cloudbase/garm-provider-common v0.1.4 h1:spRjl0PV4r8vKaCTNp6xBQbRKfls/cmbBEl/i/eGWSo= github.com/cloudbase/garm-provider-common v0.1.6 h1:wLqolRkUD2Z4rzuBLDs2exL1Aq+eJ5RBVnRvk5JP6fs=
github.com/cloudbase/garm-provider-common v0.1.4/go.mod h1:sK26i2NpjjAjhanNKiWw8iPkqt+XeohTKpFnEP7JdZ4= github.com/cloudbase/garm-provider-common v0.1.6/go.mod h1:2O51WbcfqRx5fDHyyJgIFq7KdTZZnefsM+aoOchyleU=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@ -28,8 +28,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU=
@ -52,13 +52,12 @@ github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZ
github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0= github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0=
github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58=
github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.3 h1:kkGXqQOBSDDWRhWNXTFpqGSCMyh/PLnqUvMGJPDJDs0=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-jwt/jwt/v5 v5.2.3/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
@ -66,10 +65,8 @@ github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EO
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-github/v57 v57.0.0 h1:L+Y3UPTY8ALM8x+TV0lg+IEBI+upibemtBD8Q9u7zHs= github.com/google/go-github/v72 v72.0.0 h1:FcIO37BLoVPBO9igQQ6tStsv2asG4IPcYFi655PPvBM=
github.com/google/go-github/v57 v57.0.0/go.mod h1:s0omdnye0hvK/ecLvpsGfJMiRt85PimQh4oygmLIxHw= github.com/google/go-github/v72 v72.0.0/go.mod h1:WWtw8GMRiL62mvIquf1kO3onRHeWWKmK01qdCY8c5fg=
github.com/google/go-github/v71 v71.0.0 h1:Zi16OymGKZZMm8ZliffVVJ/Q9YZreDKONCr+WUd0Z30=
github.com/google/go-github/v71 v71.0.0/go.mod h1:URZXObp2BLlMjwu0O8g4y6VBneUj2bCHgnI8FfgZ51M=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@ -155,10 +152,10 @@ github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k= github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18= github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
github.com/prometheus/procfs v0.16.0 h1:xh6oHhKwnOJKMYiYBDWmkHqQPyiY40sny36Cmx2bbsM= github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
github.com/prometheus/procfs v0.16.0/go.mod h1:8veyXUu3nGP7oaCxhX6yeaM5u4stL2FeMXnCqhDthZg= github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
@ -167,8 +164,9 @@ github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWN
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
@ -178,33 +176,33 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 h1:xzABM9let0HLLqFypcxvLmlvEciCHL7+Lv+4vwZqecI= github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 h1:xzABM9let0HLLqFypcxvLmlvEciCHL7+Lv+4vwZqecI=
github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569/go.mod h1:2Ly+NIftZN4de9zRmENdYbvPQeaVIYKWpLFStLFEBgI= github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569/go.mod h1:2Ly+NIftZN4de9zRmENdYbvPQeaVIYKWpLFStLFEBgI=
go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ= go.mongodb.org/mongo-driver v1.17.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw=
go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.mongodb.org/mongo-driver v1.17.4/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw= go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw=
go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg= go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg=
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/oauth2 v0.29.0 h1:WdYw2tdTK1S8olAzWHdgeqfy+Mtm9XNhv/xJsY65d98= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.29.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
@ -220,16 +218,15 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/datatypes v1.2.5 h1:9UogU3jkydFVW1bIVVeoYsTpLRgwDVW3rHfJG6/Ek9I= gorm.io/datatypes v1.2.6 h1:KafLdXvFUhzNeL2ncm03Gl3eTLONQfNKZ+wJ+9Y4Nck=
gorm.io/datatypes v1.2.5/go.mod h1:I5FUdlKpLb5PMqeMQhm30CQ6jXP8Rj89xkTeCSAaAD4= gorm.io/datatypes v1.2.6/go.mod h1:M2iO+6S3hhi4nAyYe444Pcb0dcIiOMJ7QHaUXxyiNZY=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
gorm.io/driver/postgres v1.5.0 h1:u2FXTy14l45qc3UeCJ7QaAXZmZfDDv0YrthvmRq1l0U= gorm.io/driver/postgres v1.5.0 h1:u2FXTy14l45qc3UeCJ7QaAXZmZfDDv0YrthvmRq1l0U=
gorm.io/driver/postgres v1.5.0/go.mod h1:FUZXzO+5Uqg5zzwzv4KK49R8lvGIyscBOqYrtI1Ce9A= gorm.io/driver/postgres v1.5.0/go.mod h1:FUZXzO+5Uqg5zzwzv4KK49R8lvGIyscBOqYrtI1Ce9A=
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I= gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/driver/sqlserver v1.5.4 h1:xA+Y1KDNspv79q43bPyjDMUgHoYHLhXYmdFcYPobg8g= gorm.io/driver/sqlserver v1.6.0 h1:VZOBQVsVhkHU/NzNhRJKoANt5pZGQAS1Bwc6m6dgfnc=
gorm.io/driver/sqlserver v1.5.4/go.mod h1:+frZ/qYmuna11zHPlh5oc2O6ZA/lS88Keb0XSH1Zh/g= gorm.io/driver/sqlserver v1.6.0/go.mod h1:WQzt4IJo/WHKnckU9jXBLMJIVNMVeTu25dnOzehntWw=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=

View file

@ -22,11 +22,12 @@ import (
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"net"
"net/http" "net/http"
"time" "time"
"github.com/bradleyfalzon/ghinstallation/v2" "github.com/bradleyfalzon/ghinstallation/v2"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/oauth2" "golang.org/x/oauth2"
@ -642,11 +643,22 @@ func (g GithubCredentials) GetHTTPClient(ctx context.Context) (*http.Client, err
} }
} }
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
httpTransport := &http.Transport{ httpTransport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
TLSClientConfig: &tls.Config{ TLSClientConfig: &tls.Config{
RootCAs: roots, RootCAs: roots,
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
}, },
ForceAttemptHTTP2: true,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
} }
var tc *http.Client var tc *http.Client

View file

@ -1,11 +1,11 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
import ( import (
context "context" context "context"
github "github.com/google/go-github/v57/github" github "github.com/google/go-github/v72/github"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
params "github.com/cloudbase/garm/params" params "github.com/cloudbase/garm/params"
@ -302,7 +302,7 @@ func (_m *GithubClient) ListEntityRunnerApplicationDownloads(ctx context.Context
} }
// ListEntityRunners provides a mock function with given fields: ctx, opts // ListEntityRunners provides a mock function with given fields: ctx, opts
func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) { func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error) {
ret := _m.Called(ctx, opts) ret := _m.Called(ctx, opts)
if len(ret) == 0 { if len(ret) == 0 {
@ -312,10 +312,10 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List
var r0 *github.Runners var r0 *github.Runners
var r1 *github.Response var r1 *github.Response
var r2 error var r2 error
if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) (*github.Runners, *github.Response, error)); ok { if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) (*github.Runners, *github.Response, error)); ok {
return rf(ctx, opts) return rf(ctx, opts)
} }
if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) *github.Runners); ok { if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) *github.Runners); ok {
r0 = rf(ctx, opts) r0 = rf(ctx, opts)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
@ -323,7 +323,7 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List
} }
} }
if rf, ok := ret.Get(1).(func(context.Context, *github.ListOptions) *github.Response); ok { if rf, ok := ret.Get(1).(func(context.Context, *github.ListRunnersOptions) *github.Response); ok {
r1 = rf(ctx, opts) r1 = rf(ctx, opts)
} else { } else {
if ret.Get(1) != nil { if ret.Get(1) != nil {
@ -331,7 +331,7 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List
} }
} }
if rf, ok := ret.Get(2).(func(context.Context, *github.ListOptions) error); ok { if rf, ok := ret.Get(2).(func(context.Context, *github.ListRunnersOptions) error); ok {
r2 = rf(ctx, opts) r2 = rf(ctx, opts)
} else { } else {
r2 = ret.Error(2) r2 = ret.Error(2)

View file

@ -5,7 +5,7 @@ package mocks
import ( import (
context "context" context "context"
github "github.com/google/go-github/v57/github" github "github.com/google/go-github/v72/github"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
) )

View file

@ -1,11 +1,11 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
import ( import (
context "context" context "context"
github "github.com/google/go-github/v57/github" github "github.com/google/go-github/v72/github"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
params "github.com/cloudbase/garm/params" params "github.com/cloudbase/garm/params"
@ -263,7 +263,7 @@ func (_m *GithubEntityOperations) ListEntityRunnerApplicationDownloads(ctx conte
} }
// ListEntityRunners provides a mock function with given fields: ctx, opts // ListEntityRunners provides a mock function with given fields: ctx, opts
func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) { func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error) {
ret := _m.Called(ctx, opts) ret := _m.Called(ctx, opts)
if len(ret) == 0 { if len(ret) == 0 {
@ -273,10 +273,10 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g
var r0 *github.Runners var r0 *github.Runners
var r1 *github.Response var r1 *github.Response
var r2 error var r2 error
if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) (*github.Runners, *github.Response, error)); ok { if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) (*github.Runners, *github.Response, error)); ok {
return rf(ctx, opts) return rf(ctx, opts)
} }
if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) *github.Runners); ok { if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) *github.Runners); ok {
r0 = rf(ctx, opts) r0 = rf(ctx, opts)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
@ -284,7 +284,7 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g
} }
} }
if rf, ok := ret.Get(1).(func(context.Context, *github.ListOptions) *github.Response); ok { if rf, ok := ret.Get(1).(func(context.Context, *github.ListRunnersOptions) *github.Response); ok {
r1 = rf(ctx, opts) r1 = rf(ctx, opts)
} else { } else {
if ret.Get(1) != nil { if ret.Get(1) != nil {
@ -292,7 +292,7 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g
} }
} }
if rf, ok := ret.Get(2).(func(context.Context, *github.ListOptions) error); ok { if rf, ok := ret.Get(2).(func(context.Context, *github.ListRunnersOptions) error); ok {
r2 = rf(ctx, opts) r2 = rf(ctx, opts)
} else { } else {
r2 = ret.Error(2) r2 = ret.Error(2)

View file

@ -5,7 +5,7 @@ package mocks
import ( import (
context "context" context "context"
github "github.com/google/go-github/v57/github" github "github.com/google/go-github/v72/github"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
) )

View file

@ -1,4 +1,4 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
@ -60,7 +60,7 @@ func (_m *PoolManager) GetWebhookInfo(ctx context.Context) (params.HookInfo, err
return r0, r1 return r0, r1
} }
// GithubRunnerRegistrationToken provides a mock function with given fields: // GithubRunnerRegistrationToken provides a mock function with no fields
func (_m *PoolManager) GithubRunnerRegistrationToken() (string, error) { func (_m *PoolManager) GithubRunnerRegistrationToken() (string, error) {
ret := _m.Called() ret := _m.Called()
@ -106,7 +106,7 @@ func (_m *PoolManager) HandleWorkflowJob(job params.WorkflowJob) error {
return r0 return r0
} }
// ID provides a mock function with given fields: // ID provides a mock function with no fields
func (_m *PoolManager) ID() string { func (_m *PoolManager) ID() string {
ret := _m.Called() ret := _m.Called()
@ -152,7 +152,7 @@ func (_m *PoolManager) InstallWebhook(ctx context.Context, param params.InstallW
return r0, r1 return r0, r1
} }
// RootCABundle provides a mock function with given fields: // RootCABundle provides a mock function with no fields
func (_m *PoolManager) RootCABundle() (params.CertificateBundle, error) { func (_m *PoolManager) RootCABundle() (params.CertificateBundle, error) {
ret := _m.Called() ret := _m.Called()
@ -180,7 +180,7 @@ func (_m *PoolManager) RootCABundle() (params.CertificateBundle, error) {
return r0, r1 return r0, r1
} }
// Start provides a mock function with given fields: // Start provides a mock function with no fields
func (_m *PoolManager) Start() error { func (_m *PoolManager) Start() error {
ret := _m.Called() ret := _m.Called()
@ -198,7 +198,7 @@ func (_m *PoolManager) Start() error {
return r0 return r0
} }
// Status provides a mock function with given fields: // Status provides a mock function with no fields
func (_m *PoolManager) Status() params.PoolManagerStatus { func (_m *PoolManager) Status() params.PoolManagerStatus {
ret := _m.Called() ret := _m.Called()
@ -216,7 +216,7 @@ func (_m *PoolManager) Status() params.PoolManagerStatus {
return r0 return r0
} }
// Stop provides a mock function with given fields: // Stop provides a mock function with no fields
func (_m *PoolManager) Stop() error { func (_m *PoolManager) Stop() error {
ret := _m.Called() ret := _m.Called()
@ -252,7 +252,7 @@ func (_m *PoolManager) UninstallWebhook(ctx context.Context) error {
return r0 return r0
} }
// Wait provides a mock function with given fields: // Wait provides a mock function with no fields
func (_m *PoolManager) Wait() error { func (_m *PoolManager) Wait() error {
ret := _m.Called() ret := _m.Called()
@ -270,7 +270,7 @@ func (_m *PoolManager) Wait() error {
return r0 return r0
} }
// WebhookSecret provides a mock function with given fields: // WebhookSecret provides a mock function with no fields
func (_m *PoolManager) WebhookSecret() string { func (_m *PoolManager) WebhookSecret() string {
ret := _m.Called() ret := _m.Called()

View file

@ -1,15 +1,17 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
import ( import (
context "context" context "context"
common "github.com/cloudbase/garm/runner/common"
garm_provider_commonparams "github.com/cloudbase/garm-provider-common/params" garm_provider_commonparams "github.com/cloudbase/garm-provider-common/params"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
params "github.com/cloudbase/garm/params" params "github.com/cloudbase/garm/params"
"github.com/cloudbase/garm/runner/common"
) )
// Provider is an autogenerated mock type for the Provider type // Provider is an autogenerated mock type for the Provider type
@ -17,7 +19,7 @@ type Provider struct {
mock.Mock mock.Mock
} }
// AsParams provides a mock function with given fields: // AsParams provides a mock function with no fields
func (_m *Provider) AsParams() params.Provider { func (_m *Provider) AsParams() params.Provider {
ret := _m.Called() ret := _m.Called()
@ -35,9 +37,9 @@ func (_m *Provider) AsParams() params.Provider {
return r0 return r0
} }
// CreateInstance provides a mock function with given fields: ctx, bootstrapParams // CreateInstance provides a mock function with given fields: ctx, bootstrapParams, createInstanceParams
func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams garm_provider_commonparams.BootstrapInstance, createInstanceParams common.CreateInstanceParams) (garm_provider_commonparams.ProviderInstance, error) { func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams garm_provider_commonparams.BootstrapInstance, createInstanceParams common.CreateInstanceParams) (garm_provider_commonparams.ProviderInstance, error) {
ret := _m.Called(ctx, bootstrapParams) ret := _m.Called(ctx, bootstrapParams, createInstanceParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for CreateInstance") panic("no return value specified for CreateInstance")
@ -45,17 +47,17 @@ func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams garm_pro
var r0 garm_provider_commonparams.ProviderInstance var r0 garm_provider_commonparams.ProviderInstance
var r1 error var r1 error
if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance) (garm_provider_commonparams.ProviderInstance, error)); ok { if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance, common.CreateInstanceParams) (garm_provider_commonparams.ProviderInstance, error)); ok {
return rf(ctx, bootstrapParams) return rf(ctx, bootstrapParams, createInstanceParams)
} }
if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance) garm_provider_commonparams.ProviderInstance); ok { if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance, common.CreateInstanceParams) garm_provider_commonparams.ProviderInstance); ok {
r0 = rf(ctx, bootstrapParams) r0 = rf(ctx, bootstrapParams, createInstanceParams)
} else { } else {
r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance) r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance)
} }
if rf, ok := ret.Get(1).(func(context.Context, garm_provider_commonparams.BootstrapInstance) error); ok { if rf, ok := ret.Get(1).(func(context.Context, garm_provider_commonparams.BootstrapInstance, common.CreateInstanceParams) error); ok {
r1 = rf(ctx, bootstrapParams) r1 = rf(ctx, bootstrapParams, createInstanceParams)
} else { } else {
r1 = ret.Error(1) r1 = ret.Error(1)
} }
@ -63,17 +65,17 @@ func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams garm_pro
return r0, r1 return r0, r1
} }
// DeleteInstance provides a mock function with given fields: ctx, instance // DeleteInstance provides a mock function with given fields: ctx, instance, deleteInstanceParams
func (_m *Provider) DeleteInstance(ctx context.Context, instance string, deleteInstanceParams common.DeleteInstanceParams) error { func (_m *Provider) DeleteInstance(ctx context.Context, instance string, deleteInstanceParams common.DeleteInstanceParams) error {
ret := _m.Called(ctx, instance) ret := _m.Called(ctx, instance, deleteInstanceParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for DeleteInstance") panic("no return value specified for DeleteInstance")
} }
var r0 error var r0 error
if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.DeleteInstanceParams) error); ok {
r0 = rf(ctx, instance) r0 = rf(ctx, instance, deleteInstanceParams)
} else { } else {
r0 = ret.Error(0) r0 = ret.Error(0)
} }
@ -81,7 +83,7 @@ func (_m *Provider) DeleteInstance(ctx context.Context, instance string, deleteI
return r0 return r0
} }
// DisableJITConfig provides a mock function with given fields: // DisableJITConfig provides a mock function with no fields
func (_m *Provider) DisableJITConfig() bool { func (_m *Provider) DisableJITConfig() bool {
ret := _m.Called() ret := _m.Called()
@ -99,9 +101,9 @@ func (_m *Provider) DisableJITConfig() bool {
return r0 return r0
} }
// GetInstance provides a mock function with given fields: ctx, instance // GetInstance provides a mock function with given fields: ctx, instance, getInstanceParams
func (_m *Provider) GetInstance(ctx context.Context, instance string, getInstanceParams common.GetInstanceParams) (garm_provider_commonparams.ProviderInstance, error) { func (_m *Provider) GetInstance(ctx context.Context, instance string, getInstanceParams common.GetInstanceParams) (garm_provider_commonparams.ProviderInstance, error) {
ret := _m.Called(ctx, instance) ret := _m.Called(ctx, instance, getInstanceParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for GetInstance") panic("no return value specified for GetInstance")
@ -109,17 +111,17 @@ func (_m *Provider) GetInstance(ctx context.Context, instance string, getInstanc
var r0 garm_provider_commonparams.ProviderInstance var r0 garm_provider_commonparams.ProviderInstance
var r1 error var r1 error
if rf, ok := ret.Get(0).(func(context.Context, string) (garm_provider_commonparams.ProviderInstance, error)); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.GetInstanceParams) (garm_provider_commonparams.ProviderInstance, error)); ok {
return rf(ctx, instance) return rf(ctx, instance, getInstanceParams)
} }
if rf, ok := ret.Get(0).(func(context.Context, string) garm_provider_commonparams.ProviderInstance); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.GetInstanceParams) garm_provider_commonparams.ProviderInstance); ok {
r0 = rf(ctx, instance) r0 = rf(ctx, instance, getInstanceParams)
} else { } else {
r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance) r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance)
} }
if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { if rf, ok := ret.Get(1).(func(context.Context, string, common.GetInstanceParams) error); ok {
r1 = rf(ctx, instance) r1 = rf(ctx, instance, getInstanceParams)
} else { } else {
r1 = ret.Error(1) r1 = ret.Error(1)
} }
@ -127,9 +129,9 @@ func (_m *Provider) GetInstance(ctx context.Context, instance string, getInstanc
return r0, r1 return r0, r1
} }
// ListInstances provides a mock function with given fields: ctx, poolID // ListInstances provides a mock function with given fields: ctx, poolID, listInstancesParams
func (_m *Provider) ListInstances(ctx context.Context, poolID string, listInstancesParams common.ListInstancesParams) ([]garm_provider_commonparams.ProviderInstance, error) { func (_m *Provider) ListInstances(ctx context.Context, poolID string, listInstancesParams common.ListInstancesParams) ([]garm_provider_commonparams.ProviderInstance, error) {
ret := _m.Called(ctx, poolID) ret := _m.Called(ctx, poolID, listInstancesParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for ListInstances") panic("no return value specified for ListInstances")
@ -137,19 +139,19 @@ func (_m *Provider) ListInstances(ctx context.Context, poolID string, listInstan
var r0 []garm_provider_commonparams.ProviderInstance var r0 []garm_provider_commonparams.ProviderInstance
var r1 error var r1 error
if rf, ok := ret.Get(0).(func(context.Context, string) ([]garm_provider_commonparams.ProviderInstance, error)); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.ListInstancesParams) ([]garm_provider_commonparams.ProviderInstance, error)); ok {
return rf(ctx, poolID) return rf(ctx, poolID, listInstancesParams)
} }
if rf, ok := ret.Get(0).(func(context.Context, string) []garm_provider_commonparams.ProviderInstance); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.ListInstancesParams) []garm_provider_commonparams.ProviderInstance); ok {
r0 = rf(ctx, poolID) r0 = rf(ctx, poolID, listInstancesParams)
} else { } else {
if ret.Get(0) != nil { if ret.Get(0) != nil {
r0 = ret.Get(0).([]garm_provider_commonparams.ProviderInstance) r0 = ret.Get(0).([]garm_provider_commonparams.ProviderInstance)
} }
} }
if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { if rf, ok := ret.Get(1).(func(context.Context, string, common.ListInstancesParams) error); ok {
r1 = rf(ctx, poolID) r1 = rf(ctx, poolID, listInstancesParams)
} else { } else {
r1 = ret.Error(1) r1 = ret.Error(1)
} }
@ -157,17 +159,17 @@ func (_m *Provider) ListInstances(ctx context.Context, poolID string, listInstan
return r0, r1 return r0, r1
} }
// RemoveAllInstances provides a mock function with given fields: ctx // RemoveAllInstances provides a mock function with given fields: ctx, removeAllInstancesParams
func (_m *Provider) RemoveAllInstances(ctx context.Context, removeAllInstances common.RemoveAllInstancesParams) error { func (_m *Provider) RemoveAllInstances(ctx context.Context, removeAllInstancesParams common.RemoveAllInstancesParams) error {
ret := _m.Called(ctx) ret := _m.Called(ctx, removeAllInstancesParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for RemoveAllInstances") panic("no return value specified for RemoveAllInstances")
} }
var r0 error var r0 error
if rf, ok := ret.Get(0).(func(context.Context) error); ok { if rf, ok := ret.Get(0).(func(context.Context, common.RemoveAllInstancesParams) error); ok {
r0 = rf(ctx) r0 = rf(ctx, removeAllInstancesParams)
} else { } else {
r0 = ret.Error(0) r0 = ret.Error(0)
} }
@ -175,17 +177,17 @@ func (_m *Provider) RemoveAllInstances(ctx context.Context, removeAllInstances c
return r0 return r0
} }
// Start provides a mock function with given fields: ctx, instance // Start provides a mock function with given fields: ctx, instance, startParams
func (_m *Provider) Start(ctx context.Context, instance string, startParams common.StartParams) error { func (_m *Provider) Start(ctx context.Context, instance string, startParams common.StartParams) error {
ret := _m.Called(ctx, instance) ret := _m.Called(ctx, instance, startParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for Start") panic("no return value specified for Start")
} }
var r0 error var r0 error
if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.StartParams) error); ok {
r0 = rf(ctx, instance) r0 = rf(ctx, instance, startParams)
} else { } else {
r0 = ret.Error(0) r0 = ret.Error(0)
} }
@ -193,17 +195,17 @@ func (_m *Provider) Start(ctx context.Context, instance string, startParams comm
return r0 return r0
} }
// Stop provides a mock function with given fields: ctx, instance // Stop provides a mock function with given fields: ctx, instance, stopParams
func (_m *Provider) Stop(ctx context.Context, instance string, stopParams common.StopParams) error { func (_m *Provider) Stop(ctx context.Context, instance string, stopParams common.StopParams) error {
ret := _m.Called(ctx, instance) ret := _m.Called(ctx, instance, stopParams)
if len(ret) == 0 { if len(ret) == 0 {
panic("no return value specified for Stop") panic("no return value specified for Stop")
} }
var r0 error var r0 error
if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { if rf, ok := ret.Get(0).(func(context.Context, string, common.StopParams) error); ok {
r0 = rf(ctx, instance) r0 = rf(ctx, instance, stopParams)
} else { } else {
r0 = ret.Error(0) r0 = ret.Error(0)
} }

View file

@ -5,7 +5,7 @@ package mocks
import ( import (
context "context" context "context"
github "github.com/google/go-github/v57/github" github "github.com/google/go-github/v72/github"
mock "github.com/stretchr/testify/mock" mock "github.com/stretchr/testify/mock"
) )

View file

@ -3,7 +3,7 @@ package common
import ( import (
"context" "context"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/cloudbase/garm/params" "github.com/cloudbase/garm/params"
) )
@ -14,7 +14,7 @@ type GithubEntityOperations interface {
CreateEntityHook(ctx context.Context, hook *github.Hook) (ret *github.Hook, err error) CreateEntityHook(ctx context.Context, hook *github.Hook) (ret *github.Hook, err error)
DeleteEntityHook(ctx context.Context, id int64) (ret *github.Response, err error) DeleteEntityHook(ctx context.Context, id int64) (ret *github.Response, err error)
PingEntityHook(ctx context.Context, id int64) (ret *github.Response, err error) PingEntityHook(ctx context.Context, id int64) (ret *github.Response, err error)
ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error)
ListEntityRunnerApplicationDownloads(ctx context.Context) ([]*github.RunnerApplicationDownload, *github.Response, error) ListEntityRunnerApplicationDownloads(ctx context.Context) ([]*github.RunnerApplicationDownload, *github.Response, error)
RemoveEntityRunner(ctx context.Context, runnerID int64) (*github.Response, error) RemoveEntityRunner(ctx context.Context, runnerID int64) (*github.Response, error)
CreateEntityRegistrationToken(ctx context.Context) (*github.RegistrationToken, *github.Response, error) CreateEntityRegistrationToken(ctx context.Context) (*github.RegistrationToken, *github.Response, error)

View file

@ -1,4 +1,4 @@
// Code generated by mockery v2.42.0. DO NOT EDIT. // Code generated by mockery v2.53.3. DO NOT EDIT.
package mocks package mocks
@ -193,7 +193,7 @@ func (_m *PoolManagerController) GetEnterprisePoolManager(enterprise params.Ente
return r0, r1 return r0, r1
} }
// GetEnterprisePoolManagers provides a mock function with given fields: // GetEnterprisePoolManagers provides a mock function with no fields
func (_m *PoolManagerController) GetEnterprisePoolManagers() (map[string]common.PoolManager, error) { func (_m *PoolManagerController) GetEnterprisePoolManagers() (map[string]common.PoolManager, error) {
ret := _m.Called() ret := _m.Called()
@ -253,7 +253,7 @@ func (_m *PoolManagerController) GetOrgPoolManager(org params.Organization) (com
return r0, r1 return r0, r1
} }
// GetOrgPoolManagers provides a mock function with given fields: // GetOrgPoolManagers provides a mock function with no fields
func (_m *PoolManagerController) GetOrgPoolManagers() (map[string]common.PoolManager, error) { func (_m *PoolManagerController) GetOrgPoolManagers() (map[string]common.PoolManager, error) {
ret := _m.Called() ret := _m.Called()
@ -313,7 +313,7 @@ func (_m *PoolManagerController) GetRepoPoolManager(repo params.Repository) (com
return r0, r1 return r0, r1
} }
// GetRepoPoolManagers provides a mock function with given fields: // GetRepoPoolManagers provides a mock function with no fields
func (_m *PoolManagerController) GetRepoPoolManagers() (map[string]common.PoolManager, error) { func (_m *PoolManagerController) GetRepoPoolManagers() (map[string]common.PoolManager, error) {
ret := _m.Called() ret := _m.Called()

View file

@ -6,7 +6,7 @@ import (
"net/url" "net/url"
"strings" "strings"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/pkg/errors" "github.com/pkg/errors"
runnerErrors "github.com/cloudbase/garm-provider-common/errors" runnerErrors "github.com/cloudbase/garm-provider-common/errors"
@ -21,16 +21,12 @@ func validateHookRequest(controllerID, baseURL string, allHooks []*github.Hook,
partialMatches := []string{} partialMatches := []string{}
for _, hook := range allHooks { for _, hook := range allHooks {
hookURL, ok := hook.Config["url"].(string) hookURL := strings.ToLower(hook.GetURL())
if !ok {
continue
}
hookURL = strings.ToLower(hookURL)
if hook.Config["url"] == req.Config["url"] { if hook.GetURL() == req.GetURL() {
return runnerErrors.NewConflictError("hook already installed") return runnerErrors.NewConflictError("hook already installed")
} else if strings.Contains(hookURL, controllerID) || strings.Contains(hookURL, parsed.Hostname()) { } else if strings.Contains(hookURL, controllerID) || strings.Contains(hookURL, parsed.Hostname()) {
partialMatches = append(partialMatches, hook.Config["url"].(string)) partialMatches = append(partialMatches, hook.GetURL())
} }
} }
@ -42,18 +38,12 @@ func validateHookRequest(controllerID, baseURL string, allHooks []*github.Hook,
} }
func hookToParamsHookInfo(hook *github.Hook) params.HookInfo { func hookToParamsHookInfo(hook *github.Hook) params.HookInfo {
var hookURL string
url, ok := hook.Config["url"]
if ok {
hookURL = url.(string)
}
var insecureSSL bool var insecureSSL bool
insecureSSLConfig, ok := hook.Config["insecure_ssl"] var hookURL string
if ok { config := hook.GetConfig()
if insecureSSLConfig.(string) == "1" { if config != nil {
insecureSSL = true insecureSSL = config.GetInsecureSSL() == "1"
} hookURL = config.GetURL()
} }
return params.HookInfo{ return params.HookInfo{

View file

@ -63,7 +63,7 @@ func (i *instanceDeleteBackoff) ShouldProcess(key string) (bool, time.Time) {
now := time.Now().UTC() now := time.Now().UTC()
deadline := ib.lastRecordedFailureTime.Add(time.Duration(ib.backoffSeconds) * time.Second) deadline := ib.lastRecordedFailureTime.Add(time.Duration(ib.backoffSeconds) * time.Second)
return deadline.After(now), deadline return now.After(deadline), deadline
} }
func (i *instanceDeleteBackoff) Delete(key string) { func (i *instanceDeleteBackoff) Delete(key string) {

View file

@ -27,7 +27,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
@ -1931,12 +1931,12 @@ func (r *basePoolManager) InstallWebhook(ctx context.Context, param params.Insta
insecureSSL = "1" insecureSSL = "1"
} }
req := &github.Hook{ req := &github.Hook{
Active: github.Bool(true), Active: github.Ptr(true),
Config: map[string]interface{}{ Config: &github.HookConfig{
"url": r.controllerInfo.ControllerWebhookURL, URL: github.Ptr(r.controllerInfo.ControllerWebhookURL),
"content_type": "json", ContentType: github.Ptr("json"),
"insecure_ssl": insecureSSL, InsecureSSL: github.Ptr(insecureSSL),
"secret": r.WebhookSecret(), Secret: github.Ptr(r.WebhookSecret()),
}, },
Events: []string{ Events: []string{
"workflow_job", "workflow_job",
@ -1998,8 +1998,10 @@ func (r *basePoolManager) FetchTools() ([]commonParams.RunnerApplicationDownload
} }
func (r *basePoolManager) GetGithubRunners() ([]*github.Runner, error) { func (r *basePoolManager) GetGithubRunners() ([]*github.Runner, error) {
opts := github.ListOptions{ opts := github.ListRunnersOptions{
PerPage: 100, ListOptions: github.ListOptions{
PerPage: 100,
},
} }
var allRunners []*github.Runner var allRunners []*github.Runner

View file

@ -3,7 +3,7 @@ package pool
import ( import (
"context" "context"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/cloudbase/garm/params" "github.com/cloudbase/garm/params"
) )
@ -32,7 +32,7 @@ func (s *stubGithubClient) PingEntityHook(_ context.Context, _ int64) (*github.R
return nil, s.err return nil, s.err
} }
func (s *stubGithubClient) ListEntityRunners(_ context.Context, _ *github.ListOptions) (*github.Runners, *github.Response, error) { func (s *stubGithubClient) ListEntityRunners(_ context.Context, _ *github.ListRunnersOptions) (*github.Runners, *github.Response, error) {
return nil, nil, s.err return nil, nil, s.err
} }

View file

@ -6,7 +6,7 @@ import (
"sync" "sync"
"sync/atomic" "sync/atomic"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
runnerErrors "github.com/cloudbase/garm-provider-common/errors" runnerErrors "github.com/cloudbase/garm-provider-common/errors"
commonParams "github.com/cloudbase/garm-provider-common/params" commonParams "github.com/cloudbase/garm-provider-common/params"

View file

@ -6,7 +6,7 @@ import (
"log/slog" "log/slog"
"os" "os"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
@ -141,8 +141,8 @@ func getGhOrgWebhook(url, ghToken, orgName string) (*github.Hook, error) {
} }
for _, hook := range ghOrgHooks { for _, hook := range ghOrgHooks {
hookURL, ok := hook.Config["url"].(string) hookURL := hook.GetURL()
if ok && hookURL == url { if hookURL == url {
return hook, nil return hook, nil
} }
} }
@ -158,8 +158,8 @@ func getGhRepoWebhook(url, ghToken, orgName, repoName string) (*github.Hook, err
} }
for _, hook := range ghRepoHooks { for _, hook := range ghRepoHooks {
hookURL, ok := hook.Config["url"].(string) hookURL := hook.GetURL()
if ok && hookURL == url { if hookURL == url {
return hook, nil return hook, nil
} }
} }

View file

@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
commonParams "github.com/cloudbase/garm-provider-common/params" commonParams "github.com/cloudbase/garm-provider-common/params"
"github.com/cloudbase/garm/params" "github.com/cloudbase/garm/params"

View file

@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
commonParams "github.com/cloudbase/garm-provider-common/params" commonParams "github.com/cloudbase/garm-provider-common/params"
"github.com/cloudbase/garm/params" "github.com/cloudbase/garm/params"
@ -57,7 +57,7 @@ func (suite *GarmSuite) CreateOrg(orgName, credentialsName, orgWebhookSecret str
WebhookSecret: orgWebhookSecret, WebhookSecret: orgWebhookSecret,
} }
org, err := createOrg(suite.cli, suite.authToken, orgParams) org, err := createOrg(suite.cli, suite.authToken, orgParams)
suite.NoError(err, "error creating organization") suite.Require().NoError(err, "error creating organization")
return org return org
} }
@ -68,7 +68,7 @@ func (suite *GarmSuite) UpdateOrg(id, credentialsName string) *params.Organizati
CredentialsName: credentialsName, CredentialsName: credentialsName,
} }
org, err := updateOrg(suite.cli, suite.authToken, id, updateParams) org, err := updateOrg(suite.cli, suite.authToken, id, updateParams)
suite.NoError(err, "error updating organization") suite.Require().NoError(err, "error updating organization")
return org return org
} }
@ -79,15 +79,15 @@ func (suite *GarmSuite) InstallOrgWebhook(id string) *params.HookInfo {
WebhookEndpointType: params.WebhookEndpointDirect, WebhookEndpointType: params.WebhookEndpointDirect,
} }
_, err := installOrgWebhook(suite.cli, suite.authToken, id, webhookParams) _, err := installOrgWebhook(suite.cli, suite.authToken, id, webhookParams)
suite.NoError(err, "error installing organization webhook") suite.Require().NoError(err, "error installing organization webhook")
webhookInfo, err := getOrgWebhook(suite.cli, suite.authToken, id) webhookInfo, err := getOrgWebhook(suite.cli, suite.authToken, id)
suite.NoError(err, "error getting organization webhook") suite.Require().NoError(err, "error getting organization webhook")
return webhookInfo return webhookInfo
} }
func (suite *GarmSuite) ValidateOrgWebhookInstalled(ghToken, url, orgName string) { func (suite *GarmSuite) ValidateOrgWebhookInstalled(ghToken, url, orgName string) {
hook, err := getGhOrgWebhook(url, ghToken, orgName) hook, err := getGhOrgWebhook(url, ghToken, orgName)
suite.NoError(err, "error getting github webhook") suite.Require().NoError(err, "error getting github webhook")
suite.NotNil(hook, "github webhook with url %s, for org %s was not properly installed", url, orgName) suite.NotNil(hook, "github webhook with url %s, for org %s was not properly installed", url, orgName)
} }
@ -99,8 +99,8 @@ func getGhOrgWebhook(url, ghToken, orgName string) (*github.Hook, error) {
} }
for _, hook := range ghOrgHooks { for _, hook := range ghOrgHooks {
hookURL, ok := hook.Config["url"].(string) hookURL := hook.Config.GetURL()
if ok && hookURL == url { if hookURL == url {
return hook, nil return hook, nil
} }
} }
@ -112,12 +112,12 @@ func (suite *GarmSuite) UninstallOrgWebhook(id string) {
t := suite.T() t := suite.T()
t.Logf("Uninstall org webhook with org_id %s", id) t.Logf("Uninstall org webhook with org_id %s", id)
err := uninstallOrgWebhook(suite.cli, suite.authToken, id) err := uninstallOrgWebhook(suite.cli, suite.authToken, id)
suite.NoError(err, "error uninstalling organization webhook") suite.Require().NoError(err, "error uninstalling organization webhook")
} }
func (suite *GarmSuite) ValidateOrgWebhookUninstalled(ghToken, url, orgName string) { func (suite *GarmSuite) ValidateOrgWebhookUninstalled(ghToken, url, orgName string) {
hook, err := getGhOrgWebhook(url, ghToken, orgName) hook, err := getGhOrgWebhook(url, ghToken, orgName)
suite.NoError(err, "error getting github webhook") suite.Require().NoError(err, "error getting github webhook")
suite.Nil(hook, "github webhook with url %s, for org %s was not properly uninstalled", url, orgName) suite.Nil(hook, "github webhook with url %s, for org %s was not properly uninstalled", url, orgName)
} }
@ -125,7 +125,7 @@ func (suite *GarmSuite) CreateOrgPool(orgID string, poolParams params.CreatePool
t := suite.T() t := suite.T()
t.Logf("Create org pool with org_id %s", orgID) t.Logf("Create org pool with org_id %s", orgID)
pool, err := createOrgPool(suite.cli, suite.authToken, orgID, poolParams) pool, err := createOrgPool(suite.cli, suite.authToken, orgID, poolParams)
suite.NoError(err, "error creating organization pool") suite.Require().NoError(err, "error creating organization pool")
return pool return pool
} }
@ -133,7 +133,7 @@ func (suite *GarmSuite) GetOrgPool(orgID, orgPoolID string) *params.Pool {
t := suite.T() t := suite.T()
t.Logf("Get org pool with org_id %s and pool_id %s", orgID, orgPoolID) t.Logf("Get org pool with org_id %s and pool_id %s", orgID, orgPoolID)
pool, err := getOrgPool(suite.cli, suite.authToken, orgID, orgPoolID) pool, err := getOrgPool(suite.cli, suite.authToken, orgID, orgPoolID)
suite.NoError(err, "error getting organization pool") suite.Require().NoError(err, "error getting organization pool")
return pool return pool
} }
@ -141,7 +141,7 @@ func (suite *GarmSuite) DeleteOrgPool(orgID, orgPoolID string) {
t := suite.T() t := suite.T()
t.Logf("Delete org pool with org_id %s and pool_id %s", orgID, orgPoolID) t.Logf("Delete org pool with org_id %s and pool_id %s", orgID, orgPoolID)
err := deleteOrgPool(suite.cli, suite.authToken, orgID, orgPoolID) err := deleteOrgPool(suite.cli, suite.authToken, orgID, orgPoolID)
suite.NoError(err, "error deleting organization pool") suite.Require().NoError(err, "error deleting organization pool")
} }
func (suite *GarmSuite) UpdateOrgPool(orgID, orgPoolID string, maxRunners, minIdleRunners uint) *params.Pool { func (suite *GarmSuite) UpdateOrgPool(orgID, orgPoolID string, maxRunners, minIdleRunners uint) *params.Pool {
@ -152,14 +152,14 @@ func (suite *GarmSuite) UpdateOrgPool(orgID, orgPoolID string, maxRunners, minId
MaxRunners: &maxRunners, MaxRunners: &maxRunners,
} }
pool, err := updateOrgPool(suite.cli, suite.authToken, orgID, orgPoolID, poolParams) pool, err := updateOrgPool(suite.cli, suite.authToken, orgID, orgPoolID, poolParams)
suite.NoError(err, "error updating organization pool") suite.Require().NoError(err, "error updating organization pool")
return pool return pool
} }
func (suite *GarmSuite) WaitOrgRunningIdleInstances(orgID string, timeout time.Duration) { func (suite *GarmSuite) WaitOrgRunningIdleInstances(orgID string, timeout time.Duration) {
t := suite.T() t := suite.T()
orgPools, err := listOrgPools(suite.cli, suite.authToken, orgID) orgPools, err := listOrgPools(suite.cli, suite.authToken, orgID)
suite.NoError(err, "error listing organization pools") suite.Require().NoError(err, "error listing organization pools")
for _, pool := range orgPools { for _, pool := range orgPools {
err := suite.WaitPoolInstances(pool.ID, commonParams.InstanceRunning, params.RunnerIdle, timeout) err := suite.WaitPoolInstances(pool.ID, commonParams.InstanceRunning, params.RunnerIdle, timeout)
if err != nil { if err != nil {
@ -174,19 +174,19 @@ func (suite *GarmSuite) dumpOrgInstancesDetails(orgID string) {
// print org details // print org details
t.Logf("Dumping org details with org_id %s", orgID) t.Logf("Dumping org details with org_id %s", orgID)
org, err := getOrg(suite.cli, suite.authToken, orgID) org, err := getOrg(suite.cli, suite.authToken, orgID)
suite.NoError(err, "error getting organization") suite.Require().NoError(err, "error getting organization")
err = printJSONResponse(org) err = printJSONResponse(org)
suite.NoError(err, "error printing organization") suite.Require().NoError(err, "error printing organization")
// print org instances details // print org instances details
t.Logf("Dumping org instances details for org %s", orgID) t.Logf("Dumping org instances details for org %s", orgID)
instances, err := listOrgInstances(suite.cli, suite.authToken, orgID) instances, err := listOrgInstances(suite.cli, suite.authToken, orgID)
suite.NoError(err, "error listing organization instances") suite.Require().NoError(err, "error listing organization instances")
for _, instance := range instances { for _, instance := range instances {
instance, err := getInstance(suite.cli, suite.authToken, instance.Name) instance, err := getInstance(suite.cli, suite.authToken, instance.Name)
suite.NoError(err, "error getting instance") suite.Require().NoError(err, "error getting instance")
t.Logf("Instance info for instace %s", instance.Name) t.Logf("Instance info for instace %s", instance.Name)
err = printJSONResponse(instance) err = printJSONResponse(instance)
suite.NoError(err, "error printing instance") suite.Require().NoError(err, "error printing instance")
} }
} }

View file

@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"golang.org/x/oauth2" "golang.org/x/oauth2"
commonParams "github.com/cloudbase/garm-provider-common/params" commonParams "github.com/cloudbase/garm-provider-common/params"
@ -41,7 +41,7 @@ func (suite *GarmSuite) TestRepositories() {
CredentialsName: fmt.Sprintf("%s-clone", suite.credentialsName), CredentialsName: fmt.Sprintf("%s-clone", suite.credentialsName),
} }
repo, err := updateRepo(suite.cli, suite.authToken, suite.repo.ID, updateParams) repo, err := updateRepo(suite.cli, suite.authToken, suite.repo.ID, updateParams)
suite.NoError(err, "error updating repository") suite.Require().NoError(err, "error updating repository")
suite.Equal(fmt.Sprintf("%s-clone", suite.credentialsName), repo.CredentialsName, "credentials name mismatch") suite.Equal(fmt.Sprintf("%s-clone", suite.credentialsName), repo.CredentialsName, "credentials name mismatch")
suite.repo = repo suite.repo = repo
@ -88,16 +88,16 @@ func (suite *GarmSuite) InstallRepoWebhook(id string) *params.HookInfo {
WebhookEndpointType: params.WebhookEndpointDirect, WebhookEndpointType: params.WebhookEndpointDirect,
} }
_, err := installRepoWebhook(suite.cli, suite.authToken, id, webhookParams) _, err := installRepoWebhook(suite.cli, suite.authToken, id, webhookParams)
suite.NoError(err, "error installing repository webhook") suite.Require().NoError(err, "error installing repository webhook")
webhookInfo, err := getRepoWebhook(suite.cli, suite.authToken, id) webhookInfo, err := getRepoWebhook(suite.cli, suite.authToken, id)
suite.NoError(err, "error getting repository webhook") suite.Require().NoError(err, "error getting repository webhook")
return webhookInfo return webhookInfo
} }
func (suite *GarmSuite) ValidateRepoWebhookInstalled(ghToken, url, orgName, repoName string) { func (suite *GarmSuite) ValidateRepoWebhookInstalled(ghToken, url, orgName, repoName string) {
hook, err := getGhRepoWebhook(url, ghToken, orgName, repoName) hook, err := getGhRepoWebhook(url, ghToken, orgName, repoName)
suite.NoError(err, "error getting github webhook") suite.Require().NoError(err, "error getting github webhook")
suite.NotNil(hook, "github webhook with url %s, for repo %s/%s was not properly installed", url, orgName, repoName) suite.NotNil(hook, "github webhook with url %s, for repo %s/%s was not properly installed", url, orgName, repoName)
} }
@ -109,8 +109,8 @@ func getGhRepoWebhook(url, ghToken, orgName, repoName string) (*github.Hook, err
} }
for _, hook := range ghRepoHooks { for _, hook := range ghRepoHooks {
hookURL, ok := hook.Config["url"].(string) hookURL := hook.Config.GetURL()
if ok && hookURL == url { if hookURL == url {
return hook, nil return hook, nil
} }
} }
@ -128,12 +128,12 @@ func (suite *GarmSuite) UninstallRepoWebhook(id string) {
t := suite.T() t := suite.T()
t.Logf("Uninstall repo webhook with repo_id %s", id) t.Logf("Uninstall repo webhook with repo_id %s", id)
err := uninstallRepoWebhook(suite.cli, suite.authToken, id) err := uninstallRepoWebhook(suite.cli, suite.authToken, id)
suite.NoError(err, "error uninstalling repository webhook") suite.Require().NoError(err, "error uninstalling repository webhook")
} }
func (suite *GarmSuite) ValidateRepoWebhookUninstalled(ghToken, url, orgName, repoName string) { func (suite *GarmSuite) ValidateRepoWebhookUninstalled(ghToken, url, orgName, repoName string) {
hook, err := getGhRepoWebhook(url, ghToken, orgName, repoName) hook, err := getGhRepoWebhook(url, ghToken, orgName, repoName)
suite.NoError(err, "error getting github webhook") suite.Require().NoError(err, "error getting github webhook")
suite.Nil(hook, "github webhook with url %s, for repo %s/%s was not properly uninstalled", url, orgName, repoName) suite.Nil(hook, "github webhook with url %s, for repo %s/%s was not properly uninstalled", url, orgName, repoName)
} }
@ -141,7 +141,7 @@ func (suite *GarmSuite) CreateRepoPool(repoID string, poolParams params.CreatePo
t := suite.T() t := suite.T()
t.Logf("Create repo pool with repo_id %s and pool_params %+v", repoID, poolParams) t.Logf("Create repo pool with repo_id %s and pool_params %+v", repoID, poolParams)
pool, err := createRepoPool(suite.cli, suite.authToken, repoID, poolParams) pool, err := createRepoPool(suite.cli, suite.authToken, repoID, poolParams)
suite.NoError(err, "error creating repository pool") suite.Require().NoError(err, "error creating repository pool")
return pool return pool
} }
@ -149,7 +149,7 @@ func (suite *GarmSuite) GetRepoPool(repoID, repoPoolID string) *params.Pool {
t := suite.T() t := suite.T()
t.Logf("Get repo pool repo_id %s and pool_id %s", repoID, repoPoolID) t.Logf("Get repo pool repo_id %s and pool_id %s", repoID, repoPoolID)
pool, err := getRepoPool(suite.cli, suite.authToken, repoID, repoPoolID) pool, err := getRepoPool(suite.cli, suite.authToken, repoID, repoPoolID)
suite.NoError(err, "error getting repository pool") suite.Require().NoError(err, "error getting repository pool")
return pool return pool
} }
@ -157,7 +157,7 @@ func (suite *GarmSuite) DeleteRepoPool(repoID, repoPoolID string) {
t := suite.T() t := suite.T()
t.Logf("Delete repo pool with repo_id %s and pool_id %s", repoID, repoPoolID) t.Logf("Delete repo pool with repo_id %s and pool_id %s", repoID, repoPoolID)
err := deleteRepoPool(suite.cli, suite.authToken, repoID, repoPoolID) err := deleteRepoPool(suite.cli, suite.authToken, repoID, repoPoolID)
suite.NoError(err, "error deleting repository pool") suite.Require().NoError(err, "error deleting repository pool")
} }
func (suite *GarmSuite) UpdateRepoPool(repoID, repoPoolID string, maxRunners, minIdleRunners uint) *params.Pool { func (suite *GarmSuite) UpdateRepoPool(repoID, repoPoolID string, maxRunners, minIdleRunners uint) *params.Pool {
@ -168,14 +168,14 @@ func (suite *GarmSuite) UpdateRepoPool(repoID, repoPoolID string, maxRunners, mi
MaxRunners: &maxRunners, MaxRunners: &maxRunners,
} }
pool, err := updateRepoPool(suite.cli, suite.authToken, repoID, repoPoolID, poolParams) pool, err := updateRepoPool(suite.cli, suite.authToken, repoID, repoPoolID, poolParams)
suite.NoError(err, "error updating repository pool") suite.Require().NoError(err, "error updating repository pool")
return pool return pool
} }
func (suite *GarmSuite) WaitRepoRunningIdleInstances(repoID string, timeout time.Duration) { func (suite *GarmSuite) WaitRepoRunningIdleInstances(repoID string, timeout time.Duration) {
t := suite.T() t := suite.T()
repoPools, err := listRepoPools(suite.cli, suite.authToken, repoID) repoPools, err := listRepoPools(suite.cli, suite.authToken, repoID)
suite.NoError(err, "error listing repo pools") suite.Require().NoError(err, "error listing repo pools")
for _, pool := range repoPools { for _, pool := range repoPools {
err := suite.WaitPoolInstances(pool.ID, commonParams.InstanceRunning, params.RunnerIdle, timeout) err := suite.WaitPoolInstances(pool.ID, commonParams.InstanceRunning, params.RunnerIdle, timeout)
if err != nil { if err != nil {
@ -190,19 +190,19 @@ func (suite *GarmSuite) dumpRepoInstancesDetails(repoID string) {
// print repo details // print repo details
t.Logf("Dumping repo details for repo %s", repoID) t.Logf("Dumping repo details for repo %s", repoID)
repo, err := getRepo(suite.cli, suite.authToken, repoID) repo, err := getRepo(suite.cli, suite.authToken, repoID)
suite.NoError(err, "error getting repo") suite.Require().NoError(err, "error getting repo")
err = printJSONResponse(repo) err = printJSONResponse(repo)
suite.NoError(err, "error printing repo") suite.Require().NoError(err, "error printing repo")
// print repo instances details // print repo instances details
t.Logf("Dumping repo instances details for repo %s", repoID) t.Logf("Dumping repo instances details for repo %s", repoID)
instances, err := listRepoInstances(suite.cli, suite.authToken, repoID) instances, err := listRepoInstances(suite.cli, suite.authToken, repoID)
suite.NoError(err, "error listing repo instances") suite.Require().NoError(err, "error listing repo instances")
for _, instance := range instances { for _, instance := range instances {
instance, err := getInstance(suite.cli, suite.authToken, instance.Name) instance, err := getInstance(suite.cli, suite.authToken, instance.Name)
suite.NoError(err, "error getting instance") suite.Require().NoError(err, "error getting instance")
t.Logf("Instance info for instance %s", instance.Name) t.Logf("Instance info for instance %s", instance.Name)
err = printJSONResponse(instance) err = printJSONResponse(instance)
suite.NoError(err, "error printing instance") suite.Require().NoError(err, "error printing instance")
} }
} }

View file

@ -22,7 +22,7 @@ import (
"log/slog" "log/slog"
"net/http" "net/http"
"github.com/google/go-github/v57/github" "github.com/google/go-github/v72/github"
"github.com/pkg/errors" "github.com/pkg/errors"
runnerErrors "github.com/cloudbase/garm-provider-common/errors" runnerErrors "github.com/cloudbase/garm-provider-common/errors"
@ -160,7 +160,7 @@ func (g *githubClient) PingEntityHook(ctx context.Context, id int64) (ret *githu
return ret, err return ret, err
} }
func (g *githubClient) ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) { func (g *githubClient) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error) {
var ret *github.Runners var ret *github.Runners
var response *github.Response var response *github.Response
var err error var err error
@ -383,7 +383,7 @@ func (g *githubClient) GetEntityJITConfig(ctx context.Context, instance string,
Labels: labels, Labels: labels,
// nolint:golangci-lint,godox // nolint:golangci-lint,godox
// TODO(gabriel-samfira): Should we make this configurable? // TODO(gabriel-samfira): Should we make this configurable?
WorkFolder: github.String("_work"), WorkFolder: github.Ptr("_work"),
} }
metrics.GithubOperationCount.WithLabelValues( metrics.GithubOperationCount.WithLabelValues(

View file

@ -13,7 +13,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/google/go-github/v71/github" "github.com/google/go-github/v72/github"
) )
const ( const (

View file

@ -45,6 +45,7 @@ const (
InstancePendingDelete InstanceStatus = "pending_delete" InstancePendingDelete InstanceStatus = "pending_delete"
InstancePendingForceDelete InstanceStatus = "pending_force_delete" InstancePendingForceDelete InstanceStatus = "pending_force_delete"
InstanceDeleting InstanceStatus = "deleting" InstanceDeleting InstanceStatus = "deleting"
InstanceDeleted InstanceStatus = "deleted"
InstancePendingCreate InstanceStatus = "pending_create" InstancePendingCreate InstanceStatus = "pending_create"
InstanceCreating InstanceStatus = "creating" InstanceCreating InstanceStatus = "creating"
InstanceStatusUnknown InstanceStatus = "unknown" InstanceStatusUnknown InstanceStatus = "unknown"

View file

@ -1,26 +1,28 @@
version: "2"
run: run:
timeout: 1m timeout: 1m
tests: true tests: true
linters: linters:
disable-all: true default: none
enable: enable: # please keep this alphabetized
- asasalint
- asciicheck - asciicheck
- copyloopvar
- dupl
- errcheck - errcheck
- forcetypeassert - forcetypeassert
- goconst
- gocritic - gocritic
- gofmt
- goimports
- gosimple
- govet - govet
- ineffassign - ineffassign
- misspell - misspell
- musttag
- revive - revive
- staticcheck - staticcheck
- typecheck
- unused - unused
issues: issues:
exclude-use-default: false
max-issues-per-linter: 0 max-issues-per-linter: 0
max-same-issues: 10 max-same-issues: 10

View file

@ -77,7 +77,7 @@ func newSink(fn func(prefix, args string), formatter Formatter) logr.LogSink {
write: fn, write: fn,
} }
// For skipping fnlogger.Info and fnlogger.Error. // For skipping fnlogger.Info and fnlogger.Error.
l.Formatter.AddCallDepth(1) l.AddCallDepth(1) // via Formatter
return l return l
} }
@ -164,17 +164,17 @@ type fnlogger struct {
} }
func (l fnlogger) WithName(name string) logr.LogSink { func (l fnlogger) WithName(name string) logr.LogSink {
l.Formatter.AddName(name) l.AddName(name) // via Formatter
return &l return &l
} }
func (l fnlogger) WithValues(kvList ...any) logr.LogSink { func (l fnlogger) WithValues(kvList ...any) logr.LogSink {
l.Formatter.AddValues(kvList) l.AddValues(kvList) // via Formatter
return &l return &l
} }
func (l fnlogger) WithCallDepth(depth int) logr.LogSink { func (l fnlogger) WithCallDepth(depth int) logr.LogSink {
l.Formatter.AddCallDepth(depth) l.AddCallDepth(depth) // via Formatter
return &l return &l
} }

View file

@ -25,6 +25,7 @@ Asta Xie <xiemengjun at gmail.com>
B Lamarche <blam413 at gmail.com> B Lamarche <blam413 at gmail.com>
Bes Dollma <bdollma@thousandeyes.com> Bes Dollma <bdollma@thousandeyes.com>
Bogdan Constantinescu <bog.con.bc at gmail.com> Bogdan Constantinescu <bog.con.bc at gmail.com>
Brad Higgins <brad at defined.net>
Brian Hendriks <brian at dolthub.com> Brian Hendriks <brian at dolthub.com>
Bulat Gaifullin <gaifullinbf at gmail.com> Bulat Gaifullin <gaifullinbf at gmail.com>
Caine Jette <jette at alum.mit.edu> Caine Jette <jette at alum.mit.edu>
@ -37,6 +38,7 @@ Daniel Montoya <dsmontoyam at gmail.com>
Daniel Nichter <nil at codenode.com> Daniel Nichter <nil at codenode.com>
Daniël van Eeden <git at myname.nl> Daniël van Eeden <git at myname.nl>
Dave Protasowski <dprotaso at gmail.com> Dave Protasowski <dprotaso at gmail.com>
Diego Dupin <diego.dupin at gmail.com>
Dirkjan Bussink <d.bussink at gmail.com> Dirkjan Bussink <d.bussink at gmail.com>
DisposaBoy <disposaboy at dby.me> DisposaBoy <disposaboy at dby.me>
Egor Smolyakov <egorsmkv at gmail.com> Egor Smolyakov <egorsmkv at gmail.com>
@ -133,6 +135,7 @@ Ziheng Lyu <zihenglv at gmail.com>
Barracuda Networks, Inc. Barracuda Networks, Inc.
Counting Ltd. Counting Ltd.
Defined Networking Inc.
DigitalOcean Inc. DigitalOcean Inc.
Dolthub Inc. Dolthub Inc.
dyves labs AG dyves labs AG

View file

@ -1,5 +1,16 @@
# Changelog # Changelog
## v1.9.3 (2025-06-13)
* `tx.Commit()` and `tx.Rollback()` returned `ErrInvalidConn` always.
Now they return cached real error if present. (#1690)
* Optimize reading small resultsets to fix performance regression
introduced by compression protocol support. (#1707)
* Fix `db.Ping()` on compressed connection. (#1723)
## v1.9.2 (2025-04-07) ## v1.9.2 (2025-04-07)
v1.9.2 is a re-release of v1.9.1 due to a release process issue; no changes were made to the content. v1.9.2 is a re-release of v1.9.1 due to a release process issue; no changes were made to the content.

View file

@ -42,6 +42,11 @@ func (b *buffer) busy() bool {
return len(b.buf) > 0 return len(b.buf) > 0
} }
// len returns how many bytes in the read buffer.
func (b *buffer) len() int {
return len(b.buf)
}
// fill reads into the read buffer until at least _need_ bytes are in it. // fill reads into the read buffer until at least _need_ bytes are in it.
func (b *buffer) fill(need int, r readerFunc) error { func (b *buffer) fill(need int, r readerFunc) error {
// we'll move the contents of the current buffer to dest before filling it. // we'll move the contents of the current buffer to dest before filling it.
@ -86,17 +91,10 @@ func (b *buffer) fill(need int, r readerFunc) error {
// returns next N bytes from buffer. // returns next N bytes from buffer.
// The returned slice is only guaranteed to be valid until the next read // The returned slice is only guaranteed to be valid until the next read
func (b *buffer) readNext(need int, r readerFunc) ([]byte, error) { func (b *buffer) readNext(need int) []byte {
if len(b.buf) < need { data := b.buf[:need:need]
// refill
if err := b.fill(need, r); err != nil {
return nil, err
}
}
data := b.buf[:need]
b.buf = b.buf[need:] b.buf = b.buf[need:]
return data, nil return data
} }
// takeBuffer returns a buffer with the requested size. // takeBuffer returns a buffer with the requested size.

View file

@ -84,9 +84,9 @@ func (c *compIO) reset() {
c.buff.Reset() c.buff.Reset()
} }
func (c *compIO) readNext(need int, r readerFunc) ([]byte, error) { func (c *compIO) readNext(need int) ([]byte, error) {
for c.buff.Len() < need { for c.buff.Len() < need {
if err := c.readCompressedPacket(r); err != nil { if err := c.readCompressedPacket(); err != nil {
return nil, err return nil, err
} }
} }
@ -94,8 +94,8 @@ func (c *compIO) readNext(need int, r readerFunc) ([]byte, error) {
return data[:need:need], nil // prevent caller writes into c.buff return data[:need:need], nil // prevent caller writes into c.buff
} }
func (c *compIO) readCompressedPacket(r readerFunc) error { func (c *compIO) readCompressedPacket() error {
header, err := c.mc.buf.readNext(7, r) // size of compressed header header, err := c.mc.readNext(7)
if err != nil { if err != nil {
return err return err
} }
@ -103,7 +103,7 @@ func (c *compIO) readCompressedPacket(r readerFunc) error {
// compressed header structure // compressed header structure
comprLength := getUint24(header[0:3]) comprLength := getUint24(header[0:3])
compressionSequence := uint8(header[3]) compressionSequence := header[3]
uncompressedLength := getUint24(header[4:7]) uncompressedLength := getUint24(header[4:7])
if debug { if debug {
fmt.Printf("uncompress cmplen=%v uncomplen=%v pkt_cmp_seq=%v expected_cmp_seq=%v\n", fmt.Printf("uncompress cmplen=%v uncomplen=%v pkt_cmp_seq=%v expected_cmp_seq=%v\n",
@ -113,14 +113,13 @@ func (c *compIO) readCompressedPacket(r readerFunc) error {
// Server may return error packet (e.g. 1153 Got a packet bigger than 'max_allowed_packet' bytes) // Server may return error packet (e.g. 1153 Got a packet bigger than 'max_allowed_packet' bytes)
// before receiving all packets from client. In this case, seqnr is younger than expected. // before receiving all packets from client. In this case, seqnr is younger than expected.
// NOTE: Both of mariadbclient and mysqlclient do not check seqnr. Only server checks it. // NOTE: Both of mariadbclient and mysqlclient do not check seqnr. Only server checks it.
if debug && compressionSequence != c.mc.sequence { if debug && compressionSequence != c.mc.compressSequence {
fmt.Printf("WARN: unexpected cmpress seq nr: expected %v, got %v", fmt.Printf("WARN: unexpected cmpress seq nr: expected %v, got %v",
c.mc.sequence, compressionSequence) c.mc.compressSequence, compressionSequence)
} }
c.mc.sequence = compressionSequence + 1 c.mc.compressSequence = compressionSequence + 1
c.mc.compressSequence = c.mc.sequence
comprData, err := c.mc.buf.readNext(comprLength, r) comprData, err := c.mc.readNext(comprLength)
if err != nil { if err != nil {
return err return err
} }
@ -200,7 +199,7 @@ func (c *compIO) writeCompressedPacket(data []byte, uncompressedLen int) (int, e
comprLength := len(data) - 7 comprLength := len(data) - 7
if debug { if debug {
fmt.Printf( fmt.Printf(
"writeCompressedPacket: comprLength=%v, uncompressedLen=%v, seq=%v", "writeCompressedPacket: comprLength=%v, uncompressedLen=%v, seq=%v\n",
comprLength, uncompressedLen, mc.compressSequence) comprLength, uncompressedLen, mc.compressSequence)
} }

View file

@ -17,6 +17,7 @@ import (
"fmt" "fmt"
"io" "io"
"math" "math"
"os"
"strconv" "strconv"
"time" "time"
) )
@ -25,19 +26,30 @@ import (
// https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html // https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html
// https://mariadb.com/kb/en/clientserver-protocol/ // https://mariadb.com/kb/en/clientserver-protocol/
// read n bytes from mc.buf
func (mc *mysqlConn) readNext(n int) ([]byte, error) {
if mc.buf.len() < n {
err := mc.buf.fill(n, mc.readWithTimeout)
if err != nil {
return nil, err
}
}
return mc.buf.readNext(n), nil
}
// Read packet to buffer 'data' // Read packet to buffer 'data'
func (mc *mysqlConn) readPacket() ([]byte, error) { func (mc *mysqlConn) readPacket() ([]byte, error) {
var prevData []byte var prevData []byte
invalidSequence := false invalidSequence := false
readNext := mc.buf.readNext readNext := mc.readNext
if mc.compress { if mc.compress {
readNext = mc.compIO.readNext readNext = mc.compIO.readNext
} }
for { for {
// read packet header // read packet header
data, err := readNext(4, mc.readWithTimeout) data, err := readNext(4)
if err != nil { if err != nil {
mc.close() mc.close()
if cerr := mc.canceled.Value(); cerr != nil { if cerr := mc.canceled.Value(); cerr != nil {
@ -51,17 +63,11 @@ func (mc *mysqlConn) readPacket() ([]byte, error) {
pktLen := getUint24(data[:3]) pktLen := getUint24(data[:3])
seq := data[3] seq := data[3]
if mc.compress { // check packet sync [8 bit]
if seq != mc.sequence {
mc.log(fmt.Sprintf("[warn] unexpected sequence nr: expected %v, got %v", mc.sequence, seq))
// MySQL and MariaDB doesn't check packet nr in compressed packet. // MySQL and MariaDB doesn't check packet nr in compressed packet.
if debug && seq != mc.compressSequence { if !mc.compress {
fmt.Printf("[debug] mismatched compression sequence nr: expected: %v, got %v",
mc.compressSequence, seq)
}
mc.compressSequence = seq + 1
} else {
// check packet sync [8 bit]
if seq != mc.sequence {
mc.log(fmt.Sprintf("[warn] unexpected seq nr: expected %v, got %v", mc.sequence, seq))
// For large packets, we stop reading as soon as sync error. // For large packets, we stop reading as soon as sync error.
if len(prevData) > 0 { if len(prevData) > 0 {
mc.close() mc.close()
@ -69,8 +75,8 @@ func (mc *mysqlConn) readPacket() ([]byte, error) {
} }
invalidSequence = true invalidSequence = true
} }
mc.sequence++
} }
mc.sequence = seq + 1
// packets with length 0 terminate a previous packet which is a // packets with length 0 terminate a previous packet which is a
// multiple of (2^24)-1 bytes long // multiple of (2^24)-1 bytes long
@ -85,7 +91,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) {
} }
// read packet body [pktLen bytes] // read packet body [pktLen bytes]
data, err = readNext(pktLen, mc.readWithTimeout) data, err = readNext(pktLen)
if err != nil { if err != nil {
mc.close() mc.close()
if cerr := mc.canceled.Value(); cerr != nil { if cerr := mc.canceled.Value(); cerr != nil {
@ -135,7 +141,7 @@ func (mc *mysqlConn) writePacket(data []byte) error {
// Write packet // Write packet
if debug { if debug {
fmt.Printf("writePacket: size=%v seq=%v", size, mc.sequence) fmt.Fprintf(os.Stderr, "writePacket: size=%v seq=%v\n", size, mc.sequence)
} }
n, err := writeFunc(data[:4+size]) n, err := writeFunc(data[:4+size])
@ -434,7 +440,9 @@ func (mc *mysqlConn) writeCommandPacket(command byte) error {
data[4] = command data[4] = command
// Send CMD packet // Send CMD packet
return mc.writePacket(data) err = mc.writePacket(data)
mc.syncSequence()
return err
} }
func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error {
@ -475,7 +483,9 @@ func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error {
binary.LittleEndian.PutUint32(data[5:], arg) binary.LittleEndian.PutUint32(data[5:], arg)
// Send CMD packet // Send CMD packet
return mc.writePacket(data) err = mc.writePacket(data)
mc.syncSequence()
return err
} }
/****************************************************************************** /******************************************************************************
@ -945,7 +955,6 @@ func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
pktLen = dataOffset + argLen pktLen = dataOffset + argLen
} }
stmt.mc.resetSequence()
// Add command byte [1 byte] // Add command byte [1 byte]
data[4] = comStmtSendLongData data[4] = comStmtSendLongData
@ -957,6 +966,8 @@ func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
// Send CMD packet // Send CMD packet
err := stmt.mc.writePacket(data[:4+pktLen]) err := stmt.mc.writePacket(data[:4+pktLen])
// Every COM_LONG_DATA packet reset Packet Sequence
stmt.mc.resetSequence()
if err == nil { if err == nil {
data = data[pktLen-dataOffset:] data = data[pktLen-dataOffset:]
continue continue
@ -964,8 +975,6 @@ func (stmt *mysqlStmt) writeCommandLongData(paramID int, arg []byte) error {
return err return err
} }
// Reset Packet Sequence
stmt.mc.resetSequence()
return nil return nil
} }

View file

@ -13,18 +13,32 @@ type mysqlTx struct {
} }
func (tx *mysqlTx) Commit() (err error) { func (tx *mysqlTx) Commit() (err error) {
if tx.mc == nil || tx.mc.closed.Load() { if tx.mc == nil {
return ErrInvalidConn return ErrInvalidConn
} }
if tx.mc.closed.Load() {
err = tx.mc.error()
if err == nil {
err = ErrInvalidConn
}
return
}
err = tx.mc.exec("COMMIT") err = tx.mc.exec("COMMIT")
tx.mc = nil tx.mc = nil
return return
} }
func (tx *mysqlTx) Rollback() (err error) { func (tx *mysqlTx) Rollback() (err error) {
if tx.mc == nil || tx.mc.closed.Load() { if tx.mc == nil {
return ErrInvalidConn return ErrInvalidConn
} }
if tx.mc.closed.Load() {
err = tx.mc.error()
if err == nil {
err = ErrInvalidConn
}
return
}
err = tx.mc.exec("ROLLBACK") err = tx.mc.exec("ROLLBACK")
tx.mc = nil tx.mc = nil
return return

View file

@ -155,7 +155,7 @@ stored in base64 encoded form, which was redundant with the information in the
type Token struct { type Token struct {
Raw string // Raw contains the raw token Raw string // Raw contains the raw token
Method SigningMethod // Method is the signing method used or to be used Method SigningMethod // Method is the signing method used or to be used
Header map[string]interface{} // Header is the first segment of the token in decoded form Header map[string]any // Header is the first segment of the token in decoded form
Claims Claims // Claims is the second segment of the token in decoded form Claims Claims // Claims is the second segment of the token in decoded form
Signature []byte // Signature is the third segment of the token in decoded form Signature []byte // Signature is the third segment of the token in decoded form
Valid bool // Valid specifies if the token is valid Valid bool // Valid specifies if the token is valid

View file

@ -55,7 +55,7 @@ func (m *SigningMethodECDSA) Alg() string {
// Verify implements token verification for the SigningMethod. // Verify implements token verification for the SigningMethod.
// For this verify method, key must be an ecdsa.PublicKey struct // For this verify method, key must be an ecdsa.PublicKey struct
func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key any) error {
// Get the key // Get the key
var ecdsaKey *ecdsa.PublicKey var ecdsaKey *ecdsa.PublicKey
switch k := key.(type) { switch k := key.(type) {
@ -89,7 +89,7 @@ func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interf
// Sign implements token signing for the SigningMethod. // Sign implements token signing for the SigningMethod.
// For this signing method, key must be an ecdsa.PrivateKey struct // For this signing method, key must be an ecdsa.PrivateKey struct
func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { func (m *SigningMethodECDSA) Sign(signingString string, key any) ([]byte, error) {
// Get the key // Get the key
var ecdsaKey *ecdsa.PrivateKey var ecdsaKey *ecdsa.PrivateKey
switch k := key.(type) { switch k := key.(type) {

View file

@ -23,7 +23,7 @@ func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
} }
// Parse the key // Parse the key
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err return nil, err
@ -50,7 +50,7 @@ func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
} }
// Parse the key // Parse the key
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil { if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey parsedKey = cert.PublicKey

View file

@ -33,7 +33,7 @@ func (m *SigningMethodEd25519) Alg() string {
// Verify implements token verification for the SigningMethod. // Verify implements token verification for the SigningMethod.
// For this verify method, key must be an ed25519.PublicKey // For this verify method, key must be an ed25519.PublicKey
func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key any) error {
var ed25519Key ed25519.PublicKey var ed25519Key ed25519.PublicKey
var ok bool var ok bool
@ -55,7 +55,7 @@ func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key inte
// Sign implements token signing for the SigningMethod. // Sign implements token signing for the SigningMethod.
// For this signing method, key must be an ed25519.PrivateKey // For this signing method, key must be an ed25519.PrivateKey
func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { func (m *SigningMethodEd25519) Sign(signingString string, key any) ([]byte, error) {
var ed25519Key crypto.Signer var ed25519Key crypto.Signer
var ok bool var ok bool

View file

@ -24,7 +24,7 @@ func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) {
} }
// Parse the key // Parse the key
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err return nil, err
} }
@ -49,7 +49,7 @@ func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) {
} }
// Parse the key // Parse the key
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
return nil, err return nil, err
} }

View file

@ -55,7 +55,7 @@ func (m *SigningMethodHMAC) Alg() string {
// about this, and why we intentionally are not supporting string as a key can // about this, and why we intentionally are not supporting string as a key can
// be found on our usage guide // be found on our usage guide
// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types.
func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key any) error {
// Verify the key is the right type // Verify the key is the right type
keyBytes, ok := key.([]byte) keyBytes, ok := key.([]byte)
if !ok { if !ok {
@ -88,7 +88,7 @@ func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interfa
// cryptographically random source, e.g. crypto/rand. Additional information // cryptographically random source, e.g. crypto/rand. Additional information
// about this, and why we intentionally are not supporting string as a key can // about this, and why we intentionally are not supporting string as a key can
// be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. // be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/.
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { func (m *SigningMethodHMAC) Sign(signingString string, key any) ([]byte, error) {
if keyBytes, ok := key.([]byte); ok { if keyBytes, ok := key.([]byte); ok {
if !m.Hash.Available() { if !m.Hash.Available() {
return nil, ErrHashUnavailable return nil, ErrHashUnavailable

View file

@ -5,9 +5,9 @@ import (
"fmt" "fmt"
) )
// MapClaims is a claims type that uses the map[string]interface{} for JSON // MapClaims is a claims type that uses the map[string]any for JSON
// decoding. This is the default claims type if you don't supply one // decoding. This is the default claims type if you don't supply one
type MapClaims map[string]interface{} type MapClaims map[string]any
// GetExpirationTime implements the Claims interface. // GetExpirationTime implements the Claims interface.
func (m MapClaims) GetExpirationTime() (*NumericDate, error) { func (m MapClaims) GetExpirationTime() (*NumericDate, error) {
@ -73,7 +73,7 @@ func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) {
cs = append(cs, v) cs = append(cs, v)
case []string: case []string:
cs = v cs = v
case []interface{}: case []any:
for _, a := range v { for _, a := range v {
vs, ok := a.(string) vs, ok := a.(string)
if !ok { if !ok {
@ -92,7 +92,7 @@ func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) {
func (m MapClaims) parseString(key string) (string, error) { func (m MapClaims) parseString(key string) (string, error) {
var ( var (
ok bool ok bool
raw interface{} raw any
iss string iss string
) )
raw, ok = m[key] raw, ok = m[key]

View file

@ -25,7 +25,7 @@ func (m *signingMethodNone) Alg() string {
} }
// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { func (m *signingMethodNone) Verify(signingString string, sig []byte, key any) (err error) {
// Key must be UnsafeAllowNoneSignatureType to prevent accidentally // Key must be UnsafeAllowNoneSignatureType to prevent accidentally
// accepting 'none' signing method // accepting 'none' signing method
if _, ok := key.(unsafeNoneMagicConstant); !ok { if _, ok := key.(unsafeNoneMagicConstant); !ok {
@ -41,7 +41,7 @@ func (m *signingMethodNone) Verify(signingString string, sig []byte, key interfa
} }
// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key
func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { func (m *signingMethodNone) Sign(signingString string, key any) ([]byte, error) {
if _, ok := key.(unsafeNoneMagicConstant); ok { if _, ok := key.(unsafeNoneMagicConstant); ok {
return []byte{}, nil return []byte{}, nil
} }

View file

@ -66,20 +66,37 @@ func WithExpirationRequired() ParserOption {
} }
} }
// WithAudience configures the validator to require the specified audience in // WithAudience configures the validator to require any of the specified
// the `aud` claim. Validation will fail if the audience is not listed in the // audiences in the `aud` claim. Validation will fail if the audience is not
// token or the `aud` claim is missing. // listed in the token or the `aud` claim is missing.
// //
// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is // NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is
// application-specific. Since this validation API is helping developers in // application-specific. Since this validation API is helping developers in
// writing secure application, we decided to REQUIRE the existence of the claim, // writing secure application, we decided to REQUIRE the existence of the claim,
// if an audience is expected. // if an audience is expected.
func WithAudience(aud string) ParserOption { func WithAudience(aud ...string) ParserOption {
return func(p *Parser) { return func(p *Parser) {
p.validator.expectedAud = aud p.validator.expectedAud = aud
} }
} }
// WithAllAudiences configures the validator to require all the specified
// audiences in the `aud` claim. Validation will fail if the specified audiences
// are not listed in the token or the `aud` claim is missing. Duplicates within
// the list are de-duplicated since internally, we use a map to look up the
// audiences.
//
// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is
// application-specific. Since this validation API is helping developers in
// writing secure application, we decided to REQUIRE the existence of the claim,
// if an audience is expected.
func WithAllAudiences(aud ...string) ParserOption {
return func(p *Parser) {
p.validator.expectedAud = aud
p.validator.expectAllAud = true
}
}
// WithIssuer configures the validator to require the specified issuer in the // WithIssuer configures the validator to require the specified issuer in the
// `iss` claim. Validation will fail if a different issuer is specified in the // `iss` claim. Validation will fail if a different issuer is specified in the
// token or the `iss` claim is missing. // token or the `iss` claim is missing.

View file

@ -46,7 +46,7 @@ func (m *SigningMethodRSA) Alg() string {
// Verify implements token verification for the SigningMethod // Verify implements token verification for the SigningMethod
// For this signing method, must be an *rsa.PublicKey structure. // For this signing method, must be an *rsa.PublicKey structure.
func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key any) error {
var rsaKey *rsa.PublicKey var rsaKey *rsa.PublicKey
var ok bool var ok bool
@ -67,7 +67,7 @@ func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interfac
// Sign implements token signing for the SigningMethod // Sign implements token signing for the SigningMethod
// For this signing method, must be an *rsa.PrivateKey structure. // For this signing method, must be an *rsa.PrivateKey structure.
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { func (m *SigningMethodRSA) Sign(signingString string, key any) ([]byte, error) {
var rsaKey *rsa.PrivateKey var rsaKey *rsa.PrivateKey
var ok bool var ok bool

View file

@ -82,7 +82,7 @@ func init() {
// Verify implements token verification for the SigningMethod. // Verify implements token verification for the SigningMethod.
// For this verify method, key must be an rsa.PublicKey struct // For this verify method, key must be an rsa.PublicKey struct
func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key any) error {
var rsaKey *rsa.PublicKey var rsaKey *rsa.PublicKey
switch k := key.(type) { switch k := key.(type) {
case *rsa.PublicKey: case *rsa.PublicKey:
@ -108,7 +108,7 @@ func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key inter
// Sign implements token signing for the SigningMethod. // Sign implements token signing for the SigningMethod.
// For this signing method, key must be an rsa.PrivateKey struct // For this signing method, key must be an rsa.PrivateKey struct
func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { func (m *SigningMethodRSAPSS) Sign(signingString string, key any) ([]byte, error) {
var rsaKey *rsa.PrivateKey var rsaKey *rsa.PrivateKey
switch k := key.(type) { switch k := key.(type) {

View file

@ -23,7 +23,7 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
return nil, ErrKeyMustBePEMEncoded return nil, ErrKeyMustBePEMEncoded
} }
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err return nil, err
@ -53,7 +53,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr
return nil, ErrKeyMustBePEMEncoded return nil, ErrKeyMustBePEMEncoded
} }
var parsedKey interface{} var parsedKey any
var blockDecrypted []byte var blockDecrypted []byte
if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
@ -86,7 +86,7 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
} }
// Parse the key // Parse the key
var parsedKey interface{} var parsedKey any
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
if cert, err := x509.ParseCertificate(block.Bytes); err == nil { if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
parsedKey = cert.PublicKey parsedKey = cert.PublicKey

View file

@ -12,9 +12,9 @@ var signingMethodLock = new(sync.RWMutex)
// signature in Sign. The signature is then usually base64 encoded as part of a // signature in Sign. The signature is then usually base64 encoded as part of a
// JWT. // JWT.
type SigningMethod interface { type SigningMethod interface {
Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid Verify(signingString string, sig []byte, key any) error // Returns nil if signature is valid
Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error Sign(signingString string, key any) ([]byte, error) // Returns signature or error
Alg() string // returns the alg identifier for this method (example: 'HS256') Alg() string // returns the alg identifier for this method (example: 'HS256')
} }
// RegisterSigningMethod registers the "alg" name and a factory function for signing method. // RegisterSigningMethod registers the "alg" name and a factory function for signing method.

View file

@ -11,9 +11,9 @@ import (
// Token. This allows you to use properties in the Header of the token (such as // Token. This allows you to use properties in the Header of the token (such as
// `kid`) to identify which key to use. // `kid`) to identify which key to use.
// //
// The returned interface{} may be a single key or a VerificationKeySet containing // The returned any may be a single key or a VerificationKeySet containing
// multiple keys. // multiple keys.
type Keyfunc func(*Token) (interface{}, error) type Keyfunc func(*Token) (any, error)
// VerificationKey represents a public or secret key for verifying a token's signature. // VerificationKey represents a public or secret key for verifying a token's signature.
type VerificationKey interface { type VerificationKey interface {
@ -28,12 +28,12 @@ type VerificationKeySet struct {
// Token represents a JWT Token. Different fields will be used depending on // Token represents a JWT Token. Different fields will be used depending on
// whether you're creating or parsing/verifying a token. // whether you're creating or parsing/verifying a token.
type Token struct { type Token struct {
Raw string // Raw contains the raw token. Populated when you [Parse] a token Raw string // Raw contains the raw token. Populated when you [Parse] a token
Method SigningMethod // Method is the signing method used or to be used Method SigningMethod // Method is the signing method used or to be used
Header map[string]interface{} // Header is the first segment of the token in decoded form Header map[string]any // Header is the first segment of the token in decoded form
Claims Claims // Claims is the second segment of the token in decoded form Claims Claims // Claims is the second segment of the token in decoded form
Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token
Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token
} }
// New creates a new [Token] with the specified signing method and an empty map // New creates a new [Token] with the specified signing method and an empty map
@ -46,7 +46,7 @@ func New(method SigningMethod, opts ...TokenOption) *Token {
// claims. Additional options can be specified, but are currently unused. // claims. Additional options can be specified, but are currently unused.
func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token {
return &Token{ return &Token{
Header: map[string]interface{}{ Header: map[string]any{
"typ": "JWT", "typ": "JWT",
"alg": method.Alg(), "alg": method.Alg(),
}, },
@ -60,7 +60,7 @@ func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *To
// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types
// for an overview of the different signing methods and their respective key // for an overview of the different signing methods and their respective key
// types. // types.
func (t *Token) SignedString(key interface{}) (string, error) { func (t *Token) SignedString(key any) (string, error) {
sstr, err := t.SigningString() sstr, err := t.SigningString()
if err != nil { if err != nil {
return "", err return "", err

View file

@ -103,7 +103,7 @@ func (date *NumericDate) UnmarshalJSON(b []byte) (err error) {
type ClaimStrings []string type ClaimStrings []string
func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) {
var value interface{} var value any
if err = json.Unmarshal(data, &value); err != nil { if err = json.Unmarshal(data, &value); err != nil {
return err return err
@ -116,7 +116,7 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) {
aud = append(aud, v) aud = append(aud, v)
case []string: case []string:
aud = ClaimStrings(v) aud = ClaimStrings(v)
case []interface{}: case []any:
for _, vv := range v { for _, vv := range v {
vs, ok := vv.(string) vs, ok := vv.(string)
if !ok { if !ok {

View file

@ -1,8 +1,8 @@
package jwt package jwt
import ( import (
"crypto/subtle"
"fmt" "fmt"
"slices"
"time" "time"
) )
@ -52,8 +52,12 @@ type Validator struct {
verifyIat bool verifyIat bool
// expectedAud contains the audience this token expects. Supplying an empty // expectedAud contains the audience this token expects. Supplying an empty
// string will disable aud checking. // slice will disable aud checking.
expectedAud string expectedAud []string
// expectAllAud specifies whether all expected audiences must be present in
// the token. If false, only one of the expected audiences must be present.
expectAllAud bool
// expectedIss contains the issuer this token expects. Supplying an empty // expectedIss contains the issuer this token expects. Supplying an empty
// string will disable iss checking. // string will disable iss checking.
@ -88,7 +92,7 @@ func NewValidator(opts ...ParserOption) *Validator {
func (v *Validator) Validate(claims Claims) error { func (v *Validator) Validate(claims Claims) error {
var ( var (
now time.Time now time.Time
errs []error = make([]error, 0, 6) errs = make([]error, 0, 6)
err error err error
) )
@ -120,8 +124,8 @@ func (v *Validator) Validate(claims Claims) error {
} }
// If we have an expected audience, we also require the audience claim // If we have an expected audience, we also require the audience claim
if v.expectedAud != "" { if len(v.expectedAud) > 0 {
if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { if err = v.verifyAudience(claims, v.expectedAud, v.expectAllAud); err != nil {
errs = append(errs, err) errs = append(errs, err)
} }
} }
@ -226,33 +230,39 @@ func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool)
// //
// Additionally, if any error occurs while retrieving the claim, e.g., when its // Additionally, if any error occurs while retrieving the claim, e.g., when its
// the wrong type, an ErrTokenUnverifiable error will be returned. // the wrong type, an ErrTokenUnverifiable error will be returned.
func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error { func (v *Validator) verifyAudience(claims Claims, cmp []string, expectAllAud bool) error {
aud, err := claims.GetAudience() aud, err := claims.GetAudience()
if err != nil { if err != nil {
return err return err
} }
if len(aud) == 0 { // Check that aud exists and is not empty. We only require the aud claim
// if we expect at least one audience to be present.
if len(aud) == 0 || len(aud) == 1 && aud[0] == "" {
required := len(v.expectedAud) > 0
return errorIfRequired(required, "aud") return errorIfRequired(required, "aud")
} }
// use a var here to keep constant time compare when looping over a number of claims if !expectAllAud {
result := false for _, a := range aud {
// If we only expect one match, we can stop early if we find a match
var stringClaims string if slices.Contains(cmp, a) {
for _, a := range aud { return nil
if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { }
result = true
} }
stringClaims = stringClaims + a
return ErrTokenInvalidAudience
} }
// case where "" is sent in one or many aud claims // Note that we are looping cmp here to ensure that all expected audiences
if stringClaims == "" { // are present in the aud claim.
return errorIfRequired(required, "aud") for _, a := range cmp {
if !slices.Contains(aud, a) {
return ErrTokenInvalidAudience
}
} }
return errorIfFalse(result, ErrTokenInvalidAudience) return nil
} }
// verifyIssuer compares the iss claim in claims against cmp. // verifyIssuer compares the iss claim in claims against cmp.

View file

@ -1,487 +0,0 @@
# This is the official list of go-github authors for copyright purposes.
#
# This does not necessarily list everyone who has contributed code, since in
# some cases, their employer may be the copyright holder. To see the full list
# of contributors, see the revision history in source control or
# https://github.com/google/go-github/graphs/contributors.
#
# Authors who wish to be recognized in this file should add themselves (or
# their employer, as appropriate).
178inaba <masahiro.furudate@gmail.com>
2BFL <imqksl@gmail.com>
413x <dedifferentiator@gmail.com>
6543 <6543@obermui.de>
Abed Kibbe <abed.kibbe@gmail.com>
Abhinav Gupta <mail@abhinavg.net>
Abhishek Veeramalla <abhishek.veeramalla@gmail.com>
aboy <b1011211@gmail.com>
Adam Kohring <ajkohring@gmail.com>
adrienzieba <adrien.zieba@appdirect.com>
afdesk <work@afdesk.com>
Ahmad Nurus S <ahmadnurus.sh@gmail.com>
Ahmed Hagy <a.akram93@gmail.com>
Aidan <aidan@artificial.com>
Aidan Steele <aidan.steele@glassechidna.com.au>
Ainsley Chong <ainsley.chong@gmail.com>
ajz01 <azdenek@yahoo.com>
Akeda Bagus <akeda@x-team.com>
Akhil Mohan <akhilerm@gmail.com>
Alec Thomas <alec@swapoff.org>
Aleks Clark <aleks.clark@gmail.com>
Alex Bramley <a.bramley@gmail.com>
Alex Ellis <alexellis2@gmail.com>
Alex Orr <Alexorr.CSE@gmail.com>
Alex Su <alexsu@17.media>
Alex Unger <zyxancf@gmail.com>
Alexander Harkness <me@bearbin.net>
Alexis Gauthiez <alexis.gauthiez@gmail.com>
Ali Farooq <ali.farooq0@pm.me>
Allan Guwatudde <guwats10@gmail.com>
Allen Sun <shlallen1990@gmail.com>
Amey Sakhadeo <me@ameyms.com>
Anders Janmyr <anders@janmyr.com>
Andreas Garnæs <https://github.com/andreas>
Andrew Ryabchun <aryabchun@mail.ua>
Andrew Svoboda <svoboda.andrew@gmail.com>
Andy Grunwald <andygrunwald@gmail.com>
Andy Hume <andyhume@gmail.com>
Andy Lindeman <andy@lindeman.io>
angie pinilla <angelinepinilla@gmail.com>
anjanashenoy <anjanashenoy1@gmail.com>
Anshuman Bhartiya <anshuman.bhartiya@gmail.com>
Antoine <antoine.tu@mail.mcgill.ca>
Antoine Pelisse <apelisse@gmail.com>
Anton Nguyen <afnguyen85@gmail.com>
Anubha Kushwaha <anubha_bt2k14@dtu.ac.in>
appilon <apilon@hashicorp.com>
aprp <doelaudi@gmail.com>
apurwaj2 <apurwaj2@gmail.com>
Aravind <aravindkp@outlook.in>
Arda Kuyumcu <kuyumcuarda@gmail.com>
Arıl Bozoluk <arilbozoluk@hotmail.com>
Asier Marruedo <asiermarruedo@gmail.com>
Austin Burdine <acburdine@gmail.com>
Austin Dizzy <dizzy@wow.com>
Azuka Okuleye <azuka@zatechcorp.com>
Ben Batha <bhbatha@gmail.com>
Benjamen Keroack <benjamen@dollarshaveclub.com>
Berkay Tacyildiz <berkaytacyildiz@gmail.com>
Beshr Kayali <beshrkayali@gmail.com>
Beyang Liu <beyang.liu@gmail.com>
Billy Keyes <bluekeyes@gmail.com>
Billy Lynch <wlynch92@gmail.com>
Bingtan Lu <lubingtan@126.com>
Bjorn Neergaard <bjorn@neersighted.com>
Björn Häuser <b.haeuser@rebuy.de>
Bo Huang <bo.huang@datadoghq.com>
boljen <bol.christophe@gmail.com>
Bracken <abdawson@gmail.com>
Brad Harris <bmharris@gmail.com>
Brad Moylan <moylan.brad@gmail.com>
Bradley Falzon <brad@teambrad.net>
Bradley McAllister <brad.mcallister@hotmail.com>
Brandon Butler <b.butler@chia.net>
Brandon Cook <phylake@gmail.com>
Brandon Stubbs <brstubbs1@gmail.com>
Brett Kuhlman <kuhlman-labs@github.com>
Brett Logan <lindluni@github.com>
Brian Egizi <brian@mojotech.com>
Bryan Boreham <bryan@weave.works>
Bryan Peterson <Lazyshot@gmail.com>
Cami Diez <diezcami@gmail.com>
Carl Johnson <me@carlmjohnson.net>
Carlos Alexandro Becker <caarlos0@gmail.com>
Carlos Tadeu Panato Junior <ctadeu@gmail.com>
ChandanChainani <chainanichan@gmail.com>
chandresh-pancholi <chandreshpancholi007@gmail.com>
Charles Fenwick Elliott <Charles@FenwickElliott.io>
Charlie Yan <charlieyan08@gmail.com>
Chmouel Boudjnah <chmouel@chmouel.com>
Chris King <chriskingnet@gmail.com>
Chris Mc <prince.chrismc@gmail.com>
Chris Raborg <craborg57@gmail.com>
Chris Roche <chris@vsco.co>
Chris Schaefer <chris@dtzq.com>
chrisforrette <chris@chrisforrette.com>
Christian Bargmann <chris@cbrgm.net>
Christian Muehlhaeuser <muesli@gmail.com>
Christoph Jerolimov <jerolimov@gmail.com>
Christoph Sassenberg <defsprite@gmail.com>
CI Monk <ci-monk@protonmail.com>
Colin Misare <github.com/cmisare>
Craig Gumbley <craiggumbley@gmail.com>
Craig Peterson <cpeterson@stackoverflow.com>
Cristian Maglie <c.maglie@bug.st>
Cyb3r Jak3 <jake@jwhite.network>
Daehyeok Mun <daehyeok@gmail.com>
Dalton Hubble <dghubble@gmail.com>
Daniel Lanner <lanner.dan@gmail.com>
Daniel Leavitt <daniel.leavitt@gmail.com>
Daniel Nilsson <daniel.nilsson1989@gmail.com>
Daoq <masseto2002@gmail.com>
Dave Du Cros <davidducros@gmail.com>
Dave Henderson <dhenderson@gmail.com>
Dave Perrett <hello@daveperrett.com>
Dave Protasowski <dprotaso@gmail.com>
David Deng <daviddengcn@gmail.com>
David Gamba <davidgamba@gmail.com>
David J. M. Karlsen <david@davidkarlsen.com>
David Jannotta <djannotta@gmail.com>
David Ji <github.com/davidji99>
David Lopez Reyes <davidlopezre@gmail.com>
Davide Zipeto <dawez1@gmail.com>
Dennis Webb <dennis@bluesentryit.com>
Derek Jobst <derekjobst@gmail.com>
DeviousLab <deviouslab@gmail.com>
Dhi Aurrahman <diorahman@rockybars.com>
Diego Lapiduz <diego.lapiduz@cfpb.gov>
Diogo Vilela <be0x74a@gmail.com>
Dmitri Shuralyov <shurcooL@gmail.com>
dmnlk <seikima2demon@gmail.com>
Don Petersen <don@donpetersen.net>
Doug Turner <doug.turner@gmail.com>
Drew Fradette <drew.fradette@gmail.com>
Dustin Deus <deusdustin@gmail.com>
Dustin Lish <dustin.lish@onepeloton.com>
Eivind <eivindkn@gmail.com>
Eli Uriegas <seemethere101@gmail.com>
Elliott Beach <elliott2.71828@gmail.com>
Emerson Wood <emersonwood94@gmail.com>
Emil V <emil.vaagland@schibsted.com>
Eng Zer Jun <engzerjun@gmail.com>
eperm <staffordworrell@gmail.com>
Erick Fejta <erick@fejta.com>
Erik Nobel <hendrik.nobel@transferwise.com>
erwinvaneyk <erwinvaneyk@gmail.com>
Evan Anderson <evan.k.anderson@gmail.com>
Evan Elias <evanjelias@gmail.com>
Fabian Holler <fabian.holler@simplesurance.de>
Fabrice <fabrice.vaillant@student.ecp.fr>
Fatema-Moaiyadi <fatema.i.moaiyadi@gmail.com>
Federico Di Pierro <nierro92@gmail.com>
Felix Geisendörfer <felix@debuggable.com>
Filippo Valsorda <hi@filippo.io>
Florian Forster <ff@octo.it>
Florian Wagner <h2floh@github.com>
Francesc Gil <xescugil@gmail.com>
Francis <hello@francismakes.com>
Francisco Guimarães <francisco.cpg@gmail.com>
François de Metz <francois@2metz.fr>
Fredrik Jönsson <fredrik.jonsson@izettle.com>
Gabriel <samfiragabriel@gmail.com>
Gal Ofri <galmenashofri@gmail.com>
Garrett Squire <garrettsquire@gmail.com>
George Kontridze <george.kontridze@gmail.com>
Georgy Buranov <gburanov@gmail.com>
Glen Mailer <glenjamin@gmail.com>
Gnahz <p@oath.pl>
Google Inc.
Grachev Mikhail <work@mgrachev.com>
griffin_stewie <panterathefamilyguy@gmail.com>
guangwu <guoguangwu@magic-shield.com>
Guillaume Jacquet <guillaume.jacquet@gmail.com>
Guz Alexander <kalimatas@gmail.com>
Guðmundur Bjarni Ólafsson <gudmundur@github.com>
Hanno Hecker <hanno.hecker@zalando.de>
Hari haran <hariharan.uno@gmail.com>
Harikesh00 <prajapatiharikesh16@gmail.com>
haya14busa <haya14busa@gmail.com>
haya14busa <hayabusa1419@gmail.com>
Hiroki Ito <hiroki.ito.dev@gmail.com>
Hubot Jr <rreichel3@github.com>
Huy Tr <kingbazoka@gmail.com>
huydx <doxuanhuy@gmail.com>
i2bskn <i2bskn@gmail.com>
Iain Steers <iainsteers@gmail.com>
Ikko Ashimine <eltociear@gmail.com>
Ilia Choly <ilia.choly@gmail.com>
Ioannis Georgoulas <igeorgoulas21@gmail.com>
Isao Jonas <isao.jonas@gmail.com>
ishan upadhyay <ishanupadhyay412@gmail.com>
isqua <isqua@isqua.ru>
Jacob Valdemar <jan@lunar.app>
Jake Krammer <jake.krammer1@gmail.com>
Jake White <jake@jwhite.network>
Jameel Haffejee <RC1140@republiccommandos.co.za>
James Bowes <jbowes@repl.ca>
James Cockbain <james.cockbain@ibm.com>
James Loh <github@jloh.co>
James Maguire <jvm986@gmail.com>
James Turley <jamesturley1905@googlemail.com>
Jamie West <jamieianwest@hotmail.com>
Jan Kosecki <jan.kosecki91@gmail.com>
Jan Švábík <jansvabik@jansvabik.cz>
Jason Field <Jason@avon-lea.co.uk>
Javier Campanini <jcampanini@palantir.com>
Jef LeCompte <jeffreylec@gmail.com>
Jeff Wenzbauer <jeff.wenzbauer@niceincontact.com>
Jens Rantil <jens.rantil@gmail.com>
Jeremy Morris <jeremylevanmorris@gmail.com>
Jesse Haka <haka.jesse@gmail.com>
Jesse Newland <jesse@jnewland.com>
Jihoon Chung <j.c@navercorp.com>
Jille Timmermans <jille@quis.cx>
Jimmi Dyson <jimmidyson@gmail.com>
Joan Saum <joan.saum@epitech.eu>
Joe Tsai <joetsai@digital-static.net>
John Barton <jrbarton@gmail.com>
John Engelman <john.r.engelman@gmail.com>
John Jones <john@exthilion.org>
John Liu <john.liu@mongodb.com>
Jordan Brockopp <jdbro94@gmail.com>
Jordan Burandt <jordanburandt@gmail.com>
Jordan Sussman <jordansail22@gmail.com>
Jorge Gómez Reus <j-g1996@live.com>
Joshua Bezaleel Abednego <joshua.bezaleel@gmail.com>
João Cerqueira <joao@cerqueira.io>
JP Phillips <jonphill9@gmail.com>
jpbelanger-mtl <jp.belanger@gmail.com>
Juan <juan.rios.28@gmail.com>
Juan Basso <jrbasso@gmail.com>
Julien Garcia Gonzalez <garciagonzalez.julien@gmail.com>
Julien Rostand <jrostand@users.noreply.github.com>
Junya Kono <junya03dance@gmail.com>
Justin Abrahms <justin@abrah.ms>
Justin Toh <tohjustin@hotmail.com>
Jusung Lee <e.jusunglee@gmail.com>
jzhoucliqr <jzhou@cliqr.com>
k0ral <mail@cmoreau.info>
k1rnt <eru08tera15mora@gmail.com>
kadern0 <kaderno@gmail.com>
Karthik Sundari <karthiksundari2315@gmail.com>
Katrina Owen <kytrinyx@github.com>
Kautilya Tripathi <tripathi.kautilya@gmail.com>
Keita Urashima <ursm@ursm.jp>
Kevin Burke <kev@inburke.com>
Kevin Wang <kwangsan@gmail.com>
Kevin Zhao <kzhao@lyft.com>
kgalli <mail@kgalli.de>
Kirill <g4s8.public@gmail.com>
Konrad Malawski <konrad.malawski@project13.pl>
Kookheon Kwon <kucuny@gmail.com>
Krishna Indani <indanikrishna@gmail.com>
Krzysztof Kowalczyk <kkowalczyk@gmail.com>
Kshitij Saraogi <KshitijSaraogi@gmail.com>
Kumar Saurabh <itsksaurabh@gmail.com>
Kyle Kurz <kyle@doublekaudio.com>
kyokomi <kyoko1220adword@gmail.com>
Lars Lehtonen <lars.lehtonen@gmail.com>
Laurent Verdoïa <verdoialaurent@gmail.com>
leopoldwang <leopold.wang@gmail.com>
Liam Galvin <liam@liam-galvin.co.uk>
Lluis Campos <lluis.campos@northern.tech>
Lovro Mažgon <lovro.mazgon@gmail.com>
Loïs Postula <lois@postu.la>
Luca Campese <me@campesel.net>
Lucas Alcantara <lucasalcantaraf@gmail.com>
Lucas Martin-King <lmartinking@gmail.com>
Luis Davim <luis.davim@sendoso.com>
Luke Evers <me@lukevers.com>
Luke Hinds <luke@stacklok.com>
Luke Kysow <lkysow@gmail.com>
Luke Roberts <email@luke-roberts.co.uk>
Luke Young <luke@hydrantlabs.org>
lynn [they] <lynncyrin@gmail.com>
Magnus Kulke <mkulke@gmail.com>
Maksim Zhylinski <uzzable@gmail.com>
Marc Binder <marcandrebinder@gmail.com>
Marcelo Carlos <marcelo@permutive.com>
Mark Tareshawty <tarebyte@github.com>
Martin Holman <me@martinholman.co.nz>
Martin-Louis Bright <mlbright@gmail.com>
Martins Sipenko <martins.sipenko@gmail.com>
Marwan Sulaiman <marwan.sameer@gmail.com>
Masayuki Izumi <m@izum.in>
Mat Geist <matgeist@gmail.com>
Matija Horvat <horvat2112@gmail.com>
Matin Rahmanian <itsmatinx@gmail.com>
Matt <alpmatthew@gmail.com>
Matt Brender <mjbrender@gmail.com>
Matt Dainty <matt@bodgit-n-scarper.com>
Matt Gaunt <matt@gauntface.co.uk>
Matt Landis <landis.matt@gmail.com>
Matt Moore <mattmoor@vmware.com>
Matt Simons <mattsimons@ntlworld.com>
Maxime Bury <maxime.bury@gmail.com>
Michael Meng <mmeng@lyft.com>
Michael Spiegel <michael.m.spiegel@gmail.com>
Michael Tiller <michael.tiller@gmail.com>
Michał Glapa <michal.glapa@gmail.com>
Michelangelo Morrillo <michelangelo@morrillo.it>
Miguel Elias dos Santos <migueleliasweb@gmail.com>
Mike Chen <mchen300@gmail.com>
mohammad ali <2018cs92@student.uet.edu.pk>
Mohammed AlDujaili <avainer11@gmail.com>
Mukundan Senthil <mukundan314@gmail.com>
Munia Balayil <munia.247@gmail.com>
Mustafa Abban <mustafaabban@utexas.edu>
Nadav Kaner <nadavkaner1@gmail.com>
Naoki Kanatani <k12naoki@gmail.com>
Nathan VanBenschoten <nvanbenschoten@gmail.com>
Navaneeth Suresh <navaneeths1998@gmail.com>
Neal Caffery <neal1991@sina.com>
Neil O'Toole <neilotoole@apache.org>
Nick Miyake <nmiyake@palantir.com>
Nick Platt <hello@nickplatt.co.uk>
Nick Spragg <nick.spragg@bbc.co.uk>
Nicolas Chapurlat <nc@coorganix.com>
Nikhita Raghunath <nikitaraghunath@gmail.com>
Nilesh Singh <nilesh.singh24@outlook.com>
Noah Hanjun Lee <noah.lee@buzzvil.com>
Noah Zoschke <noah+sso2@convox.com>
ns-cweber <cweber@narrativescience.com>
nxya <nathacutlan@gmail.com>
Ole Orhagen <ole.orhagen@northern.tech>
Oleg Kovalov <iamolegkovalov@gmail.com>
Ondřej Kupka <ondra.cap@gmail.com>
Ori Talmor <talmorori@gmail.com>
Osama Faqhruldin <onfaqhru@gmail.com>
oslowalk <den.cs@pm.me>
Pablo Pérez Schröder <pablo.perezschroder@wetransfer.com>
Palash Nigam <npalash25@gmail.com>
Panagiotis Moustafellos <pmoust@gmail.com>
Parham Alvani <parham.alvani@gmail.com>
pari-27 <sonamajumdar2012@gmail.com>
Parker Moore <parkrmoore@gmail.com>
parkhyukjun89 <park.hyukjun89@gmail.com>
Pat Alwell <pat.alwell@gmail.com>
Patrick DeVivo <patrick.devivo@gmail.com>
Patrick Marabeas <patrick@marabeas.io>
Patrik Nordlén <patriki@gmail.com>
Pavel Dvoinos <pavel.dvoinos@transferwise.com>
Pavel Shtanko <pavel.shtanko@gmail.com>
Pete Wagner <thepwagner@github.com>
Petr Shevtsov <petr.shevtsov@gmail.com>
Pierce McEntagart <pierce@nightfall.ai>
Pierre Carrier <pierre@meteor.com>
Piotr Zurek <p.zurek@gmail.com>
Piyush Chugh <piyushchugh1993@gmail.com>
Pratik Mallya <pratik.mallya@gmail.com>
Qais Patankar <qaisjp@gmail.com>
Quang Le Hong <iamquang95@gmail.com>
Quentin Leffray <fiahil@gmail.com>
Quinn Slack <qslack@qslack.com>
Rackspace US, Inc.
Radek Simko <radek.simko@gmail.com>
Radliński Ignacy <radlinsk@student.agh.edu.pl>
Rafael Aramizu Gomes <rafael.aramizu@mercadolivre.com>
Rajat Jindal <rajatjindal83@gmail.com>
Rajendra arora <rajendraarora16@yahoo.com>
Rajkumar <princegosavi12@gmail.com>
Ranbir Singh <binkkatal.r@gmail.com>
Ravi Shekhar Jethani <rsjethani@gmail.com>
RaviTeja Pothana <ravi-teja@live.com>
rc1140 <jameel@republiccommandos.co.za>
Red Hat, Inc.
Reetuparna Mukherjee <reetuparna.1988@gmail.com>
reeves122 <reeves122@gmail.com>
Reinier Timmer <reinier.timmer@ah.nl>
Renjith R <renjithr201097@gmail.com>
Ricco Førgaard <ricco@fiskeben.dk>
Richard de Vries <richard.de.vries@topicus.nl>
Rob Figueiredo <robfig@yext.com>
Rohit Upadhyay <urohit011@gmail.com>
Rojan Dinc <rojand94@gmail.com>
Ronak Jain <ronakjain@outlook.in>
Ronan Pelliard <ronan.pelliard@datadoghq.com>
Ross Gustafson <srgustafson8@icloud.com>
Ruben Vereecken <rubenvereecken@gmail.com>
Russell Boley <raboley@gmail.com>
Ryan Leung <rleungx@gmail.com>
Ryan Lower <rpjlower@gmail.com>
Ryo Nakao <nakabonne@gmail.com>
Saaarah <sarah.liusy@gmail.com>
Safwan Olaimat <safwan.olaimat@gmail.com>
Sahil Dua <sahildua2305@gmail.com>
Sai Ravi Teja Chintakrindi <srt2712@gmail.com>
saisi <saisi@users.noreply.github.com>
Sam Minnée <sam@silverstripe.com>
Sandeep Sukhani <sandeep.d.sukhani@gmail.com>
Sander Knape <s.knape88@gmail.com>
Sander van Harmelen <svanharmelen@schubergphilis.com>
Sanket Payghan <sanket.payghan8@gmail.com>
Sarah Funkhouser <sarah.k.funkhouser@gmail.com>
Sarasa Kisaragi <lingsamuelgrace@gmail.com>
Sasha Melentyev <sasha@melentyev.io>
Sean Wang <sean@decrypted.org>
Sebastian Mandrean <sebastian.mandrean@gmail.com>
Sebastian Mæland Pedersen <sem.pedersen@stud.uis.no>
Sergei Popinevskii <gurza000@gmail.com>
Sergey Romanov <xxsmotur@gmail.com>
Sergio Garcia <sergio.garcia@gmail.com>
Seth Vargo <seth@sethvargo.com>
Sevki <s@sevki.org>
Shagun Khemka <shagun.khemka60@gmail.com>
shakeelrao <shakeelrao79@gmail.com>
Shawn Catanzarite <me@shawncatz.com>
Shawn Smith <shawnpsmith@gmail.com>
Shibasis Patel <patelshibasis@gmail.com>
Sho Okada <shokada3@gmail.com>
Shrikrishna Singh <krishnasingh.ss30@gmail.com>
Simon Davis <sdavis@hashicorp.com>
sona-tar <sona.zip@gmail.com>
soniachikh <sonia.chikh@gmail.com>
SoundCloud, Ltd.
Sridhar Mocherla <srmocher@microsoft.com>
SriVignessh Pss <sriknowledge@gmail.com>
Stefan Sedich <stefan.sedich@gmail.com>
Steve Teuber <github@steveteuber.com>
Stian Eikeland <stian@eikeland.se>
Suhaib Mujahid <suhaibmujahid@gmail.com>
sushmita wable <sw09007@gmail.com>
Szymon Kodrebski <simonkey007@gmail.com>
Søren Hansen <soren@dinero.dk>
T.J. Corrigan <tjcorr@github.com>
Takashi Yoneuchi <takashi.yoneuchi@shift-js.info>
Takayuki Watanabe <takanabe.w@gmail.com>
Taketoshi Fujiwara <fujiwara@leapmind.io>
Taketoshi Fujiwara <taketoshi.fujiwara@gmail.com>
Takuma Kajikawa <kj1ktk@gmail.com>
Tasya Aditya Rukmana <tadityar@gmail.com>
Theo Henson <theodorehenson@protonmail.com>
Theofilos Petsios <theofilos.pe@gmail.com>
Thomas Aidan Curran <thomas@ory.sh>
Thomas Bruyelle <thomas.bruyelle@gmail.com>
Tim Rogers <timrogers@github.com>
Timothy O'Brien <obrien.timothy.a@gmail.com>
Timothée Peignier <timothee.peignier@tryphon.org>
Tingluo Huang <tingluohuang@github.com>
tkhandel <tarunkhandelwal.iitr@gmail.com>
Tobias Gesellchen <tobias@gesellix.de>
Tom Payne <twpayne@gmail.com>
Trey Tacon <ttacon@gmail.com>
tsbkw <tsbkw0@gmail.com>
ttacon <ttacon@gmail.com>
Vaibhav Singh <vaibhav.singh.14cse@bml.edu.in>
Varadarajan Aravamudhan <varadaraajan@gmail.com>
Victor Castell <victor@victorcastell.com>
Victor Vrantchan <vrancean+github@gmail.com>
Victory Osikwemhe <osikwemhev@gmail.com>
vikkyomkar <vikky.omkar@samsung.com>
Vivek <y.vivekanand@gmail.com>
Vlad Ungureanu <vladu@palantir.com>
Wasim Thabraze <wasim@thabraze.me>
Weslei Juan Moser Pereira <wesleimsr@gmail.com>
Wheeler Law <wheeler.law@outlook.com>
Will Maier <wcmaier@gmail.com>
Will Norris <will@tailscale.com>
Willem D'Haeseleer <dhwillem@gmail.com>
William Bailey <mail@williambailey.org.uk>
William Cooke <pipeston@gmail.com>
Xabi <xmartinez1702@gmail.com>
xibz <impactbchang@gmail.com>
Yann Malet <yann.malet@gmail.com>
Yannick Utard <yannickutard@gmail.com>
Yarden Shoham <git@yardenshoham.com>
Yicheng Qin <qycqycqycqycqyc@gmail.com>
Yosuke Akatsuka <yosuke.akatsuka@access-company.com>
Yumikiyo Osanai <yumios.art@gmail.com>
Yurii Soldak <ysoldak@gmail.com>
Yusef Mohamadi <yuseferi@gmail.com>
Yusuke Kuoka <ykuoka@gmail.com>
Zach Latta <zach@zachlatta.com>
zhouhaibing089 <zhouhaibing089@gmail.com>
六开箱 <lkxed@outlook.com>
缘生 <i@ysicing.me>
蒋航 <hang.jiang@daocloud.io>

View file

@ -1,167 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"net/http"
"net/url"
)
// ArtifactWorkflowRun represents a GitHub artifact's workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts
type ArtifactWorkflowRun struct {
ID *int64 `json:"id,omitempty"`
RepositoryID *int64 `json:"repository_id,omitempty"`
HeadRepositoryID *int64 `json:"head_repository_id,omitempty"`
HeadBranch *string `json:"head_branch,omitempty"`
HeadSHA *string `json:"head_sha,omitempty"`
}
// Artifact represents a GitHub artifact. Artifacts allow sharing
// data between jobs in a workflow and provide storage for data
// once a workflow is complete.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts
type Artifact struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
Name *string `json:"name,omitempty"`
SizeInBytes *int64 `json:"size_in_bytes,omitempty"`
URL *string `json:"url,omitempty"`
ArchiveDownloadURL *string `json:"archive_download_url,omitempty"`
Expired *bool `json:"expired,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
WorkflowRun *ArtifactWorkflowRun `json:"workflow_run,omitempty"`
}
// ArtifactList represents a list of GitHub artifacts.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#artifacts
type ArtifactList struct {
TotalCount *int64 `json:"total_count,omitempty"`
Artifacts []*Artifact `json:"artifacts,omitempty"`
}
// ListArtifacts lists all artifacts that belong to a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#list-artifacts-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/artifacts
func (s *ActionsService) ListArtifacts(ctx context.Context, owner, repo string, opts *ListOptions) (*ArtifactList, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/artifacts", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
artifactList := new(ArtifactList)
resp, err := s.client.Do(ctx, req, artifactList)
if err != nil {
return nil, resp, err
}
return artifactList, resp, nil
}
// ListWorkflowRunArtifacts lists all artifacts that belong to a workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#list-workflow-run-artifacts
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts
func (s *ActionsService) ListWorkflowRunArtifacts(ctx context.Context, owner, repo string, runID int64, opts *ListOptions) (*ArtifactList, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/artifacts", owner, repo, runID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
artifactList := new(ArtifactList)
resp, err := s.client.Do(ctx, req, artifactList)
if err != nil {
return nil, resp, err
}
return artifactList, resp, nil
}
// GetArtifact gets a specific artifact for a workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#get-an-artifact
//
//meta:operation GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}
func (s *ActionsService) GetArtifact(ctx context.Context, owner, repo string, artifactID int64) (*Artifact, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/artifacts/%v", owner, repo, artifactID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
artifact := new(Artifact)
resp, err := s.client.Do(ctx, req, artifact)
if err != nil {
return nil, resp, err
}
return artifact, resp, nil
}
// DownloadArtifact gets a redirect URL to download an archive for a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#download-an-artifact
//
//meta:operation GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}
func (s *ActionsService) DownloadArtifact(ctx context.Context, owner, repo string, artifactID int64, maxRedirects int) (*url.URL, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/artifacts/%v/zip", owner, repo, artifactID)
resp, err := s.client.roundTripWithOptionalFollowRedirect(ctx, u, maxRedirects)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status)
}
parsedURL, err := url.Parse(resp.Header.Get("Location"))
if err != nil {
return nil, newResponse(resp), err
}
return parsedURL, newResponse(resp), nil
}
// DeleteArtifact deletes a workflow run artifact.
//
// GitHub API docs: https://docs.github.com/rest/actions/artifacts#delete-an-artifact
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}
func (s *ActionsService) DeleteArtifact(ctx context.Context, owner, repo string, artifactID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/artifacts/%v", owner, repo, artifactID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,249 +0,0 @@
// Copyright 2022 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ActionsCache represents a GitHub action cache.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#about-the-cache-api
type ActionsCache struct {
ID *int64 `json:"id,omitempty" url:"-"`
Ref *string `json:"ref,omitempty" url:"ref"`
Key *string `json:"key,omitempty" url:"key"`
Version *string `json:"version,omitempty" url:"-"`
LastAccessedAt *Timestamp `json:"last_accessed_at,omitempty" url:"-"`
CreatedAt *Timestamp `json:"created_at,omitempty" url:"-"`
SizeInBytes *int64 `json:"size_in_bytes,omitempty" url:"-"`
}
// ActionsCacheList represents a list of GitHub actions Cache.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#list-github-actions-caches-for-a-repository
type ActionsCacheList struct {
TotalCount int `json:"total_count"`
ActionsCaches []*ActionsCache `json:"actions_caches,omitempty"`
}
// ActionsCacheUsage represents a GitHub Actions Cache Usage object.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#get-github-actions-cache-usage-for-a-repository
type ActionsCacheUsage struct {
FullName string `json:"full_name"`
ActiveCachesSizeInBytes int64 `json:"active_caches_size_in_bytes"`
ActiveCachesCount int `json:"active_caches_count"`
}
// ActionsCacheUsageList represents a list of repositories with GitHub Actions cache usage for an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#get-github-actions-cache-usage-for-a-repository
type ActionsCacheUsageList struct {
TotalCount int `json:"total_count"`
RepoCacheUsage []*ActionsCacheUsage `json:"repository_cache_usages,omitempty"`
}
// TotalCacheUsage represents total GitHub actions cache usage of an organization or enterprise.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#get-github-actions-cache-usage-for-an-enterprise
type TotalCacheUsage struct {
TotalActiveCachesUsageSizeInBytes int64 `json:"total_active_caches_size_in_bytes"`
TotalActiveCachesCount int `json:"total_active_caches_count"`
}
// ActionsCacheListOptions represents a list of all possible optional Query parameters for ListCaches method.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#list-github-actions-caches-for-a-repository
type ActionsCacheListOptions struct {
ListOptions
// The Git reference for the results you want to list.
// The ref for a branch can be formatted either as refs/heads/<branch name>
// or simply <branch name>. To reference a pull request use refs/pull/<number>/merge
Ref *string `url:"ref,omitempty"`
Key *string `url:"key,omitempty"`
// Can be one of: "created_at", "last_accessed_at", "size_in_bytes". Default: "last_accessed_at"
Sort *string `url:"sort,omitempty"`
// Can be one of: "asc", "desc" Default: desc
Direction *string `url:"direction,omitempty"`
}
// ListCaches lists the GitHub Actions caches for a repository.
// You must authenticate using an access token with the repo scope to use this endpoint.
//
// Permissions: must have the actions:read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#list-github-actions-caches-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/caches
func (s *ActionsService) ListCaches(ctx context.Context, owner, repo string, opts *ActionsCacheListOptions) (*ActionsCacheList, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/caches", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
actionCacheList := new(ActionsCacheList)
resp, err := s.client.Do(ctx, req, actionCacheList)
if err != nil {
return nil, resp, err
}
return actionCacheList, resp, nil
}
// DeleteCachesByKey deletes one or more GitHub Actions caches for a repository, using a complete cache key.
// By default, all caches that match the provided key are deleted, but you can optionally provide
// a Git ref to restrict deletions to caches that match both the provided key and the Git ref.
// The ref for a branch can be formatted either as "refs/heads/<branch name>" or simply "<branch name>".
// To reference a pull request use "refs/pull/<number>/merge". If you don't want to use ref just pass nil in parameter.
//
// Permissions: You must authenticate using an access token with the repo scope to use this endpoint. GitHub Apps must have the actions:write permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#delete-github-actions-caches-for-a-repository-using-a-cache-key
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/caches
func (s *ActionsService) DeleteCachesByKey(ctx context.Context, owner, repo, key string, ref *string) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/caches", owner, repo)
u, err := addOptions(u, ActionsCache{Key: &key, Ref: ref})
if err != nil {
return nil, err
}
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// DeleteCachesByID deletes a GitHub Actions cache for a repository, using a cache ID.
//
// Permissions: You must authenticate using an access token with the repo scope to use this endpoint. GitHub Apps must have the actions:write permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#delete-a-github-actions-cache-for-a-repository-using-a-cache-id
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}
func (s *ActionsService) DeleteCachesByID(ctx context.Context, owner, repo string, cacheID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/caches/%v", owner, repo, cacheID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// GetCacheUsageForRepo gets GitHub Actions cache usage for a repository. The data fetched using this API is refreshed approximately every 5 minutes,
// so values returned from this endpoint may take at least 5 minutes to get updated.
//
// Permissions: Anyone with read access to the repository can use this endpoint. If the repository is private, you must use an
// access token with the repo scope. GitHub Apps must have the actions:read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#get-github-actions-cache-usage-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/cache/usage
func (s *ActionsService) GetCacheUsageForRepo(ctx context.Context, owner, repo string) (*ActionsCacheUsage, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/cache/usage", owner, repo)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
cacheUsage := new(ActionsCacheUsage)
res, err := s.client.Do(ctx, req, cacheUsage)
if err != nil {
return nil, res, err
}
return cacheUsage, res, err
}
// ListCacheUsageByRepoForOrg lists repositories and their GitHub Actions cache usage for an organization. The data fetched using this API is
// refreshed approximately every 5 minutes, so values returned from this endpoint may take at least 5 minutes to get updated.
//
// Permissions: You must authenticate using an access token with the read:org scope to use this endpoint.
// GitHub Apps must have the organization_admistration:read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#list-repositories-with-github-actions-cache-usage-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/cache/usage-by-repository
func (s *ActionsService) ListCacheUsageByRepoForOrg(ctx context.Context, org string, opts *ListOptions) (*ActionsCacheUsageList, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/cache/usage-by-repository", org)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
cacheUsage := new(ActionsCacheUsageList)
res, err := s.client.Do(ctx, req, cacheUsage)
if err != nil {
return nil, res, err
}
return cacheUsage, res, err
}
// GetTotalCacheUsageForOrg gets the total GitHub Actions cache usage for an organization. The data fetched using this API is refreshed approximately every
// 5 minutes, so values returned from this endpoint may take at least 5 minutes to get updated.
//
// Permissions: You must authenticate using an access token with the read:org scope to use this endpoint.
// GitHub Apps must have the organization_admistration:read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/actions/cache#get-github-actions-cache-usage-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/cache/usage
func (s *ActionsService) GetTotalCacheUsageForOrg(ctx context.Context, org string) (*TotalCacheUsage, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/cache/usage", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
cacheUsage := new(TotalCacheUsage)
res, err := s.client.Do(ctx, req, cacheUsage)
if err != nil {
return nil, res, err
}
return cacheUsage, res, err
}
// GetTotalCacheUsageForEnterprise gets the total GitHub Actions cache usage for an enterprise. The data fetched using this API is refreshed approximately every 5 minutes,
// so values returned from this endpoint may take at least 5 minutes to get updated.
//
// Permissions: You must authenticate using an access token with the "admin:enterprise" scope to use this endpoint.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/cache#get-github-actions-cache-usage-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/cache/usage
func (s *ActionsService) GetTotalCacheUsageForEnterprise(ctx context.Context, enterprise string) (*TotalCacheUsage, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/cache/usage", enterprise)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
cacheUsage := new(TotalCacheUsage)
res, err := s.client.Do(ctx, req, cacheUsage)
if err != nil {
return nil, res, err
}
return cacheUsage, res, err
}

View file

@ -1,207 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ActionsEnabledOnEnterpriseRepos represents all the repositories in an enterprise for which Actions is enabled.
type ActionsEnabledOnEnterpriseRepos struct {
TotalCount int `json:"total_count"`
Organizations []*Organization `json:"organizations"`
}
// ActionsPermissionsEnterprise represents a policy for allowed actions in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions
type ActionsPermissionsEnterprise struct {
EnabledOrganizations *string `json:"enabled_organizations,omitempty"`
AllowedActions *string `json:"allowed_actions,omitempty"`
SelectedActionsURL *string `json:"selected_actions_url,omitempty"`
}
func (a ActionsPermissionsEnterprise) String() string {
return Stringify(a)
}
// GetActionsPermissionsInEnterprise gets the GitHub Actions permissions policy for an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#get-github-actions-permissions-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/permissions
func (s *ActionsService) GetActionsPermissionsInEnterprise(ctx context.Context, enterprise string) (*ActionsPermissionsEnterprise, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions", enterprise)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
permissions := new(ActionsPermissionsEnterprise)
resp, err := s.client.Do(ctx, req, permissions)
if err != nil {
return nil, resp, err
}
return permissions, resp, nil
}
// EditActionsPermissionsInEnterprise sets the permissions policy in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#set-github-actions-permissions-for-an-enterprise
//
//meta:operation PUT /enterprises/{enterprise}/actions/permissions
func (s *ActionsService) EditActionsPermissionsInEnterprise(ctx context.Context, enterprise string, actionsPermissionsEnterprise ActionsPermissionsEnterprise) (*ActionsPermissionsEnterprise, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions", enterprise)
req, err := s.client.NewRequest("PUT", u, actionsPermissionsEnterprise)
if err != nil {
return nil, nil, err
}
p := new(ActionsPermissionsEnterprise)
resp, err := s.client.Do(ctx, req, p)
if err != nil {
return nil, resp, err
}
return p, resp, nil
}
// ListEnabledOrgsInEnterprise lists the selected organizations that are enabled for GitHub Actions in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#list-selected-organizations-enabled-for-github-actions-in-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/permissions/organizations
func (s *ActionsService) ListEnabledOrgsInEnterprise(ctx context.Context, owner string, opts *ListOptions) (*ActionsEnabledOnEnterpriseRepos, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/organizations", owner)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
orgs := &ActionsEnabledOnEnterpriseRepos{}
resp, err := s.client.Do(ctx, req, orgs)
if err != nil {
return nil, resp, err
}
return orgs, resp, nil
}
// SetEnabledOrgsInEnterprise replaces the list of selected organizations that are enabled for GitHub Actions in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#set-selected-organizations-enabled-for-github-actions-in-an-enterprise
//
//meta:operation PUT /enterprises/{enterprise}/actions/permissions/organizations
func (s *ActionsService) SetEnabledOrgsInEnterprise(ctx context.Context, owner string, organizationIDs []int64) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/organizations", owner)
req, err := s.client.NewRequest("PUT", u, struct {
IDs []int64 `json:"selected_organization_ids"`
}{IDs: organizationIDs})
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// AddEnabledOrgInEnterprise adds an organization to the list of selected organizations that are enabled for GitHub Actions in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#enable-a-selected-organization-for-github-actions-in-an-enterprise
//
//meta:operation PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}
func (s *ActionsService) AddEnabledOrgInEnterprise(ctx context.Context, owner string, organizationID int64) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/organizations/%v", owner, organizationID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// RemoveEnabledOrgInEnterprise removes an organization from the list of selected organizations that are enabled for GitHub Actions in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#disable-a-selected-organization-for-github-actions-in-an-enterprise
//
//meta:operation DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}
func (s *ActionsService) RemoveEnabledOrgInEnterprise(ctx context.Context, owner string, organizationID int64) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/organizations/%v", owner, organizationID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// GetActionsAllowedInEnterprise gets the actions that are allowed in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/permissions/selected-actions
func (s *ActionsService) GetActionsAllowedInEnterprise(ctx context.Context, enterprise string) (*ActionsAllowed, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/selected-actions", enterprise)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
actionsAllowed := new(ActionsAllowed)
resp, err := s.client.Do(ctx, req, actionsAllowed)
if err != nil {
return nil, resp, err
}
return actionsAllowed, resp, nil
}
// EditActionsAllowedInEnterprise sets the actions that are allowed in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/permissions#set-allowed-actions-and-reusable-workflows-for-an-enterprise
//
//meta:operation PUT /enterprises/{enterprise}/actions/permissions/selected-actions
func (s *ActionsService) EditActionsAllowedInEnterprise(ctx context.Context, enterprise string, actionsAllowed ActionsAllowed) (*ActionsAllowed, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/permissions/selected-actions", enterprise)
req, err := s.client.NewRequest("PUT", u, actionsAllowed)
if err != nil {
return nil, nil, err
}
p := new(ActionsAllowed)
resp, err := s.client.Do(ctx, req, p)
if err != nil {
return nil, resp, err
}
return p, resp, nil
}

View file

@ -1,220 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ActionsPermissions represents a policy for repositories and allowed actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions
type ActionsPermissions struct {
EnabledRepositories *string `json:"enabled_repositories,omitempty"`
AllowedActions *string `json:"allowed_actions,omitempty"`
SelectedActionsURL *string `json:"selected_actions_url,omitempty"`
}
func (a ActionsPermissions) String() string {
return Stringify(a)
}
// ActionsEnabledOnOrgRepos represents all the repositories in an organization for which Actions is enabled.
type ActionsEnabledOnOrgRepos struct {
TotalCount int `json:"total_count"`
Repositories []*Repository `json:"repositories"`
}
// ActionsAllowed represents selected actions that are allowed.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions
type ActionsAllowed struct {
GithubOwnedAllowed *bool `json:"github_owned_allowed,omitempty"`
VerifiedAllowed *bool `json:"verified_allowed,omitempty"`
PatternsAllowed []string `json:"patterns_allowed,omitempty"`
}
func (a ActionsAllowed) String() string {
return Stringify(a)
}
// GetActionsPermissions gets the GitHub Actions permissions policy for repositories and allowed actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#get-github-actions-permissions-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/permissions
func (s *ActionsService) GetActionsPermissions(ctx context.Context, org string) (*ActionsPermissions, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
permissions := new(ActionsPermissions)
resp, err := s.client.Do(ctx, req, permissions)
if err != nil {
return nil, resp, err
}
return permissions, resp, nil
}
// EditActionsPermissions sets the permissions policy for repositories and allowed actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#set-github-actions-permissions-for-an-organization
//
//meta:operation PUT /orgs/{org}/actions/permissions
func (s *ActionsService) EditActionsPermissions(ctx context.Context, org string, actionsPermissions ActionsPermissions) (*ActionsPermissions, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions", org)
req, err := s.client.NewRequest("PUT", u, actionsPermissions)
if err != nil {
return nil, nil, err
}
p := new(ActionsPermissions)
resp, err := s.client.Do(ctx, req, p)
if err != nil {
return nil, resp, err
}
return p, resp, nil
}
// ListEnabledReposInOrg lists the selected repositories that are enabled for GitHub Actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization
//
//meta:operation GET /orgs/{org}/actions/permissions/repositories
func (s *ActionsService) ListEnabledReposInOrg(ctx context.Context, owner string, opts *ListOptions) (*ActionsEnabledOnOrgRepos, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/repositories", owner)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
repos := &ActionsEnabledOnOrgRepos{}
resp, err := s.client.Do(ctx, req, repos)
if err != nil {
return nil, resp, err
}
return repos, resp, nil
}
// SetEnabledReposInOrg replaces the list of selected repositories that are enabled for GitHub Actions in an organization..
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#set-selected-repositories-enabled-for-github-actions-in-an-organization
//
//meta:operation PUT /orgs/{org}/actions/permissions/repositories
func (s *ActionsService) SetEnabledReposInOrg(ctx context.Context, owner string, repositoryIDs []int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/repositories", owner)
req, err := s.client.NewRequest("PUT", u, struct {
IDs []int64 `json:"selected_repository_ids"`
}{IDs: repositoryIDs})
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// AddEnabledReposInOrg adds a repository to the list of selected repositories that are enabled for GitHub Actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#enable-a-selected-repository-for-github-actions-in-an-organization
//
//meta:operation PUT /orgs/{org}/actions/permissions/repositories/{repository_id}
func (s *ActionsService) AddEnabledReposInOrg(ctx context.Context, owner string, repositoryID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/repositories/%v", owner, repositoryID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// RemoveEnabledReposInOrg removes a single repository from the list of enabled repos for GitHub Actions in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#disable-a-selected-repository-for-github-actions-in-an-organization
//
//meta:operation DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}
func (s *ActionsService) RemoveEnabledReposInOrg(ctx context.Context, owner string, repositoryID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/repositories/%v", owner, repositoryID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// GetActionsAllowed gets the actions that are allowed in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/permissions/selected-actions
func (s *ActionsService) GetActionsAllowed(ctx context.Context, org string) (*ActionsAllowed, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/selected-actions", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
actionsAllowed := new(ActionsAllowed)
resp, err := s.client.Do(ctx, req, actionsAllowed)
if err != nil {
return nil, resp, err
}
return actionsAllowed, resp, nil
}
// EditActionsAllowed sets the actions that are allowed in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/permissions#set-allowed-actions-and-reusable-workflows-for-an-organization
//
//meta:operation PUT /orgs/{org}/actions/permissions/selected-actions
func (s *ActionsService) EditActionsAllowed(ctx context.Context, org string, actionsAllowed ActionsAllowed) (*ActionsAllowed, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/permissions/selected-actions", org)
req, err := s.client.NewRequest("PUT", u, actionsAllowed)
if err != nil {
return nil, nil, err
}
p := new(ActionsAllowed)
resp, err := s.client.Do(ctx, req, p)
if err != nil {
return nil, resp, err
}
return p, resp, nil
}

View file

@ -1,267 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// OrgRequiredWorkflow represents a required workflow object at the org level.
type OrgRequiredWorkflow struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Path *string `json:"path,omitempty"`
Scope *string `json:"scope,omitempty"`
Ref *string `json:"ref,omitempty"`
State *string `json:"state,omitempty"`
SelectedRepositoriesURL *string `json:"selected_repositories_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Repository *Repository `json:"repository,omitempty"`
}
// OrgRequiredWorkflows represents the required workflows for the org.
type OrgRequiredWorkflows struct {
TotalCount *int `json:"total_count,omitempty"`
RequiredWorkflows []*OrgRequiredWorkflow `json:"required_workflows,omitempty"`
}
// CreateUpdateRequiredWorkflowOptions represents the input object used to create or update required workflows.
type CreateUpdateRequiredWorkflowOptions struct {
WorkflowFilePath *string `json:"workflow_file_path,omitempty"`
RepositoryID *int64 `json:"repository_id,omitempty"`
Scope *string `json:"scope,omitempty"`
SelectedRepositoryIDs *SelectedRepoIDs `json:"selected_repository_ids,omitempty"`
}
// RequiredWorkflowSelectedRepos represents the repos that a required workflow is applied to.
type RequiredWorkflowSelectedRepos struct {
TotalCount *int `json:"total_count,omitempty"`
Repositories []*Repository `json:"repositories,omitempty"`
}
// RepoRequiredWorkflow represents a required workflow object at the repo level.
type RepoRequiredWorkflow struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
Name *string `json:"name,omitempty"`
Path *string `json:"path,omitempty"`
State *string `json:"state,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
BadgeURL *string `json:"badge_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
SourceRepository *Repository `json:"source_repository,omitempty"`
}
// RepoRequiredWorkflows represents the required workflows for a repo.
type RepoRequiredWorkflows struct {
TotalCount *int `json:"total_count,omitempty"`
RequiredWorkflows []*RepoRequiredWorkflow `json:"required_workflows,omitempty"`
}
// ListOrgRequiredWorkflows lists the RequiredWorkflows for an org.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation GET /orgs/{org}/actions/required_workflows
func (s *ActionsService) ListOrgRequiredWorkflows(ctx context.Context, org string, opts *ListOptions) (*OrgRequiredWorkflows, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows", org)
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
requiredWorkflows := new(OrgRequiredWorkflows)
resp, err := s.client.Do(ctx, req, &requiredWorkflows)
if err != nil {
return nil, resp, err
}
return requiredWorkflows, resp, nil
}
// CreateRequiredWorkflow creates the required workflow in an org.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation POST /orgs/{org}/actions/required_workflows
func (s *ActionsService) CreateRequiredWorkflow(ctx context.Context, org string, createRequiredWorkflowOptions *CreateUpdateRequiredWorkflowOptions) (*OrgRequiredWorkflow, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows", org)
req, err := s.client.NewRequest("POST", url, createRequiredWorkflowOptions)
if err != nil {
return nil, nil, err
}
orgRequiredWorkflow := new(OrgRequiredWorkflow)
resp, err := s.client.Do(ctx, req, orgRequiredWorkflow)
if err != nil {
return nil, resp, err
}
return orgRequiredWorkflow, resp, nil
}
// GetRequiredWorkflowByID get the RequiredWorkflows for an org by its ID.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation GET /orgs/{org}/actions/required_workflows/{workflow_id}
func (s *ActionsService) GetRequiredWorkflowByID(ctx context.Context, owner string, requiredWorkflowID int64) (*OrgRequiredWorkflow, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/required_workflows/%v", owner, requiredWorkflowID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
requiredWorkflow := new(OrgRequiredWorkflow)
resp, err := s.client.Do(ctx, req, &requiredWorkflow)
if err != nil {
return nil, resp, err
}
return requiredWorkflow, resp, nil
}
// UpdateRequiredWorkflow updates a required workflow in an org.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation PATCH /orgs/{org}/actions/required_workflows/{workflow_id}
func (s *ActionsService) UpdateRequiredWorkflow(ctx context.Context, org string, requiredWorkflowID int64, updateRequiredWorkflowOptions *CreateUpdateRequiredWorkflowOptions) (*OrgRequiredWorkflow, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v", org, requiredWorkflowID)
req, err := s.client.NewRequest("PATCH", url, updateRequiredWorkflowOptions)
if err != nil {
return nil, nil, err
}
orgRequiredWorkflow := new(OrgRequiredWorkflow)
resp, err := s.client.Do(ctx, req, orgRequiredWorkflow)
if err != nil {
return nil, resp, err
}
return orgRequiredWorkflow, resp, nil
}
// DeleteRequiredWorkflow deletes a required workflow in an org.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation DELETE /orgs/{org}/actions/required_workflows/{workflow_id}
func (s *ActionsService) DeleteRequiredWorkflow(ctx context.Context, org string, requiredWorkflowID int64) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v", org, requiredWorkflowID)
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// ListRequiredWorkflowSelectedRepos lists the Repositories selected for a workflow.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation GET /orgs/{org}/actions/required_workflows/{workflow_id}/repositories
func (s *ActionsService) ListRequiredWorkflowSelectedRepos(ctx context.Context, org string, requiredWorkflowID int64, opts *ListOptions) (*RequiredWorkflowSelectedRepos, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v/repositories", org, requiredWorkflowID)
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
requiredWorkflowRepos := new(RequiredWorkflowSelectedRepos)
resp, err := s.client.Do(ctx, req, &requiredWorkflowRepos)
if err != nil {
return nil, resp, err
}
return requiredWorkflowRepos, resp, nil
}
// SetRequiredWorkflowSelectedRepos sets the Repositories selected for a workflow.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation PUT /orgs/{org}/actions/required_workflows/{workflow_id}/repositories
func (s *ActionsService) SetRequiredWorkflowSelectedRepos(ctx context.Context, org string, requiredWorkflowID int64, ids SelectedRepoIDs) (*Response, error) {
type repoIDs struct {
SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"`
}
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v/repositories", org, requiredWorkflowID)
req, err := s.client.NewRequest("PUT", url, repoIDs{SelectedIDs: ids})
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AddRepoToRequiredWorkflow adds the Repository to a required workflow.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation PUT /orgs/{org}/actions/required_workflows/{workflow_id}/repositories/{repository_id}
func (s *ActionsService) AddRepoToRequiredWorkflow(ctx context.Context, org string, requiredWorkflowID, repoID int64) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v/repositories/%v", org, requiredWorkflowID, repoID)
req, err := s.client.NewRequest("PUT", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RemoveRepoFromRequiredWorkflow removes the Repository from a required workflow.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation DELETE /orgs/{org}/actions/required_workflows/{workflow_id}/repositories/{repository_id}
func (s *ActionsService) RemoveRepoFromRequiredWorkflow(ctx context.Context, org string, requiredWorkflowID, repoID int64) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/required_workflows/%v/repositories/%v", org, requiredWorkflowID, repoID)
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// ListRepoRequiredWorkflows lists the RequiredWorkflows for a repo.
//
// GitHub API docs: https://docs.github.com/actions/using-workflows/required-workflows
//
//meta:operation GET /repos/{owner}/{repo}/actions/required_workflows
func (s *ActionsService) ListRepoRequiredWorkflows(ctx context.Context, owner, repo string, opts *ListOptions) (*RepoRequiredWorkflows, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/required_workflows", owner, repo)
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
requiredWorkflows := new(RepoRequiredWorkflows)
resp, err := s.client.Do(ctx, req, &requiredWorkflows)
if err != nil {
return nil, resp, err
}
return requiredWorkflows, resp, nil
}

View file

@ -1,337 +0,0 @@
// Copyright 2021 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// RunnerGroup represents a self-hosted runner group configured in an organization.
type RunnerGroup struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Visibility *string `json:"visibility,omitempty"`
Default *bool `json:"default,omitempty"`
SelectedRepositoriesURL *string `json:"selected_repositories_url,omitempty"`
RunnersURL *string `json:"runners_url,omitempty"`
Inherited *bool `json:"inherited,omitempty"`
AllowsPublicRepositories *bool `json:"allows_public_repositories,omitempty"`
RestrictedToWorkflows *bool `json:"restricted_to_workflows,omitempty"`
SelectedWorkflows []string `json:"selected_workflows,omitempty"`
WorkflowRestrictionsReadOnly *bool `json:"workflow_restrictions_read_only,omitempty"`
}
// RunnerGroups represents a collection of self-hosted runner groups configured for an organization.
type RunnerGroups struct {
TotalCount int `json:"total_count"`
RunnerGroups []*RunnerGroup `json:"runner_groups"`
}
// CreateRunnerGroupRequest represents a request to create a Runner group for an organization.
type CreateRunnerGroupRequest struct {
Name *string `json:"name,omitempty"`
Visibility *string `json:"visibility,omitempty"`
// List of repository IDs that can access the runner group.
SelectedRepositoryIDs []int64 `json:"selected_repository_ids,omitempty"`
// Runners represent a list of runner IDs to add to the runner group.
Runners []int64 `json:"runners,omitempty"`
// If set to True, public repos can use this runner group
AllowsPublicRepositories *bool `json:"allows_public_repositories,omitempty"`
// If true, the runner group will be restricted to running only the workflows specified in the SelectedWorkflows slice.
RestrictedToWorkflows *bool `json:"restricted_to_workflows,omitempty"`
// List of workflows the runner group should be allowed to run. This setting will be ignored unless RestrictedToWorkflows is set to true.
SelectedWorkflows []string `json:"selected_workflows,omitempty"`
}
// UpdateRunnerGroupRequest represents a request to update a Runner group for an organization.
type UpdateRunnerGroupRequest struct {
Name *string `json:"name,omitempty"`
Visibility *string `json:"visibility,omitempty"`
AllowsPublicRepositories *bool `json:"allows_public_repositories,omitempty"`
RestrictedToWorkflows *bool `json:"restricted_to_workflows,omitempty"`
SelectedWorkflows []string `json:"selected_workflows,omitempty"`
}
// SetRepoAccessRunnerGroupRequest represents a request to replace the list of repositories
// that can access a self-hosted runner group configured in an organization.
type SetRepoAccessRunnerGroupRequest struct {
// Updated list of repository IDs that should be given access to the runner group.
SelectedRepositoryIDs []int64 `json:"selected_repository_ids"`
}
// SetRunnerGroupRunnersRequest represents a request to replace the list of
// self-hosted runners that are part of an organization runner group.
type SetRunnerGroupRunnersRequest struct {
// Updated list of runner IDs that should be given access to the runner group.
Runners []int64 `json:"runners"`
}
// ListOrgRunnerGroupOptions extend ListOptions to have the optional parameters VisibleToRepository.
type ListOrgRunnerGroupOptions struct {
ListOptions
// Only return runner groups that are allowed to be used by this repository.
VisibleToRepository string `url:"visible_to_repository,omitempty"`
}
// ListOrganizationRunnerGroups lists all self-hosted runner groups configured in an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#list-self-hosted-runner-groups-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runner-groups
func (s *ActionsService) ListOrganizationRunnerGroups(ctx context.Context, org string, opts *ListOrgRunnerGroupOptions) (*RunnerGroups, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups", org)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
groups := &RunnerGroups{}
resp, err := s.client.Do(ctx, req, &groups)
if err != nil {
return nil, resp, err
}
return groups, resp, nil
}
// GetOrganizationRunnerGroup gets a specific self-hosted runner group for an organization using its RunnerGroup ID.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#get-a-self-hosted-runner-group-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runner-groups/{runner_group_id}
func (s *ActionsService) GetOrganizationRunnerGroup(ctx context.Context, org string, groupID int64) (*RunnerGroup, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v", org, groupID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runnerGroup := new(RunnerGroup)
resp, err := s.client.Do(ctx, req, runnerGroup)
if err != nil {
return nil, resp, err
}
return runnerGroup, resp, nil
}
// DeleteOrganizationRunnerGroup deletes a self-hosted runner group from an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#delete-a-self-hosted-runner-group-from-an-organization
//
//meta:operation DELETE /orgs/{org}/actions/runner-groups/{runner_group_id}
func (s *ActionsService) DeleteOrganizationRunnerGroup(ctx context.Context, org string, groupID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v", org, groupID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// CreateOrganizationRunnerGroup creates a new self-hosted runner group for an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#create-a-self-hosted-runner-group-for-an-organization
//
//meta:operation POST /orgs/{org}/actions/runner-groups
func (s *ActionsService) CreateOrganizationRunnerGroup(ctx context.Context, org string, createReq CreateRunnerGroupRequest) (*RunnerGroup, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups", org)
req, err := s.client.NewRequest("POST", u, createReq)
if err != nil {
return nil, nil, err
}
runnerGroup := new(RunnerGroup)
resp, err := s.client.Do(ctx, req, runnerGroup)
if err != nil {
return nil, resp, err
}
return runnerGroup, resp, nil
}
// UpdateOrganizationRunnerGroup updates a self-hosted runner group for an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#update-a-self-hosted-runner-group-for-an-organization
//
//meta:operation PATCH /orgs/{org}/actions/runner-groups/{runner_group_id}
func (s *ActionsService) UpdateOrganizationRunnerGroup(ctx context.Context, org string, groupID int64, updateReq UpdateRunnerGroupRequest) (*RunnerGroup, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v", org, groupID)
req, err := s.client.NewRequest("PATCH", u, updateReq)
if err != nil {
return nil, nil, err
}
runnerGroup := new(RunnerGroup)
resp, err := s.client.Do(ctx, req, runnerGroup)
if err != nil {
return nil, resp, err
}
return runnerGroup, resp, nil
}
// ListRepositoryAccessRunnerGroup lists the repositories with access to a self-hosted runner group configured in an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#list-repository-access-to-a-self-hosted-runner-group-in-an-organization
//
//meta:operation GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories
func (s *ActionsService) ListRepositoryAccessRunnerGroup(ctx context.Context, org string, groupID int64, opts *ListOptions) (*ListRepositories, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/repositories", org, groupID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
repos := &ListRepositories{}
resp, err := s.client.Do(ctx, req, &repos)
if err != nil {
return nil, resp, err
}
return repos, resp, nil
}
// SetRepositoryAccessRunnerGroup replaces the list of repositories that have access to a self-hosted runner group configured in an organization
// with a new List of repositories.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#set-repository-access-for-a-self-hosted-runner-group-in-an-organization
//
//meta:operation PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories
func (s *ActionsService) SetRepositoryAccessRunnerGroup(ctx context.Context, org string, groupID int64, ids SetRepoAccessRunnerGroupRequest) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/repositories", org, groupID)
req, err := s.client.NewRequest("PUT", u, ids)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AddRepositoryAccessRunnerGroup adds a repository to the list of selected repositories that can access a self-hosted runner group.
// The runner group must have visibility set to 'selected'.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#add-repository-access-to-a-self-hosted-runner-group-in-an-organization
//
//meta:operation PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}
func (s *ActionsService) AddRepositoryAccessRunnerGroup(ctx context.Context, org string, groupID, repoID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/repositories/%v", org, groupID, repoID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RemoveRepositoryAccessRunnerGroup removes a repository from the list of selected repositories that can access a self-hosted runner group.
// The runner group must have visibility set to 'selected'.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#remove-repository-access-to-a-self-hosted-runner-group-in-an-organization
//
//meta:operation DELETE /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}
func (s *ActionsService) RemoveRepositoryAccessRunnerGroup(ctx context.Context, org string, groupID, repoID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/repositories/%v", org, groupID, repoID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// ListRunnerGroupRunners lists self-hosted runners that are in a specific organization group.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#list-self-hosted-runners-in-a-group-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners
func (s *ActionsService) ListRunnerGroupRunners(ctx context.Context, org string, groupID int64, opts *ListOptions) (*Runners, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/runners", org, groupID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runners := &Runners{}
resp, err := s.client.Do(ctx, req, &runners)
if err != nil {
return nil, resp, err
}
return runners, resp, nil
}
// SetRunnerGroupRunners replaces the list of self-hosted runners that are part of an organization runner group
// with a new list of runners.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#set-self-hosted-runners-in-a-group-for-an-organization
//
//meta:operation PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/runners
func (s *ActionsService) SetRunnerGroupRunners(ctx context.Context, org string, groupID int64, ids SetRunnerGroupRunnersRequest) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/runners", org, groupID)
req, err := s.client.NewRequest("PUT", u, ids)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AddRunnerGroupRunners adds a self-hosted runner to a runner group configured in an organization.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#add-a-self-hosted-runner-to-a-group-for-an-organization
//
//meta:operation PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/runners/{runner_id}
func (s *ActionsService) AddRunnerGroupRunners(ctx context.Context, org string, groupID, runnerID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/runners/%v", org, groupID, runnerID)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RemoveRunnerGroupRunners removes a self-hosted runner from a group configured in an organization.
// The runner is then returned to the default group.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runner-groups#remove-a-self-hosted-runner-from-a-group-for-an-organization
//
//meta:operation DELETE /orgs/{org}/actions/runner-groups/{runner_group_id}/runners/{runner_id}
func (s *ActionsService) RemoveRunnerGroupRunners(ctx context.Context, org string, groupID, runnerID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runner-groups/%v/runners/%v", org, groupID, runnerID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,371 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// RunnerApplicationDownload represents a binary for the self-hosted runner application that can be downloaded.
type RunnerApplicationDownload struct {
OS *string `json:"os,omitempty"`
Architecture *string `json:"architecture,omitempty"`
DownloadURL *string `json:"download_url,omitempty"`
Filename *string `json:"filename,omitempty"`
TempDownloadToken *string `json:"temp_download_token,omitempty"`
SHA256Checksum *string `json:"sha256_checksum,omitempty"`
}
// ListRunnerApplicationDownloads lists self-hosted runner application binaries that can be downloaded and run.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#list-runner-applications-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/runners/downloads
func (s *ActionsService) ListRunnerApplicationDownloads(ctx context.Context, owner, repo string) ([]*RunnerApplicationDownload, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/downloads", owner, repo)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var rads []*RunnerApplicationDownload
resp, err := s.client.Do(ctx, req, &rads)
if err != nil {
return nil, resp, err
}
return rads, resp, nil
}
// GenerateJITConfigRequest specifies body parameters to GenerateRepoJITConfig.
type GenerateJITConfigRequest struct {
Name string `json:"name"`
RunnerGroupID int64 `json:"runner_group_id"`
WorkFolder *string `json:"work_folder,omitempty"`
// Labels represents the names of the custom labels to add to the runner.
// Minimum items: 1. Maximum items: 100.
Labels []string `json:"labels"`
}
// JITRunnerConfig represents encoded JIT configuration that can be used to bootstrap a self-hosted runner.
type JITRunnerConfig struct {
Runner *Runner `json:"runner,omitempty"`
EncodedJITConfig *string `json:"encoded_jit_config,omitempty"`
}
// GenerateOrgJITConfig generate a just-in-time configuration for an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-an-organization
//
//meta:operation POST /orgs/{org}/actions/runners/generate-jitconfig
func (s *ActionsService) GenerateOrgJITConfig(ctx context.Context, owner string, request *GenerateJITConfigRequest) (*JITRunnerConfig, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/generate-jitconfig", owner)
req, err := s.client.NewRequest("POST", u, request)
if err != nil {
return nil, nil, err
}
jitConfig := new(JITRunnerConfig)
resp, err := s.client.Do(ctx, req, jitConfig)
if err != nil {
return nil, resp, err
}
return jitConfig, resp, nil
}
// GenerateRepoJITConfig generates a just-in-time configuration for a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository
//
//meta:operation POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig
func (s *ActionsService) GenerateRepoJITConfig(ctx context.Context, owner, repo string, request *GenerateJITConfigRequest) (*JITRunnerConfig, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/generate-jitconfig", owner, repo)
req, err := s.client.NewRequest("POST", u, request)
if err != nil {
return nil, nil, err
}
jitConfig := new(JITRunnerConfig)
resp, err := s.client.Do(ctx, req, jitConfig)
if err != nil {
return nil, resp, err
}
return jitConfig, resp, nil
}
// RegistrationToken represents a token that can be used to add a self-hosted runner to a repository.
type RegistrationToken struct {
Token *string `json:"token,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
}
// CreateRegistrationToken creates a token that can be used to add a self-hosted runner.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-a-registration-token-for-a-repository
//
//meta:operation POST /repos/{owner}/{repo}/actions/runners/registration-token
func (s *ActionsService) CreateRegistrationToken(ctx context.Context, owner, repo string) (*RegistrationToken, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/registration-token", owner, repo)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
registrationToken := new(RegistrationToken)
resp, err := s.client.Do(ctx, req, registrationToken)
if err != nil {
return nil, resp, err
}
return registrationToken, resp, nil
}
// Runner represents a self-hosted runner registered with a repository.
type Runner struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
OS *string `json:"os,omitempty"`
Status *string `json:"status,omitempty"`
Busy *bool `json:"busy,omitempty"`
Labels []*RunnerLabels `json:"labels,omitempty"`
}
// RunnerLabels represents a collection of labels attached to each runner.
type RunnerLabels struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
}
// Runners represents a collection of self-hosted runners for a repository.
type Runners struct {
TotalCount int `json:"total_count"`
Runners []*Runner `json:"runners"`
}
// ListRunners lists all the self-hosted runners for a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#list-self-hosted-runners-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/runners
func (s *ActionsService) ListRunners(ctx context.Context, owner, repo string, opts *ListOptions) (*Runners, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runners := &Runners{}
resp, err := s.client.Do(ctx, req, &runners)
if err != nil {
return nil, resp, err
}
return runners, resp, nil
}
// GetRunner gets a specific self-hosted runner for a repository using its runner ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#get-a-self-hosted-runner-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/runners/{runner_id}
func (s *ActionsService) GetRunner(ctx context.Context, owner, repo string, runnerID int64) (*Runner, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/%v", owner, repo, runnerID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runner := new(Runner)
resp, err := s.client.Do(ctx, req, runner)
if err != nil {
return nil, resp, err
}
return runner, resp, nil
}
// RemoveToken represents a token that can be used to remove a self-hosted runner from a repository.
type RemoveToken struct {
Token *string `json:"token,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
}
// CreateRemoveToken creates a token that can be used to remove a self-hosted runner from a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-a-remove-token-for-a-repository
//
//meta:operation POST /repos/{owner}/{repo}/actions/runners/remove-token
func (s *ActionsService) CreateRemoveToken(ctx context.Context, owner, repo string) (*RemoveToken, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/remove-token", owner, repo)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
removeToken := new(RemoveToken)
resp, err := s.client.Do(ctx, req, removeToken)
if err != nil {
return nil, resp, err
}
return removeToken, resp, nil
}
// RemoveRunner forces the removal of a self-hosted runner in a repository using the runner id.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#delete-a-self-hosted-runner-from-a-repository
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}
func (s *ActionsService) RemoveRunner(ctx context.Context, owner, repo string, runnerID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runners/%v", owner, repo, runnerID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// ListOrganizationRunnerApplicationDownloads lists self-hosted runner application binaries that can be downloaded and run.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#list-runner-applications-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runners/downloads
func (s *ActionsService) ListOrganizationRunnerApplicationDownloads(ctx context.Context, owner string) ([]*RunnerApplicationDownload, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/downloads", owner)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var rads []*RunnerApplicationDownload
resp, err := s.client.Do(ctx, req, &rads)
if err != nil {
return nil, resp, err
}
return rads, resp, nil
}
// CreateOrganizationRegistrationToken creates a token that can be used to add a self-hosted runner to an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-a-registration-token-for-an-organization
//
//meta:operation POST /orgs/{org}/actions/runners/registration-token
func (s *ActionsService) CreateOrganizationRegistrationToken(ctx context.Context, owner string) (*RegistrationToken, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/registration-token", owner)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
registrationToken := new(RegistrationToken)
resp, err := s.client.Do(ctx, req, registrationToken)
if err != nil {
return nil, resp, err
}
return registrationToken, resp, nil
}
// ListOrganizationRunners lists all the self-hosted runners for an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#list-self-hosted-runners-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runners
func (s *ActionsService) ListOrganizationRunners(ctx context.Context, owner string, opts *ListOptions) (*Runners, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners", owner)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runners := &Runners{}
resp, err := s.client.Do(ctx, req, &runners)
if err != nil {
return nil, resp, err
}
return runners, resp, nil
}
// GetOrganizationRunner gets a specific self-hosted runner for an organization using its runner ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#get-a-self-hosted-runner-for-an-organization
//
//meta:operation GET /orgs/{org}/actions/runners/{runner_id}
func (s *ActionsService) GetOrganizationRunner(ctx context.Context, owner string, runnerID int64) (*Runner, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/%v", owner, runnerID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runner := new(Runner)
resp, err := s.client.Do(ctx, req, runner)
if err != nil {
return nil, resp, err
}
return runner, resp, nil
}
// CreateOrganizationRemoveToken creates a token that can be used to remove a self-hosted runner from an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-a-remove-token-for-an-organization
//
//meta:operation POST /orgs/{org}/actions/runners/remove-token
func (s *ActionsService) CreateOrganizationRemoveToken(ctx context.Context, owner string) (*RemoveToken, *Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/remove-token", owner)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
removeToken := new(RemoveToken)
resp, err := s.client.Do(ctx, req, removeToken)
if err != nil {
return nil, resp, err
}
return removeToken, resp, nil
}
// RemoveOrganizationRunner forces the removal of a self-hosted runner from an organization using the runner id.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#delete-a-self-hosted-runner-from-an-organization
//
//meta:operation DELETE /orgs/{org}/actions/runners/{runner_id}
func (s *ActionsService) RemoveOrganizationRunner(ctx context.Context, owner string, runnerID int64) (*Response, error) {
u := fmt.Sprintf("orgs/%v/actions/runners/%v", owner, runnerID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,396 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"encoding/json"
"fmt"
"strconv"
)
// PublicKey represents the public key that should be used to encrypt secrets.
type PublicKey struct {
KeyID *string `json:"key_id"`
Key *string `json:"key"`
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// This ensures GitHub Enterprise versions which return a numeric key id
// do not error out when unmarshaling.
func (p *PublicKey) UnmarshalJSON(data []byte) error {
var pk struct {
KeyID interface{} `json:"key_id"`
Key *string `json:"key"`
}
if err := json.Unmarshal(data, &pk); err != nil {
return err
}
p.Key = pk.Key
switch v := pk.KeyID.(type) {
case nil:
return nil
case string:
p.KeyID = &v
case float64:
p.KeyID = String(strconv.FormatFloat(v, 'f', -1, 64))
default:
return fmt.Errorf("unable to unmarshal %T as a string", v)
}
return nil
}
func (s *ActionsService) getPublicKey(ctx context.Context, url string) (*PublicKey, *Response, error) {
req, err := s.client.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
pubKey := new(PublicKey)
resp, err := s.client.Do(ctx, req, pubKey)
if err != nil {
return nil, resp, err
}
return pubKey, resp, nil
}
// GetRepoPublicKey gets a public key that should be used for secret encryption.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-a-repository-public-key
//
//meta:operation GET /repos/{owner}/{repo}/actions/secrets/public-key
func (s *ActionsService) GetRepoPublicKey(ctx context.Context, owner, repo string) (*PublicKey, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/secrets/public-key", owner, repo)
return s.getPublicKey(ctx, url)
}
// GetOrgPublicKey gets a public key that should be used for secret encryption.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-an-organization-public-key
//
//meta:operation GET /orgs/{org}/actions/secrets/public-key
func (s *ActionsService) GetOrgPublicKey(ctx context.Context, org string) (*PublicKey, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/public-key", org)
return s.getPublicKey(ctx, url)
}
// GetEnvPublicKey gets a public key that should be used for secret encryption.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-an-environment-public-key
//
//meta:operation GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key
func (s *ActionsService) GetEnvPublicKey(ctx context.Context, repoID int, env string) (*PublicKey, *Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/secrets/public-key", repoID, env)
return s.getPublicKey(ctx, url)
}
// Secret represents a repository action secret.
type Secret struct {
Name string `json:"name"`
CreatedAt Timestamp `json:"created_at"`
UpdatedAt Timestamp `json:"updated_at"`
Visibility string `json:"visibility,omitempty"`
SelectedRepositoriesURL string `json:"selected_repositories_url,omitempty"`
}
// Secrets represents one item from the ListSecrets response.
type Secrets struct {
TotalCount int `json:"total_count"`
Secrets []*Secret `json:"secrets"`
}
func (s *ActionsService) listSecrets(ctx context.Context, url string, opts *ListOptions) (*Secrets, *Response, error) {
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
secrets := new(Secrets)
resp, err := s.client.Do(ctx, req, &secrets)
if err != nil {
return nil, resp, err
}
return secrets, resp, nil
}
// ListRepoSecrets lists all secrets available in a repository
// without revealing their encrypted values.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#list-repository-secrets
//
//meta:operation GET /repos/{owner}/{repo}/actions/secrets
func (s *ActionsService) ListRepoSecrets(ctx context.Context, owner, repo string, opts *ListOptions) (*Secrets, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/secrets", owner, repo)
return s.listSecrets(ctx, url, opts)
}
// ListOrgSecrets lists all secrets available in an organization
// without revealing their encrypted values.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#list-organization-secrets
//
//meta:operation GET /orgs/{org}/actions/secrets
func (s *ActionsService) ListOrgSecrets(ctx context.Context, org string, opts *ListOptions) (*Secrets, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets", org)
return s.listSecrets(ctx, url, opts)
}
// ListEnvSecrets lists all secrets available in an environment.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#list-environment-secrets
//
//meta:operation GET /repositories/{repository_id}/environments/{environment_name}/secrets
func (s *ActionsService) ListEnvSecrets(ctx context.Context, repoID int, env string, opts *ListOptions) (*Secrets, *Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/secrets", repoID, env)
return s.listSecrets(ctx, url, opts)
}
func (s *ActionsService) getSecret(ctx context.Context, url string) (*Secret, *Response, error) {
req, err := s.client.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
secret := new(Secret)
resp, err := s.client.Do(ctx, req, secret)
if err != nil {
return nil, resp, err
}
return secret, resp, nil
}
// GetRepoSecret gets a single repository secret without revealing its encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-a-repository-secret
//
//meta:operation GET /repos/{owner}/{repo}/actions/secrets/{secret_name}
func (s *ActionsService) GetRepoSecret(ctx context.Context, owner, repo, name string) (*Secret, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, name)
return s.getSecret(ctx, url)
}
// GetOrgSecret gets a single organization secret without revealing its encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-an-organization-secret
//
//meta:operation GET /orgs/{org}/actions/secrets/{secret_name}
func (s *ActionsService) GetOrgSecret(ctx context.Context, org, name string) (*Secret, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v", org, name)
return s.getSecret(ctx, url)
}
// GetEnvSecret gets a single environment secret without revealing its encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#get-an-environment-secret
//
//meta:operation GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}
func (s *ActionsService) GetEnvSecret(ctx context.Context, repoID int, env, secretName string) (*Secret, *Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/secrets/%v", repoID, env, secretName)
return s.getSecret(ctx, url)
}
// SelectedRepoIDs are the repository IDs that have access to the actions secrets.
type SelectedRepoIDs []int64
// EncryptedSecret represents a secret that is encrypted using a public key.
//
// The value of EncryptedValue must be your secret, encrypted with
// LibSodium (see documentation here: https://libsodium.gitbook.io/doc/bindings_for_other_languages)
// using the public key retrieved using the GetPublicKey method.
type EncryptedSecret struct {
Name string `json:"-"`
KeyID string `json:"key_id"`
EncryptedValue string `json:"encrypted_value"`
Visibility string `json:"visibility,omitempty"`
SelectedRepositoryIDs SelectedRepoIDs `json:"selected_repository_ids,omitempty"`
}
func (s *ActionsService) putSecret(ctx context.Context, url string, eSecret *EncryptedSecret) (*Response, error) {
req, err := s.client.NewRequest("PUT", url, eSecret)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// CreateOrUpdateRepoSecret creates or updates a repository secret with an encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#create-or-update-a-repository-secret
//
//meta:operation PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}
func (s *ActionsService) CreateOrUpdateRepoSecret(ctx context.Context, owner, repo string, eSecret *EncryptedSecret) (*Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, eSecret.Name)
return s.putSecret(ctx, url, eSecret)
}
// CreateOrUpdateOrgSecret creates or updates an organization secret with an encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#create-or-update-an-organization-secret
//
//meta:operation PUT /orgs/{org}/actions/secrets/{secret_name}
func (s *ActionsService) CreateOrUpdateOrgSecret(ctx context.Context, org string, eSecret *EncryptedSecret) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v", org, eSecret.Name)
return s.putSecret(ctx, url, eSecret)
}
// CreateOrUpdateEnvSecret creates or updates a single environment secret with an encrypted value.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#create-or-update-an-environment-secret
//
//meta:operation PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}
func (s *ActionsService) CreateOrUpdateEnvSecret(ctx context.Context, repoID int, env string, eSecret *EncryptedSecret) (*Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/secrets/%v", repoID, env, eSecret.Name)
return s.putSecret(ctx, url, eSecret)
}
func (s *ActionsService) deleteSecret(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// DeleteRepoSecret deletes a secret in a repository using the secret name.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#delete-a-repository-secret
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}
func (s *ActionsService) DeleteRepoSecret(ctx context.Context, owner, repo, name string) (*Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, name)
return s.deleteSecret(ctx, url)
}
// DeleteOrgSecret deletes a secret in an organization using the secret name.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#delete-an-organization-secret
//
//meta:operation DELETE /orgs/{org}/actions/secrets/{secret_name}
func (s *ActionsService) DeleteOrgSecret(ctx context.Context, org, name string) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v", org, name)
return s.deleteSecret(ctx, url)
}
// DeleteEnvSecret deletes a secret in an environment using the secret name.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#delete-an-environment-secret
//
//meta:operation DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}
func (s *ActionsService) DeleteEnvSecret(ctx context.Context, repoID int, env, secretName string) (*Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/secrets/%v", repoID, env, secretName)
return s.deleteSecret(ctx, url)
}
// SelectedReposList represents the list of repositories selected for an organization secret.
type SelectedReposList struct {
TotalCount *int `json:"total_count,omitempty"`
Repositories []*Repository `json:"repositories,omitempty"`
}
func (s *ActionsService) listSelectedReposForSecret(ctx context.Context, url string, opts *ListOptions) (*SelectedReposList, *Response, error) {
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
result := new(SelectedReposList)
resp, err := s.client.Do(ctx, req, result)
if err != nil {
return nil, resp, err
}
return result, resp, nil
}
// ListSelectedReposForOrgSecret lists all repositories that have access to a secret.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#list-selected-repositories-for-an-organization-secret
//
//meta:operation GET /orgs/{org}/actions/secrets/{secret_name}/repositories
func (s *ActionsService) ListSelectedReposForOrgSecret(ctx context.Context, org, name string, opts *ListOptions) (*SelectedReposList, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v/repositories", org, name)
return s.listSelectedReposForSecret(ctx, url, opts)
}
func (s *ActionsService) setSelectedReposForSecret(ctx context.Context, url string, ids SelectedRepoIDs) (*Response, error) {
type repoIDs struct {
SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"`
}
req, err := s.client.NewRequest("PUT", url, repoIDs{SelectedIDs: ids})
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// SetSelectedReposForOrgSecret sets the repositories that have access to a secret.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#set-selected-repositories-for-an-organization-secret
//
//meta:operation PUT /orgs/{org}/actions/secrets/{secret_name}/repositories
func (s *ActionsService) SetSelectedReposForOrgSecret(ctx context.Context, org, name string, ids SelectedRepoIDs) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v/repositories", org, name)
return s.setSelectedReposForSecret(ctx, url, ids)
}
func (s *ActionsService) addSelectedRepoToSecret(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("PUT", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AddSelectedRepoToOrgSecret adds a repository to an organization secret.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#add-selected-repository-to-an-organization-secret
//
//meta:operation PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}
func (s *ActionsService) AddSelectedRepoToOrgSecret(ctx context.Context, org, name string, repo *Repository) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v/repositories/%v", org, name, *repo.ID)
return s.addSelectedRepoToSecret(ctx, url)
}
func (s *ActionsService) removeSelectedRepoFromSecret(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RemoveSelectedRepoFromOrgSecret removes a repository from an organization secret.
//
// GitHub API docs: https://docs.github.com/rest/actions/secrets#remove-selected-repository-from-an-organization-secret
//
//meta:operation DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}
func (s *ActionsService) RemoveSelectedRepoFromOrgSecret(ctx context.Context, org, name string, repo *Repository) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/secrets/%v/repositories/%v", org, name, *repo.ID)
return s.removeSelectedRepoFromSecret(ctx, url)
}

View file

@ -1,331 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ActionsVariable represents a repository action variable.
type ActionsVariable struct {
Name string `json:"name"`
Value string `json:"value"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Visibility *string `json:"visibility,omitempty"`
// Used by ListOrgVariables and GetOrgVariables
SelectedRepositoriesURL *string `json:"selected_repositories_url,omitempty"`
// Used by UpdateOrgVariable and CreateOrgVariable
SelectedRepositoryIDs *SelectedRepoIDs `json:"selected_repository_ids,omitempty"`
}
// ActionsVariables represents one item from the ListVariables response.
type ActionsVariables struct {
TotalCount int `json:"total_count"`
Variables []*ActionsVariable `json:"variables"`
}
func (s *ActionsService) listVariables(ctx context.Context, url string, opts *ListOptions) (*ActionsVariables, *Response, error) {
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
variables := new(ActionsVariables)
resp, err := s.client.Do(ctx, req, &variables)
if err != nil {
return nil, resp, err
}
return variables, resp, nil
}
// ListRepoVariables lists all variables available in a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#list-repository-variables
//
//meta:operation GET /repos/{owner}/{repo}/actions/variables
func (s *ActionsService) ListRepoVariables(ctx context.Context, owner, repo string, opts *ListOptions) (*ActionsVariables, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/variables", owner, repo)
return s.listVariables(ctx, url, opts)
}
// ListOrgVariables lists all variables available in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#list-organization-variables
//
//meta:operation GET /orgs/{org}/actions/variables
func (s *ActionsService) ListOrgVariables(ctx context.Context, org string, opts *ListOptions) (*ActionsVariables, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables", org)
return s.listVariables(ctx, url, opts)
}
// ListEnvVariables lists all variables available in an environment.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#list-environment-variables
//
//meta:operation GET /repositories/{repository_id}/environments/{environment_name}/variables
func (s *ActionsService) ListEnvVariables(ctx context.Context, repoID int, env string, opts *ListOptions) (*ActionsVariables, *Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/variables", repoID, env)
return s.listVariables(ctx, url, opts)
}
func (s *ActionsService) getVariable(ctx context.Context, url string) (*ActionsVariable, *Response, error) {
req, err := s.client.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
variable := new(ActionsVariable)
resp, err := s.client.Do(ctx, req, variable)
if err != nil {
return nil, resp, err
}
return variable, resp, nil
}
// GetRepoVariable gets a single repository variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#get-a-repository-variable
//
//meta:operation GET /repos/{owner}/{repo}/actions/variables/{name}
func (s *ActionsService) GetRepoVariable(ctx context.Context, owner, repo, name string) (*ActionsVariable, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/variables/%v", owner, repo, name)
return s.getVariable(ctx, url)
}
// GetOrgVariable gets a single organization variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#get-an-organization-variable
//
//meta:operation GET /orgs/{org}/actions/variables/{name}
func (s *ActionsService) GetOrgVariable(ctx context.Context, org, name string) (*ActionsVariable, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v", org, name)
return s.getVariable(ctx, url)
}
// GetEnvVariable gets a single environment variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#get-an-environment-variable
//
//meta:operation GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}
func (s *ActionsService) GetEnvVariable(ctx context.Context, repoID int, env, variableName string) (*ActionsVariable, *Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/variables/%v", repoID, env, variableName)
return s.getVariable(ctx, url)
}
func (s *ActionsService) postVariable(ctx context.Context, url string, variable *ActionsVariable) (*Response, error) {
req, err := s.client.NewRequest("POST", url, variable)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// CreateRepoVariable creates a repository variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#create-a-repository-variable
//
//meta:operation POST /repos/{owner}/{repo}/actions/variables
func (s *ActionsService) CreateRepoVariable(ctx context.Context, owner, repo string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/variables", owner, repo)
return s.postVariable(ctx, url, variable)
}
// CreateOrgVariable creates an organization variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#create-an-organization-variable
//
//meta:operation POST /orgs/{org}/actions/variables
func (s *ActionsService) CreateOrgVariable(ctx context.Context, org string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables", org)
return s.postVariable(ctx, url, variable)
}
// CreateEnvVariable creates an environment variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#create-an-environment-variable
//
//meta:operation POST /repositories/{repository_id}/environments/{environment_name}/variables
func (s *ActionsService) CreateEnvVariable(ctx context.Context, repoID int, env string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/variables", repoID, env)
return s.postVariable(ctx, url, variable)
}
func (s *ActionsService) patchVariable(ctx context.Context, url string, variable *ActionsVariable) (*Response, error) {
req, err := s.client.NewRequest("PATCH", url, variable)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// UpdateRepoVariable updates a repository variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#update-a-repository-variable
//
//meta:operation PATCH /repos/{owner}/{repo}/actions/variables/{name}
func (s *ActionsService) UpdateRepoVariable(ctx context.Context, owner, repo string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/variables/%v", owner, repo, variable.Name)
return s.patchVariable(ctx, url, variable)
}
// UpdateOrgVariable updates an organization variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#update-an-organization-variable
//
//meta:operation PATCH /orgs/{org}/actions/variables/{name}
func (s *ActionsService) UpdateOrgVariable(ctx context.Context, org string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v", org, variable.Name)
return s.patchVariable(ctx, url, variable)
}
// UpdateEnvVariable updates an environment variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#update-an-environment-variable
//
//meta:operation PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}
func (s *ActionsService) UpdateEnvVariable(ctx context.Context, repoID int, env string, variable *ActionsVariable) (*Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/variables/%v", repoID, env, variable.Name)
return s.patchVariable(ctx, url, variable)
}
func (s *ActionsService) deleteVariable(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// DeleteRepoVariable deletes a variable in a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#delete-a-repository-variable
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/variables/{name}
func (s *ActionsService) DeleteRepoVariable(ctx context.Context, owner, repo, name string) (*Response, error) {
url := fmt.Sprintf("repos/%v/%v/actions/variables/%v", owner, repo, name)
return s.deleteVariable(ctx, url)
}
// DeleteOrgVariable deletes a variable in an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#delete-an-organization-variable
//
//meta:operation DELETE /orgs/{org}/actions/variables/{name}
func (s *ActionsService) DeleteOrgVariable(ctx context.Context, org, name string) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v", org, name)
return s.deleteVariable(ctx, url)
}
// DeleteEnvVariable deletes a variable in an environment.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#delete-an-environment-variable
//
//meta:operation DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}
func (s *ActionsService) DeleteEnvVariable(ctx context.Context, repoID int, env, variableName string) (*Response, error) {
url := fmt.Sprintf("repositories/%v/environments/%v/variables/%v", repoID, env, variableName)
return s.deleteVariable(ctx, url)
}
func (s *ActionsService) listSelectedReposForVariable(ctx context.Context, url string, opts *ListOptions) (*SelectedReposList, *Response, error) {
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
result := new(SelectedReposList)
resp, err := s.client.Do(ctx, req, result)
if err != nil {
return nil, resp, err
}
return result, resp, nil
}
// ListSelectedReposForOrgVariable lists all repositories that have access to a variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#list-selected-repositories-for-an-organization-variable
//
//meta:operation GET /orgs/{org}/actions/variables/{name}/repositories
func (s *ActionsService) ListSelectedReposForOrgVariable(ctx context.Context, org, name string, opts *ListOptions) (*SelectedReposList, *Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v/repositories", org, name)
return s.listSelectedReposForVariable(ctx, url, opts)
}
func (s *ActionsService) setSelectedReposForVariable(ctx context.Context, url string, ids SelectedRepoIDs) (*Response, error) {
type repoIDs struct {
SelectedIDs SelectedRepoIDs `json:"selected_repository_ids"`
}
req, err := s.client.NewRequest("PUT", url, repoIDs{SelectedIDs: ids})
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// SetSelectedReposForOrgVariable sets the repositories that have access to a variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#set-selected-repositories-for-an-organization-variable
//
//meta:operation PUT /orgs/{org}/actions/variables/{name}/repositories
func (s *ActionsService) SetSelectedReposForOrgVariable(ctx context.Context, org, name string, ids SelectedRepoIDs) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v/repositories", org, name)
return s.setSelectedReposForVariable(ctx, url, ids)
}
func (s *ActionsService) addSelectedRepoToVariable(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("PUT", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AddSelectedRepoToOrgVariable adds a repository to an organization variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#add-selected-repository-to-an-organization-variable
//
//meta:operation PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}
func (s *ActionsService) AddSelectedRepoToOrgVariable(ctx context.Context, org, name string, repo *Repository) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v/repositories/%v", org, name, *repo.ID)
return s.addSelectedRepoToVariable(ctx, url)
}
func (s *ActionsService) removeSelectedRepoFromVariable(ctx context.Context, url string) (*Response, error) {
req, err := s.client.NewRequest("DELETE", url, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RemoveSelectedRepoFromOrgVariable removes a repository from an organization variable.
//
// GitHub API docs: https://docs.github.com/rest/actions/variables#remove-selected-repository-from-an-organization-variable
//
//meta:operation DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}
func (s *ActionsService) RemoveSelectedRepoFromOrgVariable(ctx context.Context, org, name string, repo *Repository) (*Response, error) {
url := fmt.Sprintf("orgs/%v/actions/variables/%v/repositories/%v", org, name, *repo.ID)
return s.removeSelectedRepoFromVariable(ctx, url)
}

View file

@ -1,139 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"net/http"
"net/url"
)
// TaskStep represents a single task step from a sequence of tasks of a job.
type TaskStep struct {
Name *string `json:"name,omitempty"`
Status *string `json:"status,omitempty"`
Conclusion *string `json:"conclusion,omitempty"`
Number *int64 `json:"number,omitempty"`
StartedAt *Timestamp `json:"started_at,omitempty"`
CompletedAt *Timestamp `json:"completed_at,omitempty"`
}
// WorkflowJob represents a repository action workflow job.
type WorkflowJob struct {
ID *int64 `json:"id,omitempty"`
RunID *int64 `json:"run_id,omitempty"`
RunURL *string `json:"run_url,omitempty"`
NodeID *string `json:"node_id,omitempty"`
HeadBranch *string `json:"head_branch,omitempty"`
HeadSHA *string `json:"head_sha,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
Status *string `json:"status,omitempty"`
Conclusion *string `json:"conclusion,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
StartedAt *Timestamp `json:"started_at,omitempty"`
CompletedAt *Timestamp `json:"completed_at,omitempty"`
Name *string `json:"name,omitempty"`
Steps []*TaskStep `json:"steps,omitempty"`
CheckRunURL *string `json:"check_run_url,omitempty"`
// Labels represents runner labels from the `runs-on:` key from a GitHub Actions workflow.
Labels []string `json:"labels,omitempty"`
RunnerID *int64 `json:"runner_id,omitempty"`
RunnerName *string `json:"runner_name,omitempty"`
RunnerGroupID *int64 `json:"runner_group_id,omitempty"`
RunnerGroupName *string `json:"runner_group_name,omitempty"`
RunAttempt *int64 `json:"run_attempt,omitempty"`
WorkflowName *string `json:"workflow_name,omitempty"`
}
// Jobs represents a slice of repository action workflow job.
type Jobs struct {
TotalCount *int `json:"total_count,omitempty"`
Jobs []*WorkflowJob `json:"jobs,omitempty"`
}
// ListWorkflowJobsOptions specifies optional parameters to ListWorkflowJobs.
type ListWorkflowJobsOptions struct {
// Filter specifies how jobs should be filtered by their completed_at timestamp.
// Possible values are:
// latest - Returns jobs from the most recent execution of the workflow run
// all - Returns all jobs for a workflow run, including from old executions of the workflow run
//
// Default value is "latest".
Filter string `url:"filter,omitempty"`
ListOptions
}
// ListWorkflowJobs lists all jobs for a workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-jobs#list-jobs-for-a-workflow-run
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs
func (s *ActionsService) ListWorkflowJobs(ctx context.Context, owner, repo string, runID int64, opts *ListWorkflowJobsOptions) (*Jobs, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/actions/runs/%v/jobs", owner, repo, runID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
jobs := new(Jobs)
resp, err := s.client.Do(ctx, req, &jobs)
if err != nil {
return nil, resp, err
}
return jobs, resp, nil
}
// GetWorkflowJobByID gets a specific job in a workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-jobs#get-a-job-for-a-workflow-run
//
//meta:operation GET /repos/{owner}/{repo}/actions/jobs/{job_id}
func (s *ActionsService) GetWorkflowJobByID(ctx context.Context, owner, repo string, jobID int64) (*WorkflowJob, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/jobs/%v", owner, repo, jobID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
job := new(WorkflowJob)
resp, err := s.client.Do(ctx, req, job)
if err != nil {
return nil, resp, err
}
return job, resp, nil
}
// GetWorkflowJobLogs gets a redirect URL to download a plain text file of logs for a workflow job.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-jobs#download-job-logs-for-a-workflow-run
//
//meta:operation GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs
func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo string, jobID int64, maxRedirects int) (*url.URL, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/jobs/%v/logs", owner, repo, jobID)
resp, err := s.client.roundTripWithOptionalFollowRedirect(ctx, u, maxRedirects)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status)
}
parsedURL, err := url.Parse(resp.Header.Get("Location"))
return parsedURL, newResponse(resp), err
}

View file

@ -1,410 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"net/http"
"net/url"
)
// WorkflowRun represents a repository action workflow run.
type WorkflowRun struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
NodeID *string `json:"node_id,omitempty"`
HeadBranch *string `json:"head_branch,omitempty"`
HeadSHA *string `json:"head_sha,omitempty"`
RunNumber *int `json:"run_number,omitempty"`
RunAttempt *int `json:"run_attempt,omitempty"`
Event *string `json:"event,omitempty"`
DisplayTitle *string `json:"display_title,omitempty"`
Status *string `json:"status,omitempty"`
Conclusion *string `json:"conclusion,omitempty"`
WorkflowID *int64 `json:"workflow_id,omitempty"`
CheckSuiteID *int64 `json:"check_suite_id,omitempty"`
CheckSuiteNodeID *string `json:"check_suite_node_id,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
PullRequests []*PullRequest `json:"pull_requests,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
RunStartedAt *Timestamp `json:"run_started_at,omitempty"`
JobsURL *string `json:"jobs_url,omitempty"`
LogsURL *string `json:"logs_url,omitempty"`
CheckSuiteURL *string `json:"check_suite_url,omitempty"`
ArtifactsURL *string `json:"artifacts_url,omitempty"`
CancelURL *string `json:"cancel_url,omitempty"`
RerunURL *string `json:"rerun_url,omitempty"`
PreviousAttemptURL *string `json:"previous_attempt_url,omitempty"`
HeadCommit *HeadCommit `json:"head_commit,omitempty"`
WorkflowURL *string `json:"workflow_url,omitempty"`
Repository *Repository `json:"repository,omitempty"`
HeadRepository *Repository `json:"head_repository,omitempty"`
Actor *User `json:"actor,omitempty"`
TriggeringActor *User `json:"triggering_actor,omitempty"`
ReferencedWorkflows []*ReferencedWorkflow `json:"referenced_workflows,omitempty"`
}
// WorkflowRuns represents a slice of repository action workflow run.
type WorkflowRuns struct {
TotalCount *int `json:"total_count,omitempty"`
WorkflowRuns []*WorkflowRun `json:"workflow_runs,omitempty"`
}
// ListWorkflowRunsOptions specifies optional parameters to ListWorkflowRuns.
type ListWorkflowRunsOptions struct {
Actor string `url:"actor,omitempty"`
Branch string `url:"branch,omitempty"`
Event string `url:"event,omitempty"`
Status string `url:"status,omitempty"`
Created string `url:"created,omitempty"`
HeadSHA string `url:"head_sha,omitempty"`
ExcludePullRequests bool `url:"exclude_pull_requests,omitempty"`
CheckSuiteID int64 `url:"check_suite_id,omitempty"`
ListOptions
}
// WorkflowRunUsage represents a usage of a specific workflow run.
type WorkflowRunUsage struct {
Billable *WorkflowRunBillMap `json:"billable,omitempty"`
RunDurationMS *int64 `json:"run_duration_ms,omitempty"`
}
// WorkflowRunBillMap represents different runner environments available for a workflow run.
// Its key is the name of its environment, e.g. "UBUNTU", "MACOS", "WINDOWS", etc.
type WorkflowRunBillMap map[string]*WorkflowRunBill
// WorkflowRunBill specifies billable time for a specific environment in a workflow run.
type WorkflowRunBill struct {
TotalMS *int64 `json:"total_ms,omitempty"`
Jobs *int `json:"jobs,omitempty"`
JobRuns []*WorkflowRunJobRun `json:"job_runs,omitempty"`
}
// WorkflowRunJobRun represents a usage of individual jobs of a specific workflow run.
type WorkflowRunJobRun struct {
JobID *int `json:"job_id,omitempty"`
DurationMS *int64 `json:"duration_ms,omitempty"`
}
// WorkflowRunAttemptOptions specifies optional parameters to GetWorkflowRunAttempt.
type WorkflowRunAttemptOptions struct {
ExcludePullRequests *bool `url:"exclude_pull_requests,omitempty"`
}
// PendingDeploymentsRequest specifies body parameters to PendingDeployments.
type PendingDeploymentsRequest struct {
EnvironmentIDs []int64 `json:"environment_ids"`
// State can be one of: "approved", "rejected".
State string `json:"state"`
Comment string `json:"comment"`
}
type ReferencedWorkflow struct {
Path *string `json:"path,omitempty"`
SHA *string `json:"sha,omitempty"`
Ref *string `json:"ref,omitempty"`
}
func (s *ActionsService) listWorkflowRuns(ctx context.Context, endpoint string, opts *ListWorkflowRunsOptions) (*WorkflowRuns, *Response, error) {
u, err := addOptions(endpoint, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runs := new(WorkflowRuns)
resp, err := s.client.Do(ctx, req, &runs)
if err != nil {
return nil, resp, err
}
return runs, resp, nil
}
// ListWorkflowRunsByID lists all workflow runs by workflow ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs
func (s *ActionsService) ListWorkflowRunsByID(ctx context.Context, owner, repo string, workflowID int64, opts *ListWorkflowRunsOptions) (*WorkflowRuns, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/actions/workflows/%v/runs", owner, repo, workflowID)
return s.listWorkflowRuns(ctx, u, opts)
}
// ListWorkflowRunsByFileName lists all workflow runs by workflow file name.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
//
//meta:operation GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs
func (s *ActionsService) ListWorkflowRunsByFileName(ctx context.Context, owner, repo, workflowFileName string, opts *ListWorkflowRunsOptions) (*WorkflowRuns, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/actions/workflows/%v/runs", owner, repo, workflowFileName)
return s.listWorkflowRuns(ctx, u, opts)
}
// ListRepositoryWorkflowRuns lists all workflow runs for a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#list-workflow-runs-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs
func (s *ActionsService) ListRepositoryWorkflowRuns(ctx context.Context, owner, repo string, opts *ListWorkflowRunsOptions) (*WorkflowRuns, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/actions/runs", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runs := new(WorkflowRuns)
resp, err := s.client.Do(ctx, req, &runs)
if err != nil {
return nil, resp, err
}
return runs, resp, nil
}
// GetWorkflowRunByID gets a specific workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#get-a-workflow-run
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}
func (s *ActionsService) GetWorkflowRunByID(ctx context.Context, owner, repo string, runID int64) (*WorkflowRun, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v", owner, repo, runID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
run := new(WorkflowRun)
resp, err := s.client.Do(ctx, req, run)
if err != nil {
return nil, resp, err
}
return run, resp, nil
}
// GetWorkflowRunAttempt gets a specific workflow run attempt.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#get-a-workflow-run-attempt
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}
func (s *ActionsService) GetWorkflowRunAttempt(ctx context.Context, owner, repo string, runID int64, attemptNumber int, opts *WorkflowRunAttemptOptions) (*WorkflowRun, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/attempts/%v", owner, repo, runID, attemptNumber)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
run := new(WorkflowRun)
resp, err := s.client.Do(ctx, req, run)
if err != nil {
return nil, resp, err
}
return run, resp, nil
}
// GetWorkflowRunAttemptLogs gets a redirect URL to download a plain text file of logs for a workflow run for attempt number.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#download-workflow-run-attempt-logs
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs
func (s *ActionsService) GetWorkflowRunAttemptLogs(ctx context.Context, owner, repo string, runID int64, attemptNumber int, maxRedirects int) (*url.URL, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/attempts/%v/logs", owner, repo, runID, attemptNumber)
resp, err := s.client.roundTripWithOptionalFollowRedirect(ctx, u, maxRedirects)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status)
}
parsedURL, err := url.Parse(resp.Header.Get("Location"))
return parsedURL, newResponse(resp), err
}
// RerunWorkflowByID re-runs a workflow by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#re-run-a-workflow
//
//meta:operation POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun
func (s *ActionsService) RerunWorkflowByID(ctx context.Context, owner, repo string, runID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/rerun", owner, repo, runID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RerunFailedJobsByID re-runs all of the failed jobs and their dependent jobs in a workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#re-run-failed-jobs-from-a-workflow-run
//
//meta:operation POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs
func (s *ActionsService) RerunFailedJobsByID(ctx context.Context, owner, repo string, runID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/rerun-failed-jobs", owner, repo, runID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// RerunJobByID re-runs a job and its dependent jobs in a workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#re-run-a-job-from-a-workflow-run
//
//meta:operation POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun
func (s *ActionsService) RerunJobByID(ctx context.Context, owner, repo string, jobID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/jobs/%v/rerun", owner, repo, jobID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// CancelWorkflowRunByID cancels a workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#cancel-a-workflow-run
//
//meta:operation POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel
func (s *ActionsService) CancelWorkflowRunByID(ctx context.Context, owner, repo string, runID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/cancel", owner, repo, runID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// GetWorkflowRunLogs gets a redirect URL to download a plain text file of logs for a workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#download-workflow-run-logs
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs
func (s *ActionsService) GetWorkflowRunLogs(ctx context.Context, owner, repo string, runID int64, maxRedirects int) (*url.URL, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/logs", owner, repo, runID)
resp, err := s.client.roundTripWithOptionalFollowRedirect(ctx, u, maxRedirects)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusFound {
return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status)
}
parsedURL, err := url.Parse(resp.Header.Get("Location"))
return parsedURL, newResponse(resp), err
}
// DeleteWorkflowRun deletes a workflow run by ID.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#delete-a-workflow-run
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/runs/{run_id}
func (s *ActionsService) DeleteWorkflowRun(ctx context.Context, owner, repo string, runID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v", owner, repo, runID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// DeleteWorkflowRunLogs deletes all logs for a workflow run.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#delete-workflow-run-logs
//
//meta:operation DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs
func (s *ActionsService) DeleteWorkflowRunLogs(ctx context.Context, owner, repo string, runID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/logs", owner, repo, runID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// GetWorkflowRunUsageByID gets a specific workflow usage run by run ID in the unit of billable milliseconds.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#get-workflow-run-usage
//
//meta:operation GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing
func (s *ActionsService) GetWorkflowRunUsageByID(ctx context.Context, owner, repo string, runID int64) (*WorkflowRunUsage, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/timing", owner, repo, runID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
workflowRunUsage := new(WorkflowRunUsage)
resp, err := s.client.Do(ctx, req, workflowRunUsage)
if err != nil {
return nil, resp, err
}
return workflowRunUsage, resp, nil
}
// PendingDeployments approve or reject pending deployments that are waiting on approval by a required reviewer.
//
// GitHub API docs: https://docs.github.com/rest/actions/workflow-runs#review-pending-deployments-for-a-workflow-run
//
//meta:operation POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments
func (s *ActionsService) PendingDeployments(ctx context.Context, owner, repo string, runID int64, request *PendingDeploymentsRequest) ([]*Deployment, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/pending_deployments", owner, repo, runID)
req, err := s.client.NewRequest("POST", u, request)
if err != nil {
return nil, nil, err
}
var deployments []*Deployment
resp, err := s.client.Do(ctx, req, &deployments)
if err != nil {
return nil, resp, err
}
return deployments, resp, nil
}

View file

@ -1,241 +0,0 @@
// Copyright 2014 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"time"
)
// Notification identifies a GitHub notification for a user.
type Notification struct {
ID *string `json:"id,omitempty"`
Repository *Repository `json:"repository,omitempty"`
Subject *NotificationSubject `json:"subject,omitempty"`
// Reason identifies the event that triggered the notification.
//
// GitHub API docs: https://docs.github.com/rest/activity#notification-reasons
Reason *string `json:"reason,omitempty"`
Unread *bool `json:"unread,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
LastReadAt *Timestamp `json:"last_read_at,omitempty"`
URL *string `json:"url,omitempty"`
}
// NotificationSubject identifies the subject of a notification.
type NotificationSubject struct {
Title *string `json:"title,omitempty"`
URL *string `json:"url,omitempty"`
LatestCommentURL *string `json:"latest_comment_url,omitempty"`
Type *string `json:"type,omitempty"`
}
// NotificationListOptions specifies the optional parameters to the
// ActivityService.ListNotifications method.
type NotificationListOptions struct {
All bool `url:"all,omitempty"`
Participating bool `url:"participating,omitempty"`
Since time.Time `url:"since,omitempty"`
Before time.Time `url:"before,omitempty"`
ListOptions
}
// ListNotifications lists all notifications for the authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#list-notifications-for-the-authenticated-user
//
//meta:operation GET /notifications
func (s *ActivityService) ListNotifications(ctx context.Context, opts *NotificationListOptions) ([]*Notification, *Response, error) {
u := "notifications"
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var notifications []*Notification
resp, err := s.client.Do(ctx, req, &notifications)
if err != nil {
return nil, resp, err
}
return notifications, resp, nil
}
// ListRepositoryNotifications lists all notifications in a given repository
// for the authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#list-repository-notifications-for-the-authenticated-user
//
//meta:operation GET /repos/{owner}/{repo}/notifications
func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opts *NotificationListOptions) ([]*Notification, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var notifications []*Notification
resp, err := s.client.Do(ctx, req, &notifications)
if err != nil {
return nil, resp, err
}
return notifications, resp, nil
}
type markReadOptions struct {
LastReadAt Timestamp `json:"last_read_at,omitempty"`
}
// MarkNotificationsRead marks all notifications up to lastRead as read.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#mark-notifications-as-read
//
//meta:operation PUT /notifications
func (s *ActivityService) MarkNotificationsRead(ctx context.Context, lastRead Timestamp) (*Response, error) {
opts := &markReadOptions{
LastReadAt: lastRead,
}
req, err := s.client.NewRequest("PUT", "notifications", opts)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// MarkRepositoryNotificationsRead marks all notifications up to lastRead in
// the specified repository as read.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#mark-repository-notifications-as-read
//
//meta:operation PUT /repos/{owner}/{repo}/notifications
func (s *ActivityService) MarkRepositoryNotificationsRead(ctx context.Context, owner, repo string, lastRead Timestamp) (*Response, error) {
opts := &markReadOptions{
LastReadAt: lastRead,
}
u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo)
req, err := s.client.NewRequest("PUT", u, opts)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// GetThread gets the specified notification thread.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#get-a-thread
//
//meta:operation GET /notifications/threads/{thread_id}
func (s *ActivityService) GetThread(ctx context.Context, id string) (*Notification, *Response, error) {
u := fmt.Sprintf("notifications/threads/%v", id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
notification := new(Notification)
resp, err := s.client.Do(ctx, req, notification)
if err != nil {
return nil, resp, err
}
return notification, resp, nil
}
// MarkThreadRead marks the specified thread as read.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#mark-a-thread-as-read
//
//meta:operation PATCH /notifications/threads/{thread_id}
func (s *ActivityService) MarkThreadRead(ctx context.Context, id string) (*Response, error) {
u := fmt.Sprintf("notifications/threads/%v", id)
req, err := s.client.NewRequest("PATCH", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// GetThreadSubscription checks to see if the authenticated user is subscribed
// to a thread.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#get-a-thread-subscription-for-the-authenticated-user
//
//meta:operation GET /notifications/threads/{thread_id}/subscription
func (s *ActivityService) GetThreadSubscription(ctx context.Context, id string) (*Subscription, *Response, error) {
u := fmt.Sprintf("notifications/threads/%v/subscription", id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
sub := new(Subscription)
resp, err := s.client.Do(ctx, req, sub)
if err != nil {
return nil, resp, err
}
return sub, resp, nil
}
// SetThreadSubscription sets the subscription for the specified thread for the
// authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#set-a-thread-subscription
//
//meta:operation PUT /notifications/threads/{thread_id}/subscription
func (s *ActivityService) SetThreadSubscription(ctx context.Context, id string, subscription *Subscription) (*Subscription, *Response, error) {
u := fmt.Sprintf("notifications/threads/%v/subscription", id)
req, err := s.client.NewRequest("PUT", u, subscription)
if err != nil {
return nil, nil, err
}
sub := new(Subscription)
resp, err := s.client.Do(ctx, req, sub)
if err != nil {
return nil, resp, err
}
return sub, resp, nil
}
// DeleteThreadSubscription deletes the subscription for the specified thread
// for the authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/activity/notifications#delete-a-thread-subscription
//
//meta:operation DELETE /notifications/threads/{thread_id}/subscription
func (s *ActivityService) DeleteThreadSubscription(ctx context.Context, id string) (*Response, error) {
u := fmt.Sprintf("notifications/threads/%v/subscription", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,123 +0,0 @@
// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// AdminService handles communication with the admin related methods of the
// GitHub API. These API routes are normally only accessible for GitHub
// Enterprise installations.
//
// GitHub API docs: https://docs.github.com/rest/enterprise-admin
type AdminService service
// TeamLDAPMapping represents the mapping between a GitHub team and an LDAP group.
type TeamLDAPMapping struct {
ID *int64 `json:"id,omitempty"`
LDAPDN *string `json:"ldap_dn,omitempty"`
URL *string `json:"url,omitempty"`
Name *string `json:"name,omitempty"`
Slug *string `json:"slug,omitempty"`
Description *string `json:"description,omitempty"`
Privacy *string `json:"privacy,omitempty"`
Permission *string `json:"permission,omitempty"`
MembersURL *string `json:"members_url,omitempty"`
RepositoriesURL *string `json:"repositories_url,omitempty"`
}
func (m TeamLDAPMapping) String() string {
return Stringify(m)
}
// UserLDAPMapping represents the mapping between a GitHub user and an LDAP user.
type UserLDAPMapping struct {
ID *int64 `json:"id,omitempty"`
LDAPDN *string `json:"ldap_dn,omitempty"`
Login *string `json:"login,omitempty"`
AvatarURL *string `json:"avatar_url,omitempty"`
GravatarID *string `json:"gravatar_id,omitempty"`
Type *string `json:"type,omitempty"`
SiteAdmin *bool `json:"site_admin,omitempty"`
URL *string `json:"url,omitempty"`
EventsURL *string `json:"events_url,omitempty"`
FollowingURL *string `json:"following_url,omitempty"`
FollowersURL *string `json:"followers_url,omitempty"`
GistsURL *string `json:"gists_url,omitempty"`
OrganizationsURL *string `json:"organizations_url,omitempty"`
ReceivedEventsURL *string `json:"received_events_url,omitempty"`
ReposURL *string `json:"repos_url,omitempty"`
StarredURL *string `json:"starred_url,omitempty"`
SubscriptionsURL *string `json:"subscriptions_url,omitempty"`
}
func (m UserLDAPMapping) String() string {
return Stringify(m)
}
// Enterprise represents the GitHub enterprise profile.
type Enterprise struct {
ID *int `json:"id,omitempty"`
Slug *string `json:"slug,omitempty"`
Name *string `json:"name,omitempty"`
NodeID *string `json:"node_id,omitempty"`
AvatarURL *string `json:"avatar_url,omitempty"`
Description *string `json:"description,omitempty"`
WebsiteURL *string `json:"website_url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
}
func (m Enterprise) String() string {
return Stringify(m)
}
// UpdateUserLDAPMapping updates the mapping between a GitHub user and an LDAP user.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/ldap#update-ldap-mapping-for-a-user
//
//meta:operation PATCH /admin/ldap/users/{username}/mapping
func (s *AdminService) UpdateUserLDAPMapping(ctx context.Context, user string, mapping *UserLDAPMapping) (*UserLDAPMapping, *Response, error) {
u := fmt.Sprintf("admin/ldap/users/%v/mapping", user)
req, err := s.client.NewRequest("PATCH", u, mapping)
if err != nil {
return nil, nil, err
}
m := new(UserLDAPMapping)
resp, err := s.client.Do(ctx, req, m)
if err != nil {
return nil, resp, err
}
return m, resp, nil
}
// UpdateTeamLDAPMapping updates the mapping between a GitHub team and an LDAP group.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/ldap#update-ldap-mapping-for-a-team
//
//meta:operation PATCH /admin/ldap/teams/{team_id}/mapping
func (s *AdminService) UpdateTeamLDAPMapping(ctx context.Context, team int64, mapping *TeamLDAPMapping) (*TeamLDAPMapping, *Response, error) {
u := fmt.Sprintf("admin/ldap/teams/%v/mapping", team)
req, err := s.client.NewRequest("PATCH", u, mapping)
if err != nil {
return nil, nil, err
}
m := new(TeamLDAPMapping)
resp, err := s.client.Do(ctx, req, m)
if err != nil {
return nil, resp, err
}
return m, resp, nil
}

View file

@ -1,95 +0,0 @@
// Copyright 2019 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// createOrgRequest is a subset of Organization and is used internally
// by CreateOrg to pass only the known fields for the endpoint.
type createOrgRequest struct {
Login *string `json:"login,omitempty"`
Admin *string `json:"admin,omitempty"`
}
// CreateOrg creates a new organization in GitHub Enterprise.
//
// Note that only a subset of the org fields are used and org must
// not be nil.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/orgs#create-an-organization
//
//meta:operation POST /admin/organizations
func (s *AdminService) CreateOrg(ctx context.Context, org *Organization, admin string) (*Organization, *Response, error) {
u := "admin/organizations"
orgReq := &createOrgRequest{
Login: org.Login,
Admin: &admin,
}
req, err := s.client.NewRequest("POST", u, orgReq)
if err != nil {
return nil, nil, err
}
o := new(Organization)
resp, err := s.client.Do(ctx, req, o)
if err != nil {
return nil, resp, err
}
return o, resp, nil
}
// renameOrgRequest is a subset of Organization and is used internally
// by RenameOrg and RenameOrgByName to pass only the known fields for the endpoint.
type renameOrgRequest struct {
Login *string `json:"login,omitempty"`
}
// RenameOrgResponse is the response given when renaming an Organization.
type RenameOrgResponse struct {
Message *string `json:"message,omitempty"`
URL *string `json:"url,omitempty"`
}
// RenameOrg renames an organization in GitHub Enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/orgs#update-an-organization-name
//
//meta:operation PATCH /admin/organizations/{org}
func (s *AdminService) RenameOrg(ctx context.Context, org *Organization, newName string) (*RenameOrgResponse, *Response, error) {
return s.RenameOrgByName(ctx, *org.Login, newName)
}
// RenameOrgByName renames an organization in GitHub Enterprise using its current name.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/orgs#update-an-organization-name
//
//meta:operation PATCH /admin/organizations/{org}
func (s *AdminService) RenameOrgByName(ctx context.Context, org, newName string) (*RenameOrgResponse, *Response, error) {
u := fmt.Sprintf("admin/organizations/%v", org)
orgReq := &renameOrgRequest{
Login: &newName,
}
req, err := s.client.NewRequest("PATCH", u, orgReq)
if err != nil {
return nil, nil, err
}
o := new(RenameOrgResponse)
resp, err := s.client.Do(ctx, req, o)
if err != nil {
return nil, resp, err
}
return o, resp, nil
}

View file

@ -1,172 +0,0 @@
// Copyright 2017 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
)
// AdminStats represents a variety of stats of a GitHub Enterprise
// installation.
type AdminStats struct {
Issues *IssueStats `json:"issues,omitempty"`
Hooks *HookStats `json:"hooks,omitempty"`
Milestones *MilestoneStats `json:"milestones,omitempty"`
Orgs *OrgStats `json:"orgs,omitempty"`
Comments *CommentStats `json:"comments,omitempty"`
Pages *PageStats `json:"pages,omitempty"`
Users *UserStats `json:"users,omitempty"`
Gists *GistStats `json:"gists,omitempty"`
Pulls *PullStats `json:"pulls,omitempty"`
Repos *RepoStats `json:"repos,omitempty"`
}
func (s AdminStats) String() string {
return Stringify(s)
}
// IssueStats represents the number of total, open and closed issues.
type IssueStats struct {
TotalIssues *int `json:"total_issues,omitempty"`
OpenIssues *int `json:"open_issues,omitempty"`
ClosedIssues *int `json:"closed_issues,omitempty"`
}
func (s IssueStats) String() string {
return Stringify(s)
}
// HookStats represents the number of total, active and inactive hooks.
type HookStats struct {
TotalHooks *int `json:"total_hooks,omitempty"`
ActiveHooks *int `json:"active_hooks,omitempty"`
InactiveHooks *int `json:"inactive_hooks,omitempty"`
}
func (s HookStats) String() string {
return Stringify(s)
}
// MilestoneStats represents the number of total, open and close milestones.
type MilestoneStats struct {
TotalMilestones *int `json:"total_milestones,omitempty"`
OpenMilestones *int `json:"open_milestones,omitempty"`
ClosedMilestones *int `json:"closed_milestones,omitempty"`
}
func (s MilestoneStats) String() string {
return Stringify(s)
}
// OrgStats represents the number of total, disabled organizations and the team
// and team member count.
type OrgStats struct {
TotalOrgs *int `json:"total_orgs,omitempty"`
DisabledOrgs *int `json:"disabled_orgs,omitempty"`
TotalTeams *int `json:"total_teams,omitempty"`
TotalTeamMembers *int `json:"total_team_members,omitempty"`
}
func (s OrgStats) String() string {
return Stringify(s)
}
// CommentStats represents the number of total comments on commits, gists, issues
// and pull requests.
type CommentStats struct {
TotalCommitComments *int `json:"total_commit_comments,omitempty"`
TotalGistComments *int `json:"total_gist_comments,omitempty"`
TotalIssueComments *int `json:"total_issue_comments,omitempty"`
TotalPullRequestComments *int `json:"total_pull_request_comments,omitempty"`
}
func (s CommentStats) String() string {
return Stringify(s)
}
// PageStats represents the total number of github pages.
type PageStats struct {
TotalPages *int `json:"total_pages,omitempty"`
}
func (s PageStats) String() string {
return Stringify(s)
}
// UserStats represents the number of total, admin and suspended users.
type UserStats struct {
TotalUsers *int `json:"total_users,omitempty"`
AdminUsers *int `json:"admin_users,omitempty"`
SuspendedUsers *int `json:"suspended_users,omitempty"`
}
func (s UserStats) String() string {
return Stringify(s)
}
// GistStats represents the number of total, private and public gists.
type GistStats struct {
TotalGists *int `json:"total_gists,omitempty"`
PrivateGists *int `json:"private_gists,omitempty"`
PublicGists *int `json:"public_gists,omitempty"`
}
func (s GistStats) String() string {
return Stringify(s)
}
// PullStats represents the number of total, merged, mergable and unmergeable
// pull-requests.
type PullStats struct {
TotalPulls *int `json:"total_pulls,omitempty"`
MergedPulls *int `json:"merged_pulls,omitempty"`
MergablePulls *int `json:"mergeable_pulls,omitempty"`
UnmergablePulls *int `json:"unmergeable_pulls,omitempty"`
}
func (s PullStats) String() string {
return Stringify(s)
}
// RepoStats represents the number of total, root, fork, organization repositories
// together with the total number of pushes and wikis.
type RepoStats struct {
TotalRepos *int `json:"total_repos,omitempty"`
RootRepos *int `json:"root_repos,omitempty"`
ForkRepos *int `json:"fork_repos,omitempty"`
OrgRepos *int `json:"org_repos,omitempty"`
TotalPushes *int `json:"total_pushes,omitempty"`
TotalWikis *int `json:"total_wikis,omitempty"`
}
func (s RepoStats) String() string {
return Stringify(s)
}
// GetAdminStats returns a variety of metrics about a GitHub Enterprise
// installation.
//
// Please note that this is only available to site administrators,
// otherwise it will error with a 404 not found (instead of 401 or 403).
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/admin-stats#get-all-statistics
//
//meta:operation GET /enterprise/stats/all
func (s *AdminService) GetAdminStats(ctx context.Context) (*AdminStats, *Response, error) {
u := "enterprise/stats/all"
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
m := new(AdminStats)
resp, err := s.client.Do(ctx, req, m)
if err != nil {
return nil, resp, err
}
return m, resp, nil
}

View file

@ -1,141 +0,0 @@
// Copyright 2019 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// createUserRequest is a subset of User and is used internally
// by CreateUser to pass only the known fields for the endpoint.
type createUserRequest struct {
Login *string `json:"login,omitempty"`
Email *string `json:"email,omitempty"`
}
// CreateUser creates a new user in GitHub Enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#create-a-user
//
//meta:operation POST /admin/users
func (s *AdminService) CreateUser(ctx context.Context, login, email string) (*User, *Response, error) {
u := "admin/users"
userReq := &createUserRequest{
Login: &login,
Email: &email,
}
req, err := s.client.NewRequest("POST", u, userReq)
if err != nil {
return nil, nil, err
}
var user User
resp, err := s.client.Do(ctx, req, &user)
if err != nil {
return nil, resp, err
}
return &user, resp, nil
}
// DeleteUser deletes a user in GitHub Enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#delete-a-user
//
//meta:operation DELETE /admin/users/{username}
func (s *AdminService) DeleteUser(ctx context.Context, username string) (*Response, error) {
u := "admin/users/" + username
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// ImpersonateUserOptions represents the scoping for the OAuth token.
type ImpersonateUserOptions struct {
Scopes []string `json:"scopes,omitempty"`
}
// OAuthAPP represents the GitHub Site Administrator OAuth app.
type OAuthAPP struct {
URL *string `json:"url,omitempty"`
Name *string `json:"name,omitempty"`
ClientID *string `json:"client_id,omitempty"`
}
func (s OAuthAPP) String() string {
return Stringify(s)
}
// UserAuthorization represents the impersonation response.
type UserAuthorization struct {
ID *int64 `json:"id,omitempty"`
URL *string `json:"url,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Token *string `json:"token,omitempty"`
TokenLastEight *string `json:"token_last_eight,omitempty"`
HashedToken *string `json:"hashed_token,omitempty"`
App *OAuthAPP `json:"app,omitempty"`
Note *string `json:"note,omitempty"`
NoteURL *string `json:"note_url,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
Fingerprint *string `json:"fingerprint,omitempty"`
}
// CreateUserImpersonation creates an impersonation OAuth token.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#create-an-impersonation-oauth-token
//
//meta:operation POST /admin/users/{username}/authorizations
func (s *AdminService) CreateUserImpersonation(ctx context.Context, username string, opts *ImpersonateUserOptions) (*UserAuthorization, *Response, error) {
u := fmt.Sprintf("admin/users/%s/authorizations", username)
req, err := s.client.NewRequest("POST", u, opts)
if err != nil {
return nil, nil, err
}
a := new(UserAuthorization)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// DeleteUserImpersonation deletes an impersonation OAuth token.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#delete-an-impersonation-oauth-token
//
//meta:operation DELETE /admin/users/{username}/authorizations
func (s *AdminService) DeleteUserImpersonation(ctx context.Context, username string) (*Response, error) {
u := fmt.Sprintf("admin/users/%s/authorizations", username)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}

View file

@ -1,420 +0,0 @@
// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// AppsService provides access to the installation related functions
// in the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/apps/
type AppsService service
// App represents a GitHub App.
type App struct {
ID *int64 `json:"id,omitempty"`
Slug *string `json:"slug,omitempty"`
NodeID *string `json:"node_id,omitempty"`
Owner *User `json:"owner,omitempty"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
ExternalURL *string `json:"external_url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Permissions *InstallationPermissions `json:"permissions,omitempty"`
Events []string `json:"events,omitempty"`
InstallationsCount *int `json:"installations_count,omitempty"`
}
// InstallationToken represents an installation token.
type InstallationToken struct {
Token *string `json:"token,omitempty"`
ExpiresAt *Timestamp `json:"expires_at,omitempty"`
Permissions *InstallationPermissions `json:"permissions,omitempty"`
Repositories []*Repository `json:"repositories,omitempty"`
}
// InstallationTokenOptions allow restricting a token's access to specific repositories.
type InstallationTokenOptions struct {
// The IDs of the repositories that the installation token can access.
// Providing repository IDs restricts the access of an installation token to specific repositories.
RepositoryIDs []int64 `json:"repository_ids,omitempty"`
// The names of the repositories that the installation token can access.
// Providing repository names restricts the access of an installation token to specific repositories.
Repositories []string `json:"repositories,omitempty"`
// The permissions granted to the access token.
// The permissions object includes the permission names and their access type.
Permissions *InstallationPermissions `json:"permissions,omitempty"`
}
// InstallationPermissions lists the repository and organization permissions for an installation.
//
// Permission names taken from:
//
// https://docs.github.com/enterprise-server@3.0/rest/apps#create-an-installation-access-token-for-an-app
// https://docs.github.com/rest/apps#create-an-installation-access-token-for-an-app
type InstallationPermissions struct {
Actions *string `json:"actions,omitempty"`
Administration *string `json:"administration,omitempty"`
Blocking *string `json:"blocking,omitempty"`
Checks *string `json:"checks,omitempty"`
Contents *string `json:"contents,omitempty"`
ContentReferences *string `json:"content_references,omitempty"`
Deployments *string `json:"deployments,omitempty"`
Emails *string `json:"emails,omitempty"`
Environments *string `json:"environments,omitempty"`
Followers *string `json:"followers,omitempty"`
Issues *string `json:"issues,omitempty"`
Metadata *string `json:"metadata,omitempty"`
Members *string `json:"members,omitempty"`
OrganizationAdministration *string `json:"organization_administration,omitempty"`
OrganizationCustomRoles *string `json:"organization_custom_roles,omitempty"`
OrganizationHooks *string `json:"organization_hooks,omitempty"`
OrganizationPackages *string `json:"organization_packages,omitempty"`
OrganizationPlan *string `json:"organization_plan,omitempty"`
OrganizationPreReceiveHooks *string `json:"organization_pre_receive_hooks,omitempty"`
OrganizationProjects *string `json:"organization_projects,omitempty"`
OrganizationSecrets *string `json:"organization_secrets,omitempty"`
OrganizationSelfHostedRunners *string `json:"organization_self_hosted_runners,omitempty"`
OrganizationUserBlocking *string `json:"organization_user_blocking,omitempty"`
Packages *string `json:"packages,omitempty"`
Pages *string `json:"pages,omitempty"`
PullRequests *string `json:"pull_requests,omitempty"`
RepositoryHooks *string `json:"repository_hooks,omitempty"`
RepositoryProjects *string `json:"repository_projects,omitempty"`
RepositoryPreReceiveHooks *string `json:"repository_pre_receive_hooks,omitempty"`
Secrets *string `json:"secrets,omitempty"`
SecretScanningAlerts *string `json:"secret_scanning_alerts,omitempty"`
SecurityEvents *string `json:"security_events,omitempty"`
SingleFile *string `json:"single_file,omitempty"`
Statuses *string `json:"statuses,omitempty"`
TeamDiscussions *string `json:"team_discussions,omitempty"`
VulnerabilityAlerts *string `json:"vulnerability_alerts,omitempty"`
Workflows *string `json:"workflows,omitempty"`
}
// InstallationRequest represents a pending GitHub App installation request.
type InstallationRequest struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
Account *User `json:"account,omitempty"`
Requester *User `json:"requester,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
}
// Installation represents a GitHub Apps installation.
type Installation struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
AppID *int64 `json:"app_id,omitempty"`
AppSlug *string `json:"app_slug,omitempty"`
TargetID *int64 `json:"target_id,omitempty"`
Account *User `json:"account,omitempty"`
AccessTokensURL *string `json:"access_tokens_url,omitempty"`
RepositoriesURL *string `json:"repositories_url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
TargetType *string `json:"target_type,omitempty"`
SingleFileName *string `json:"single_file_name,omitempty"`
RepositorySelection *string `json:"repository_selection,omitempty"`
Events []string `json:"events,omitempty"`
SingleFilePaths []string `json:"single_file_paths,omitempty"`
Permissions *InstallationPermissions `json:"permissions,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
HasMultipleSingleFiles *bool `json:"has_multiple_single_files,omitempty"`
SuspendedBy *User `json:"suspended_by,omitempty"`
SuspendedAt *Timestamp `json:"suspended_at,omitempty"`
}
// Attachment represents a GitHub Apps attachment.
type Attachment struct {
ID *int64 `json:"id,omitempty"`
Title *string `json:"title,omitempty"`
Body *string `json:"body,omitempty"`
}
// ContentReference represents a reference to a URL in an issue or pull request.
type ContentReference struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
Reference *string `json:"reference,omitempty"`
}
func (i Installation) String() string {
return Stringify(i)
}
// Get a single GitHub App. Passing the empty string will get
// the authenticated GitHub App.
//
// Note: appSlug is just the URL-friendly name of your GitHub App.
// You can find this on the settings page for your GitHub App
// (e.g., https://github.com/settings/apps/:app_slug).
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-an-app
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-the-authenticated-app
//
//meta:operation GET /app
//meta:operation GET /apps/{app_slug}
func (s *AppsService) Get(ctx context.Context, appSlug string) (*App, *Response, error) {
var u string
if appSlug != "" {
u = fmt.Sprintf("apps/%v", appSlug)
} else {
u = "app"
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
app := new(App)
resp, err := s.client.Do(ctx, req, app)
if err != nil {
return nil, resp, err
}
return app, resp, nil
}
// ListInstallationRequests lists the pending installation requests that the current GitHub App has.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#list-installation-requests-for-the-authenticated-app
//
//meta:operation GET /app/installation-requests
func (s *AppsService) ListInstallationRequests(ctx context.Context, opts *ListOptions) ([]*InstallationRequest, *Response, error) {
u, err := addOptions("app/installation-requests", opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var i []*InstallationRequest
resp, err := s.client.Do(ctx, req, &i)
if err != nil {
return nil, resp, err
}
return i, resp, nil
}
// ListInstallations lists the installations that the current GitHub App has.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#list-installations-for-the-authenticated-app
//
//meta:operation GET /app/installations
func (s *AppsService) ListInstallations(ctx context.Context, opts *ListOptions) ([]*Installation, *Response, error) {
u, err := addOptions("app/installations", opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var i []*Installation
resp, err := s.client.Do(ctx, req, &i)
if err != nil {
return nil, resp, err
}
return i, resp, nil
}
// GetInstallation returns the specified installation.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-an-installation-for-the-authenticated-app
//
//meta:operation GET /app/installations/{installation_id}
func (s *AppsService) GetInstallation(ctx context.Context, id int64) (*Installation, *Response, error) {
return s.getInstallation(ctx, fmt.Sprintf("app/installations/%v", id))
}
// ListUserInstallations lists installations that are accessible to the authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/apps/installations#list-app-installations-accessible-to-the-user-access-token
//
//meta:operation GET /user/installations
func (s *AppsService) ListUserInstallations(ctx context.Context, opts *ListOptions) ([]*Installation, *Response, error) {
u, err := addOptions("user/installations", opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var i struct {
Installations []*Installation `json:"installations"`
}
resp, err := s.client.Do(ctx, req, &i)
if err != nil {
return nil, resp, err
}
return i.Installations, resp, nil
}
// SuspendInstallation suspends the specified installation.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#suspend-an-app-installation
//
//meta:operation PUT /app/installations/{installation_id}/suspended
func (s *AppsService) SuspendInstallation(ctx context.Context, id int64) (*Response, error) {
u := fmt.Sprintf("app/installations/%v/suspended", id)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// UnsuspendInstallation unsuspends the specified installation.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#unsuspend-an-app-installation
//
//meta:operation DELETE /app/installations/{installation_id}/suspended
func (s *AppsService) UnsuspendInstallation(ctx context.Context, id int64) (*Response, error) {
u := fmt.Sprintf("app/installations/%v/suspended", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// DeleteInstallation deletes the specified installation.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#delete-an-installation-for-the-authenticated-app
//
//meta:operation DELETE /app/installations/{installation_id}
func (s *AppsService) DeleteInstallation(ctx context.Context, id int64) (*Response, error) {
u := fmt.Sprintf("app/installations/%v", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// CreateInstallationToken creates a new installation token.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#create-an-installation-access-token-for-an-app
//
//meta:operation POST /app/installations/{installation_id}/access_tokens
func (s *AppsService) CreateInstallationToken(ctx context.Context, id int64, opts *InstallationTokenOptions) (*InstallationToken, *Response, error) {
u := fmt.Sprintf("app/installations/%v/access_tokens", id)
req, err := s.client.NewRequest("POST", u, opts)
if err != nil {
return nil, nil, err
}
t := new(InstallationToken)
resp, err := s.client.Do(ctx, req, t)
if err != nil {
return nil, resp, err
}
return t, resp, nil
}
// CreateAttachment creates a new attachment on user comment containing a url.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.3/rest/reference/apps#create-a-content-attachment
//
//meta:operation POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments
func (s *AppsService) CreateAttachment(ctx context.Context, contentReferenceID int64, title, body string) (*Attachment, *Response, error) {
u := fmt.Sprintf("content_references/%v/attachments", contentReferenceID)
payload := &Attachment{Title: String(title), Body: String(body)}
req, err := s.client.NewRequest("POST", u, payload)
if err != nil {
return nil, nil, err
}
// TODO: remove custom Accept headers when APIs fully launch.
req.Header.Set("Accept", mediaTypeContentAttachmentsPreview)
m := &Attachment{}
resp, err := s.client.Do(ctx, req, m)
if err != nil {
return nil, resp, err
}
return m, resp, nil
}
// FindOrganizationInstallation finds the organization's installation information.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-an-organization-installation-for-the-authenticated-app
//
//meta:operation GET /orgs/{org}/installation
func (s *AppsService) FindOrganizationInstallation(ctx context.Context, org string) (*Installation, *Response, error) {
return s.getInstallation(ctx, fmt.Sprintf("orgs/%v/installation", org))
}
// FindRepositoryInstallation finds the repository's installation information.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-a-repository-installation-for-the-authenticated-app
//
//meta:operation GET /repos/{owner}/{repo}/installation
func (s *AppsService) FindRepositoryInstallation(ctx context.Context, owner, repo string) (*Installation, *Response, error) {
return s.getInstallation(ctx, fmt.Sprintf("repos/%v/%v/installation", owner, repo))
}
// FindRepositoryInstallationByID finds the repository's installation information.
//
// Note: FindRepositoryInstallationByID uses the undocumented GitHub API endpoint "GET /repositories/{repository_id}/installation".
//
//meta:operation GET /repositories/{repository_id}/installation
func (s *AppsService) FindRepositoryInstallationByID(ctx context.Context, id int64) (*Installation, *Response, error) {
return s.getInstallation(ctx, fmt.Sprintf("repositories/%d/installation", id))
}
// FindUserInstallation finds the user's installation information.
//
// GitHub API docs: https://docs.github.com/rest/apps/apps#get-a-user-installation-for-the-authenticated-app
//
//meta:operation GET /users/{username}/installation
func (s *AppsService) FindUserInstallation(ctx context.Context, user string) (*Installation, *Response, error) {
return s.getInstallation(ctx, fmt.Sprintf("users/%v/installation", user))
}
func (s *AppsService) getInstallation(ctx context.Context, url string) (*Installation, *Response, error) {
req, err := s.client.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
i := new(Installation)
resp, err := s.client.Do(ctx, req, i)
if err != nil {
return nil, resp, err
}
return i, resp, nil
}

View file

@ -1,293 +0,0 @@
// Copyright 2015 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// Scope models a GitHub authorization scope.
//
// GitHub API docs: https://docs.github.com/rest/oauth/#scopes
type Scope string
// This is the set of scopes for GitHub API V3
const (
ScopeNone Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact?
ScopeUser Scope = "user"
ScopeUserEmail Scope = "user:email"
ScopeUserFollow Scope = "user:follow"
ScopePublicRepo Scope = "public_repo"
ScopeRepo Scope = "repo"
ScopeRepoDeployment Scope = "repo_deployment"
ScopeRepoStatus Scope = "repo:status"
ScopeDeleteRepo Scope = "delete_repo"
ScopeNotifications Scope = "notifications"
ScopeGist Scope = "gist"
ScopeReadRepoHook Scope = "read:repo_hook"
ScopeWriteRepoHook Scope = "write:repo_hook"
ScopeAdminRepoHook Scope = "admin:repo_hook"
ScopeAdminOrgHook Scope = "admin:org_hook"
ScopeReadOrg Scope = "read:org"
ScopeWriteOrg Scope = "write:org"
ScopeAdminOrg Scope = "admin:org"
ScopeReadPublicKey Scope = "read:public_key"
ScopeWritePublicKey Scope = "write:public_key"
ScopeAdminPublicKey Scope = "admin:public_key"
ScopeReadGPGKey Scope = "read:gpg_key"
ScopeWriteGPGKey Scope = "write:gpg_key"
ScopeAdminGPGKey Scope = "admin:gpg_key"
ScopeSecurityEvents Scope = "security_events"
)
// AuthorizationsService handles communication with the authorization related
// methods of the GitHub API.
//
// This service requires HTTP Basic Authentication; it cannot be accessed using
// an OAuth token.
//
// GitHub API docs: https://docs.github.com/rest/oauth-authorizations
type AuthorizationsService service
// Authorization represents an individual GitHub authorization.
type Authorization struct {
ID *int64 `json:"id,omitempty"`
URL *string `json:"url,omitempty"`
Scopes []Scope `json:"scopes,omitempty"`
Token *string `json:"token,omitempty"`
TokenLastEight *string `json:"token_last_eight,omitempty"`
HashedToken *string `json:"hashed_token,omitempty"`
App *AuthorizationApp `json:"app,omitempty"`
Note *string `json:"note,omitempty"`
NoteURL *string `json:"note_url,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
Fingerprint *string `json:"fingerprint,omitempty"`
// User is only populated by the Check and Reset methods.
User *User `json:"user,omitempty"`
}
func (a Authorization) String() string {
return Stringify(a)
}
// AuthorizationApp represents an individual GitHub app (in the context of authorization).
type AuthorizationApp struct {
URL *string `json:"url,omitempty"`
Name *string `json:"name,omitempty"`
ClientID *string `json:"client_id,omitempty"`
}
func (a AuthorizationApp) String() string {
return Stringify(a)
}
// Grant represents an OAuth application that has been granted access to an account.
type Grant struct {
ID *int64 `json:"id,omitempty"`
URL *string `json:"url,omitempty"`
App *AuthorizationApp `json:"app,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
func (g Grant) String() string {
return Stringify(g)
}
// AuthorizationRequest represents a request to create an authorization.
type AuthorizationRequest struct {
Scopes []Scope `json:"scopes,omitempty"`
Note *string `json:"note,omitempty"`
NoteURL *string `json:"note_url,omitempty"`
ClientID *string `json:"client_id,omitempty"`
ClientSecret *string `json:"client_secret,omitempty"`
Fingerprint *string `json:"fingerprint,omitempty"`
}
func (a AuthorizationRequest) String() string {
return Stringify(a)
}
// AuthorizationUpdateRequest represents a request to update an authorization.
//
// Note that for any one update, you must only provide one of the "scopes"
// fields. That is, you may provide only one of "Scopes", or "AddScopes", or
// "RemoveScopes".
//
// GitHub API docs: https://docs.github.com/rest/oauth-authorizations#update-an-existing-authorization
type AuthorizationUpdateRequest struct {
Scopes []string `json:"scopes,omitempty"`
AddScopes []string `json:"add_scopes,omitempty"`
RemoveScopes []string `json:"remove_scopes,omitempty"`
Note *string `json:"note,omitempty"`
NoteURL *string `json:"note_url,omitempty"`
Fingerprint *string `json:"fingerprint,omitempty"`
}
func (a AuthorizationUpdateRequest) String() string {
return Stringify(a)
}
// Check if an OAuth token is valid for a specific app.
//
// Note that this operation requires the use of BasicAuth, but where the
// username is the OAuth application clientID, and the password is its
// clientSecret. Invalid tokens will return a 404 Not Found.
//
// The returned Authorization.User field will be populated.
//
// GitHub API docs: https://docs.github.com/rest/apps/oauth-applications#check-a-token
//
//meta:operation POST /applications/{client_id}/token
func (s *AuthorizationsService) Check(ctx context.Context, clientID, accessToken string) (*Authorization, *Response, error) {
u := fmt.Sprintf("applications/%v/token", clientID)
reqBody := &struct {
AccessToken string `json:"access_token"`
}{AccessToken: accessToken}
req, err := s.client.NewRequest("POST", u, reqBody)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeOAuthAppPreview)
a := new(Authorization)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// Reset is used to reset a valid OAuth token without end user involvement.
// Applications must save the "token" property in the response, because changes
// take effect immediately.
//
// Note that this operation requires the use of BasicAuth, but where the
// username is the OAuth application clientID, and the password is its
// clientSecret. Invalid tokens will return a 404 Not Found.
//
// The returned Authorization.User field will be populated.
//
// GitHub API docs: https://docs.github.com/rest/apps/oauth-applications#reset-a-token
//
//meta:operation PATCH /applications/{client_id}/token
func (s *AuthorizationsService) Reset(ctx context.Context, clientID, accessToken string) (*Authorization, *Response, error) {
u := fmt.Sprintf("applications/%v/token", clientID)
reqBody := &struct {
AccessToken string `json:"access_token"`
}{AccessToken: accessToken}
req, err := s.client.NewRequest("PATCH", u, reqBody)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeOAuthAppPreview)
a := new(Authorization)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// Revoke an authorization for an application.
//
// Note that this operation requires the use of BasicAuth, but where the
// username is the OAuth application clientID, and the password is its
// clientSecret. Invalid tokens will return a 404 Not Found.
//
// GitHub API docs: https://docs.github.com/rest/apps/oauth-applications#delete-an-app-token
//
//meta:operation DELETE /applications/{client_id}/token
func (s *AuthorizationsService) Revoke(ctx context.Context, clientID, accessToken string) (*Response, error) {
u := fmt.Sprintf("applications/%v/token", clientID)
reqBody := &struct {
AccessToken string `json:"access_token"`
}{AccessToken: accessToken}
req, err := s.client.NewRequest("DELETE", u, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Accept", mediaTypeOAuthAppPreview)
return s.client.Do(ctx, req, nil)
}
// DeleteGrant deletes an OAuth application grant. Deleting an application's
// grant will also delete all OAuth tokens associated with the application for
// the user.
//
// GitHub API docs: https://docs.github.com/rest/apps/oauth-applications#delete-an-app-authorization
//
//meta:operation DELETE /applications/{client_id}/grant
func (s *AuthorizationsService) DeleteGrant(ctx context.Context, clientID, accessToken string) (*Response, error) {
u := fmt.Sprintf("applications/%v/grant", clientID)
reqBody := &struct {
AccessToken string `json:"access_token"`
}{AccessToken: accessToken}
req, err := s.client.NewRequest("DELETE", u, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Accept", mediaTypeOAuthAppPreview)
return s.client.Do(ctx, req, nil)
}
// CreateImpersonation creates an impersonation OAuth token.
//
// This requires admin permissions. With the returned Authorization.Token
// you can e.g. create or delete a user's public SSH key. NOTE: creating a
// new token automatically revokes an existing one.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#create-an-impersonation-oauth-token
//
//meta:operation POST /admin/users/{username}/authorizations
func (s *AuthorizationsService) CreateImpersonation(ctx context.Context, username string, authReq *AuthorizationRequest) (*Authorization, *Response, error) {
u := fmt.Sprintf("admin/users/%v/authorizations", username)
req, err := s.client.NewRequest("POST", u, authReq)
if err != nil {
return nil, nil, err
}
a := new(Authorization)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// DeleteImpersonation deletes an impersonation OAuth token.
//
// NOTE: there can be only one at a time.
//
// GitHub API docs: https://docs.github.com/enterprise-server@3.10/rest/enterprise-admin/users#delete-an-impersonation-oauth-token
//
//meta:operation DELETE /admin/users/{username}/authorizations
func (s *AuthorizationsService) DeleteImpersonation(ctx context.Context, username string) (*Response, error) {
u := fmt.Sprintf("admin/users/%v/authorizations", username)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,215 +0,0 @@
// Copyright 2021 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// BillingService provides access to the billing related functions
// in the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/billing
type BillingService service
// ActionBilling represents a GitHub Action billing.
type ActionBilling struct {
TotalMinutesUsed float64 `json:"total_minutes_used"`
TotalPaidMinutesUsed float64 `json:"total_paid_minutes_used"`
IncludedMinutes float64 `json:"included_minutes"`
MinutesUsedBreakdown MinutesUsedBreakdown `json:"minutes_used_breakdown"`
}
// MinutesUsedBreakdown counts the actions minutes used by machine type (e.g. UBUNTU, WINDOWS, MACOS).
type MinutesUsedBreakdown = map[string]int
// PackageBilling represents a GitHub Package billing.
type PackageBilling struct {
TotalGigabytesBandwidthUsed int `json:"total_gigabytes_bandwidth_used"`
TotalPaidGigabytesBandwidthUsed int `json:"total_paid_gigabytes_bandwidth_used"`
IncludedGigabytesBandwidth float64 `json:"included_gigabytes_bandwidth"`
}
// StorageBilling represents a GitHub Storage billing.
type StorageBilling struct {
DaysLeftInBillingCycle int `json:"days_left_in_billing_cycle"`
EstimatedPaidStorageForMonth float64 `json:"estimated_paid_storage_for_month"`
EstimatedStorageForMonth float64 `json:"estimated_storage_for_month"`
}
// ActiveCommitters represents the total active committers across all repositories in an Organization.
type ActiveCommitters struct {
TotalAdvancedSecurityCommitters int `json:"total_advanced_security_committers"`
Repositories []*RepositoryActiveCommitters `json:"repositories,omitempty"`
}
// RepositoryActiveCommitters represents active committers on each repository.
type RepositoryActiveCommitters struct {
Name *string `json:"name,omitempty"`
AdvancedSecurityCommitters *int `json:"advanced_security_committers,omitempty"`
AdvancedSecurityCommittersBreakdown []*AdvancedSecurityCommittersBreakdown `json:"advanced_security_committers_breakdown,omitempty"`
}
// AdvancedSecurityCommittersBreakdown represents the user activity breakdown for ActiveCommitters.
type AdvancedSecurityCommittersBreakdown struct {
UserLogin *string `json:"user_login,omitempty"`
LastPushedDate *string `json:"last_pushed_date,omitempty"`
}
// GetActionsBillingOrg returns the summary of the free and paid GitHub Actions minutes used for an Org.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-github-actions-billing-for-an-organization
//
//meta:operation GET /orgs/{org}/settings/billing/actions
func (s *BillingService) GetActionsBillingOrg(ctx context.Context, org string) (*ActionBilling, *Response, error) {
u := fmt.Sprintf("orgs/%v/settings/billing/actions", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
actionsOrgBilling := new(ActionBilling)
resp, err := s.client.Do(ctx, req, actionsOrgBilling)
if err != nil {
return nil, resp, err
}
return actionsOrgBilling, resp, nil
}
// GetPackagesBillingOrg returns the free and paid storage used for GitHub Packages in gigabytes for an Org.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-github-packages-billing-for-an-organization
//
//meta:operation GET /orgs/{org}/settings/billing/packages
func (s *BillingService) GetPackagesBillingOrg(ctx context.Context, org string) (*PackageBilling, *Response, error) {
u := fmt.Sprintf("orgs/%v/settings/billing/packages", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
packagesOrgBilling := new(PackageBilling)
resp, err := s.client.Do(ctx, req, packagesOrgBilling)
if err != nil {
return nil, resp, err
}
return packagesOrgBilling, resp, nil
}
// GetStorageBillingOrg returns the estimated paid and estimated total storage used for GitHub Actions
// and GitHub Packages in gigabytes for an Org.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-shared-storage-billing-for-an-organization
//
//meta:operation GET /orgs/{org}/settings/billing/shared-storage
func (s *BillingService) GetStorageBillingOrg(ctx context.Context, org string) (*StorageBilling, *Response, error) {
u := fmt.Sprintf("orgs/%v/settings/billing/shared-storage", org)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
storageOrgBilling := new(StorageBilling)
resp, err := s.client.Do(ctx, req, storageOrgBilling)
if err != nil {
return nil, resp, err
}
return storageOrgBilling, resp, nil
}
// GetAdvancedSecurityActiveCommittersOrg returns the GitHub Advanced Security active committers for an organization per repository.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/billing/billing#get-github-advanced-security-active-committers-for-an-organization
//
//meta:operation GET /orgs/{org}/settings/billing/advanced-security
func (s *BillingService) GetAdvancedSecurityActiveCommittersOrg(ctx context.Context, org string, opts *ListOptions) (*ActiveCommitters, *Response, error) {
u := fmt.Sprintf("orgs/%v/settings/billing/advanced-security", org)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
activeOrgCommitters := new(ActiveCommitters)
resp, err := s.client.Do(ctx, req, activeOrgCommitters)
if err != nil {
return nil, resp, err
}
return activeOrgCommitters, resp, nil
}
// GetActionsBillingUser returns the summary of the free and paid GitHub Actions minutes used for a user.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-github-actions-billing-for-a-user
//
//meta:operation GET /users/{username}/settings/billing/actions
func (s *BillingService) GetActionsBillingUser(ctx context.Context, user string) (*ActionBilling, *Response, error) {
u := fmt.Sprintf("users/%v/settings/billing/actions", user)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
actionsUserBilling := new(ActionBilling)
resp, err := s.client.Do(ctx, req, actionsUserBilling)
if err != nil {
return nil, resp, err
}
return actionsUserBilling, resp, nil
}
// GetPackagesBillingUser returns the free and paid storage used for GitHub Packages in gigabytes for a user.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-github-packages-billing-for-a-user
//
//meta:operation GET /users/{username}/settings/billing/packages
func (s *BillingService) GetPackagesBillingUser(ctx context.Context, user string) (*PackageBilling, *Response, error) {
u := fmt.Sprintf("users/%v/settings/billing/packages", user)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
packagesUserBilling := new(PackageBilling)
resp, err := s.client.Do(ctx, req, packagesUserBilling)
if err != nil {
return nil, resp, err
}
return packagesUserBilling, resp, nil
}
// GetStorageBillingUser returns the estimated paid and estimated total storage used for GitHub Actions
// and GitHub Packages in gigabytes for a user.
//
// GitHub API docs: https://docs.github.com/rest/billing/billing#get-shared-storage-billing-for-a-user
//
//meta:operation GET /users/{username}/settings/billing/shared-storage
func (s *BillingService) GetStorageBillingUser(ctx context.Context, user string) (*StorageBilling, *Response, error) {
u := fmt.Sprintf("users/%v/settings/billing/shared-storage", user)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
storageUserBilling := new(StorageBilling)
resp, err := s.client.Do(ctx, req, storageUserBilling)
if err != nil {
return nil, resp, err
}
return storageUserBilling, resp, nil
}

View file

@ -1,475 +0,0 @@
// Copyright 2018 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ChecksService provides access to the Checks API in the
// GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/checks/
type ChecksService service
// CheckRun represents a GitHub check run on a repository associated with a GitHub app.
type CheckRun struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
HeadSHA *string `json:"head_sha,omitempty"`
ExternalID *string `json:"external_id,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
DetailsURL *string `json:"details_url,omitempty"`
Status *string `json:"status,omitempty"`
Conclusion *string `json:"conclusion,omitempty"`
StartedAt *Timestamp `json:"started_at,omitempty"`
CompletedAt *Timestamp `json:"completed_at,omitempty"`
Output *CheckRunOutput `json:"output,omitempty"`
Name *string `json:"name,omitempty"`
CheckSuite *CheckSuite `json:"check_suite,omitempty"`
App *App `json:"app,omitempty"`
PullRequests []*PullRequest `json:"pull_requests,omitempty"`
}
// CheckRunOutput represents the output of a CheckRun.
type CheckRunOutput struct {
Title *string `json:"title,omitempty"`
Summary *string `json:"summary,omitempty"`
Text *string `json:"text,omitempty"`
AnnotationsCount *int `json:"annotations_count,omitempty"`
AnnotationsURL *string `json:"annotations_url,omitempty"`
Annotations []*CheckRunAnnotation `json:"annotations,omitempty"`
Images []*CheckRunImage `json:"images,omitempty"`
}
// CheckRunAnnotation represents an annotation object for a CheckRun output.
type CheckRunAnnotation struct {
Path *string `json:"path,omitempty"`
StartLine *int `json:"start_line,omitempty"`
EndLine *int `json:"end_line,omitempty"`
StartColumn *int `json:"start_column,omitempty"`
EndColumn *int `json:"end_column,omitempty"`
AnnotationLevel *string `json:"annotation_level,omitempty"`
Message *string `json:"message,omitempty"`
Title *string `json:"title,omitempty"`
RawDetails *string `json:"raw_details,omitempty"`
}
// CheckRunImage represents an image object for a CheckRun output.
type CheckRunImage struct {
Alt *string `json:"alt,omitempty"`
ImageURL *string `json:"image_url,omitempty"`
Caption *string `json:"caption,omitempty"`
}
// CheckSuite represents a suite of check runs.
type CheckSuite struct {
ID *int64 `json:"id,omitempty"`
NodeID *string `json:"node_id,omitempty"`
HeadBranch *string `json:"head_branch,omitempty"`
HeadSHA *string `json:"head_sha,omitempty"`
URL *string `json:"url,omitempty"`
BeforeSHA *string `json:"before,omitempty"`
AfterSHA *string `json:"after,omitempty"`
Status *string `json:"status,omitempty"`
Conclusion *string `json:"conclusion,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
App *App `json:"app,omitempty"`
Repository *Repository `json:"repository,omitempty"`
PullRequests []*PullRequest `json:"pull_requests,omitempty"`
// The following fields are only populated by Webhook events.
HeadCommit *Commit `json:"head_commit,omitempty"`
}
func (c CheckRun) String() string {
return Stringify(c)
}
func (c CheckSuite) String() string {
return Stringify(c)
}
// GetCheckRun gets a check-run for a repository.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#get-a-check-run
//
//meta:operation GET /repos/{owner}/{repo}/check-runs/{check_run_id}
func (s *ChecksService) GetCheckRun(ctx context.Context, owner, repo string, checkRunID int64) (*CheckRun, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-runs/%v", owner, repo, checkRunID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
checkRun := new(CheckRun)
resp, err := s.client.Do(ctx, req, checkRun)
if err != nil {
return nil, resp, err
}
return checkRun, resp, nil
}
// GetCheckSuite gets a single check suite.
//
// GitHub API docs: https://docs.github.com/rest/checks/suites#get-a-check-suite
//
//meta:operation GET /repos/{owner}/{repo}/check-suites/{check_suite_id}
func (s *ChecksService) GetCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64) (*CheckSuite, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-suites/%v", owner, repo, checkSuiteID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
checkSuite := new(CheckSuite)
resp, err := s.client.Do(ctx, req, checkSuite)
if err != nil {
return nil, resp, err
}
return checkSuite, resp, nil
}
// CreateCheckRunOptions sets up parameters needed to create a CheckRun.
type CreateCheckRunOptions struct {
Name string `json:"name"` // The name of the check (e.g., "code-coverage"). (Required.)
HeadSHA string `json:"head_sha"` // The SHA of the commit. (Required.)
DetailsURL *string `json:"details_url,omitempty"` // The URL of the integrator's site that has the full details of the check. (Optional.)
ExternalID *string `json:"external_id,omitempty"` // A reference for the run on the integrator's system. (Optional.)
Status *string `json:"status,omitempty"` // The current status. Can be one of "queued", "in_progress", or "completed". Default: "queued". (Optional.)
Conclusion *string `json:"conclusion,omitempty"` // Can be one of "success", "failure", "neutral", "cancelled", "skipped", "timed_out", or "action_required". (Optional. Required if you provide a status of "completed".)
StartedAt *Timestamp `json:"started_at,omitempty"` // The time that the check run began. (Optional.)
CompletedAt *Timestamp `json:"completed_at,omitempty"` // The time the check completed. (Optional. Required if you provide conclusion.)
Output *CheckRunOutput `json:"output,omitempty"` // Provide descriptive details about the run. (Optional)
Actions []*CheckRunAction `json:"actions,omitempty"` // Possible further actions the integrator can perform, which a user may trigger. (Optional.)
}
// CheckRunAction exposes further actions the integrator can perform, which a user may trigger.
type CheckRunAction struct {
Label string `json:"label"` // The text to be displayed on a button in the web UI. The maximum size is 20 characters. (Required.)
Description string `json:"description"` // A short explanation of what this action would do. The maximum size is 40 characters. (Required.)
Identifier string `json:"identifier"` // A reference for the action on the integrator's system. The maximum size is 20 characters. (Required.)
}
// CreateCheckRun creates a check run for repository.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#create-a-check-run
//
//meta:operation POST /repos/{owner}/{repo}/check-runs
func (s *ChecksService) CreateCheckRun(ctx context.Context, owner, repo string, opts CreateCheckRunOptions) (*CheckRun, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-runs", owner, repo)
req, err := s.client.NewRequest("POST", u, opts)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
checkRun := new(CheckRun)
resp, err := s.client.Do(ctx, req, checkRun)
if err != nil {
return nil, resp, err
}
return checkRun, resp, nil
}
// UpdateCheckRunOptions sets up parameters needed to update a CheckRun.
type UpdateCheckRunOptions struct {
Name string `json:"name"` // The name of the check (e.g., "code-coverage"). (Required.)
DetailsURL *string `json:"details_url,omitempty"` // The URL of the integrator's site that has the full details of the check. (Optional.)
ExternalID *string `json:"external_id,omitempty"` // A reference for the run on the integrator's system. (Optional.)
Status *string `json:"status,omitempty"` // The current status. Can be one of "queued", "in_progress", or "completed". Default: "queued". (Optional.)
Conclusion *string `json:"conclusion,omitempty"` // Can be one of "success", "failure", "neutral", "cancelled", "skipped", "timed_out", or "action_required". (Optional. Required if you provide a status of "completed".)
CompletedAt *Timestamp `json:"completed_at,omitempty"` // The time the check completed. (Optional. Required if you provide conclusion.)
Output *CheckRunOutput `json:"output,omitempty"` // Provide descriptive details about the run. (Optional)
Actions []*CheckRunAction `json:"actions,omitempty"` // Possible further actions the integrator can perform, which a user may trigger. (Optional.)
}
// UpdateCheckRun updates a check run for a specific commit in a repository.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#update-a-check-run
//
//meta:operation PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}
func (s *ChecksService) UpdateCheckRun(ctx context.Context, owner, repo string, checkRunID int64, opts UpdateCheckRunOptions) (*CheckRun, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-runs/%v", owner, repo, checkRunID)
req, err := s.client.NewRequest("PATCH", u, opts)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
checkRun := new(CheckRun)
resp, err := s.client.Do(ctx, req, checkRun)
if err != nil {
return nil, resp, err
}
return checkRun, resp, nil
}
// ListCheckRunAnnotations lists the annotations for a check run.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#list-check-run-annotations
//
//meta:operation GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations
func (s *ChecksService) ListCheckRunAnnotations(ctx context.Context, owner, repo string, checkRunID int64, opts *ListOptions) ([]*CheckRunAnnotation, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-runs/%v/annotations", owner, repo, checkRunID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
var checkRunAnnotations []*CheckRunAnnotation
resp, err := s.client.Do(ctx, req, &checkRunAnnotations)
if err != nil {
return nil, resp, err
}
return checkRunAnnotations, resp, nil
}
// ListCheckRunsOptions represents parameters to list check runs.
type ListCheckRunsOptions struct {
CheckName *string `url:"check_name,omitempty"` // Returns check runs with the specified name.
Status *string `url:"status,omitempty"` // Returns check runs with the specified status. Can be one of "queued", "in_progress", or "completed".
Filter *string `url:"filter,omitempty"` // Filters check runs by their completed_at timestamp. Can be one of "latest" (returning the most recent check runs) or "all". Default: "latest"
AppID *int64 `url:"app_id,omitempty"` // Filters check runs by GitHub App ID.
ListOptions
}
// ListCheckRunsResults represents the result of a check run list.
type ListCheckRunsResults struct {
Total *int `json:"total_count,omitempty"`
CheckRuns []*CheckRun `json:"check_runs,omitempty"`
}
// ListCheckRunsForRef lists check runs for a specific ref.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#list-check-runs-for-a-git-reference
//
//meta:operation GET /repos/{owner}/{repo}/commits/{ref}/check-runs
func (s *ChecksService) ListCheckRunsForRef(ctx context.Context, owner, repo, ref string, opts *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/commits/%v/check-runs", owner, repo, refURLEscape(ref))
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
var checkRunResults *ListCheckRunsResults
resp, err := s.client.Do(ctx, req, &checkRunResults)
if err != nil {
return nil, resp, err
}
return checkRunResults, resp, nil
}
// ListCheckRunsCheckSuite lists check runs for a check suite.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#list-check-runs-in-a-check-suite
//
//meta:operation GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs
func (s *ChecksService) ListCheckRunsCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64, opts *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-suites/%v/check-runs", owner, repo, checkSuiteID)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
var checkRunResults *ListCheckRunsResults
resp, err := s.client.Do(ctx, req, &checkRunResults)
if err != nil {
return nil, resp, err
}
return checkRunResults, resp, nil
}
// ReRequestCheckRun triggers GitHub to rerequest an existing check run.
//
// GitHub API docs: https://docs.github.com/rest/checks/runs#rerequest-a-check-run
//
//meta:operation POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest
func (s *ChecksService) ReRequestCheckRun(ctx context.Context, owner, repo string, checkRunID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-runs/%v/rerequest", owner, repo, checkRunID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
return s.client.Do(ctx, req, nil)
}
// ListCheckSuiteOptions represents parameters to list check suites.
type ListCheckSuiteOptions struct {
CheckName *string `url:"check_name,omitempty"` // Filters checks suites by the name of the check run.
AppID *int `url:"app_id,omitempty"` // Filters check suites by GitHub App id.
ListOptions
}
// ListCheckSuiteResults represents the result of a check run list.
type ListCheckSuiteResults struct {
Total *int `json:"total_count,omitempty"`
CheckSuites []*CheckSuite `json:"check_suites,omitempty"`
}
// ListCheckSuitesForRef lists check suite for a specific ref.
//
// GitHub API docs: https://docs.github.com/rest/checks/suites#list-check-suites-for-a-git-reference
//
//meta:operation GET /repos/{owner}/{repo}/commits/{ref}/check-suites
func (s *ChecksService) ListCheckSuitesForRef(ctx context.Context, owner, repo, ref string, opts *ListCheckSuiteOptions) (*ListCheckSuiteResults, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/commits/%v/check-suites", owner, repo, refURLEscape(ref))
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
var checkSuiteResults *ListCheckSuiteResults
resp, err := s.client.Do(ctx, req, &checkSuiteResults)
if err != nil {
return nil, resp, err
}
return checkSuiteResults, resp, nil
}
// AutoTriggerCheck enables or disables automatic creation of CheckSuite events upon pushes to the repository.
type AutoTriggerCheck struct {
AppID *int64 `json:"app_id,omitempty"` // The id of the GitHub App. (Required.)
Setting *bool `json:"setting,omitempty"` // Set to "true" to enable automatic creation of CheckSuite events upon pushes to the repository, or "false" to disable them. Default: "true" (Required.)
}
// CheckSuitePreferenceOptions set options for check suite preferences for a repository.
type CheckSuitePreferenceOptions struct {
AutoTriggerChecks []*AutoTriggerCheck `json:"auto_trigger_checks,omitempty"` // A slice of auto trigger checks that can be set for a check suite in a repository.
}
// CheckSuitePreferenceResults represents the results of the preference set operation.
type CheckSuitePreferenceResults struct {
Preferences *PreferenceList `json:"preferences,omitempty"`
Repository *Repository `json:"repository,omitempty"`
}
// PreferenceList represents a list of auto trigger checks for repository
type PreferenceList struct {
AutoTriggerChecks []*AutoTriggerCheck `json:"auto_trigger_checks,omitempty"` // A slice of auto trigger checks that can be set for a check suite in a repository.
}
// SetCheckSuitePreferences changes the default automatic flow when creating check suites.
//
// GitHub API docs: https://docs.github.com/rest/checks/suites#update-repository-preferences-for-check-suites
//
//meta:operation PATCH /repos/{owner}/{repo}/check-suites/preferences
func (s *ChecksService) SetCheckSuitePreferences(ctx context.Context, owner, repo string, opts CheckSuitePreferenceOptions) (*CheckSuitePreferenceResults, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-suites/preferences", owner, repo)
req, err := s.client.NewRequest("PATCH", u, opts)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
var checkSuitePrefResults *CheckSuitePreferenceResults
resp, err := s.client.Do(ctx, req, &checkSuitePrefResults)
if err != nil {
return nil, resp, err
}
return checkSuitePrefResults, resp, nil
}
// CreateCheckSuiteOptions sets up parameters to manually create a check suites
type CreateCheckSuiteOptions struct {
HeadSHA string `json:"head_sha"` // The sha of the head commit. (Required.)
HeadBranch *string `json:"head_branch,omitempty"` // The name of the head branch where the code changes are implemented.
}
// CreateCheckSuite manually creates a check suite for a repository.
//
// GitHub API docs: https://docs.github.com/rest/checks/suites#create-a-check-suite
//
//meta:operation POST /repos/{owner}/{repo}/check-suites
func (s *ChecksService) CreateCheckSuite(ctx context.Context, owner, repo string, opts CreateCheckSuiteOptions) (*CheckSuite, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-suites", owner, repo)
req, err := s.client.NewRequest("POST", u, opts)
if err != nil {
return nil, nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
checkSuite := new(CheckSuite)
resp, err := s.client.Do(ctx, req, checkSuite)
if err != nil {
return nil, resp, err
}
return checkSuite, resp, nil
}
// ReRequestCheckSuite triggers GitHub to rerequest an existing check suite, without pushing new code to a repository.
//
// GitHub API docs: https://docs.github.com/rest/checks/suites#rerequest-a-check-suite
//
//meta:operation POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest
func (s *ChecksService) ReRequestCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64) (*Response, error) {
u := fmt.Sprintf("repos/%v/%v/check-suites/%v/rerequest", owner, repo, checkSuiteID)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", mediaTypeCheckRunsPreview)
resp, err := s.client.Do(ctx, req, nil)
return resp, err
}

View file

@ -1,652 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"strconv"
"strings"
)
// CodeScanningService handles communication with the code scanning related
// methods of the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type CodeScanningService service
// Rule represents the complete details of GitHub Code Scanning alert type.
type Rule struct {
ID *string `json:"id,omitempty"`
Severity *string `json:"severity,omitempty"`
Description *string `json:"description,omitempty"`
Name *string `json:"name,omitempty"`
SecuritySeverityLevel *string `json:"security_severity_level,omitempty"`
FullDescription *string `json:"full_description,omitempty"`
Tags []string `json:"tags,omitempty"`
Help *string `json:"help,omitempty"`
}
// Location represents the exact location of the GitHub Code Scanning Alert in the scanned project.
type Location struct {
Path *string `json:"path,omitempty"`
StartLine *int `json:"start_line,omitempty"`
EndLine *int `json:"end_line,omitempty"`
StartColumn *int `json:"start_column,omitempty"`
EndColumn *int `json:"end_column,omitempty"`
}
// Message is a part of MostRecentInstance struct which provides the appropriate message when any action is performed on the analysis object.
type Message struct {
Text *string `json:"text,omitempty"`
}
// MostRecentInstance provides details of the most recent instance of this alert for the default branch or for the specified Git reference.
type MostRecentInstance struct {
Ref *string `json:"ref,omitempty"`
AnalysisKey *string `json:"analysis_key,omitempty"`
Category *string `json:"category,omitempty"`
Environment *string `json:"environment,omitempty"`
State *string `json:"state,omitempty"`
CommitSHA *string `json:"commit_sha,omitempty"`
Message *Message `json:"message,omitempty"`
Location *Location `json:"location,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
Classifications []string `json:"classifications,omitempty"`
}
// Tool represents the tool used to generate a GitHub Code Scanning Alert.
type Tool struct {
Name *string `json:"name,omitempty"`
GUID *string `json:"guid,omitempty"`
Version *string `json:"version,omitempty"`
}
// Alert represents an individual GitHub Code Scanning Alert on a single repository.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type Alert struct {
Number *int `json:"number,omitempty"`
Repository *Repository `json:"repository,omitempty"`
RuleID *string `json:"rule_id,omitempty"`
RuleSeverity *string `json:"rule_severity,omitempty"`
RuleDescription *string `json:"rule_description,omitempty"`
Rule *Rule `json:"rule,omitempty"`
Tool *Tool `json:"tool,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
FixedAt *Timestamp `json:"fixed_at,omitempty"`
State *string `json:"state,omitempty"`
ClosedBy *User `json:"closed_by,omitempty"`
ClosedAt *Timestamp `json:"closed_at,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
MostRecentInstance *MostRecentInstance `json:"most_recent_instance,omitempty"`
Instances []*MostRecentInstance `json:"instances,omitempty"`
DismissedBy *User `json:"dismissed_by,omitempty"`
DismissedAt *Timestamp `json:"dismissed_at,omitempty"`
DismissedReason *string `json:"dismissed_reason,omitempty"`
DismissedComment *string `json:"dismissed_comment,omitempty"`
InstancesURL *string `json:"instances_url,omitempty"`
}
// ID returns the ID associated with an alert. It is the number at the end of the security alert's URL.
func (a *Alert) ID() int64 {
if a == nil {
return 0
}
s := a.GetHTMLURL()
// Check for an ID to parse at the end of the url
if i := strings.LastIndex(s, "/"); i >= 0 {
s = s[i+1:]
}
// Return the alert ID as a 64-bit integer. Unable to convert or out of range returns 0.
id, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0
}
return id
}
// AlertInstancesListOptions specifies optional parameters to the CodeScanningService.ListAlertInstances method.
type AlertInstancesListOptions struct {
// Return code scanning alert instances for a specific branch reference.
// The ref can be formatted as refs/heads/<branch name> or simply <branch name>. To reference a pull request use refs/pull/<number>/merge
Ref string `url:"ref,omitempty"`
ListOptions
}
// AlertListOptions specifies optional parameters to the CodeScanningService.ListAlerts method.
type AlertListOptions struct {
// State of the code scanning alerts to list. Set to closed to list only closed code scanning alerts. Default: open
State string `url:"state,omitempty"`
// Return code scanning alerts for a specific branch reference.
// The ref can be formatted as refs/heads/<branch name> or simply <branch name>. To reference a pull request use refs/pull/<number>/merge
Ref string `url:"ref,omitempty"`
// If specified, only code scanning alerts with this severity will be returned. Possible values are: critical, high, medium, low, warning, note, error.
Severity string `url:"severity,omitempty"`
// The name of a code scanning tool. Only results by this tool will be listed.
ToolName string `url:"tool_name,omitempty"`
ListCursorOptions
// Add ListOptions so offset pagination with integer type "page" query parameter is accepted
// since ListCursorOptions accepts "page" as string only.
ListOptions
}
// AnalysesListOptions specifies optional parameters to the CodeScanningService.ListAnalysesForRepo method.
type AnalysesListOptions struct {
// Return code scanning analyses belonging to the same SARIF upload.
SarifID *string `url:"sarif_id,omitempty"`
// Return code scanning analyses for a specific branch reference.
// The ref can be formatted as refs/heads/<branch name> or simply <branch name>. To reference a pull request use refs/pull/<number>/merge
Ref *string `url:"ref,omitempty"`
ListOptions
}
// CodeQLDatabase represents a metadata about the CodeQL database.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type CodeQLDatabase struct {
ID *int64 `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Language *string `json:"language,omitempty"`
Uploader *User `json:"uploader,omitempty"`
ContentType *string `json:"content_type,omitempty"`
Size *int64 `json:"size,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
URL *string `json:"url,omitempty"`
}
// ScanningAnalysis represents an individual GitHub Code Scanning ScanningAnalysis on a single repository.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type ScanningAnalysis struct {
ID *int64 `json:"id,omitempty"`
Ref *string `json:"ref,omitempty"`
CommitSHA *string `json:"commit_sha,omitempty"`
AnalysisKey *string `json:"analysis_key,omitempty"`
Environment *string `json:"environment,omitempty"`
Error *string `json:"error,omitempty"`
Category *string `json:"category,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
ResultsCount *int `json:"results_count,omitempty"`
RulesCount *int `json:"rules_count,omitempty"`
URL *string `json:"url,omitempty"`
SarifID *string `json:"sarif_id,omitempty"`
Tool *Tool `json:"tool,omitempty"`
Deletable *bool `json:"deletable,omitempty"`
Warning *string `json:"warning,omitempty"`
}
// SarifAnalysis specifies the results of a code scanning job.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type SarifAnalysis struct {
CommitSHA *string `json:"commit_sha,omitempty"`
Ref *string `json:"ref,omitempty"`
Sarif *string `json:"sarif,omitempty"`
CheckoutURI *string `json:"checkout_uri,omitempty"`
StartedAt *Timestamp `json:"started_at,omitempty"`
ToolName *string `json:"tool_name,omitempty"`
}
// CodeScanningAlertState specifies the state of a code scanning alert.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type CodeScanningAlertState struct {
// State sets the state of the code scanning alert and is a required field.
// You must also provide DismissedReason when you set the state to "dismissed".
// State can be one of: "open", "dismissed".
State string `json:"state"`
// DismissedReason represents the reason for dismissing or closing the alert.
// It is required when the state is "dismissed".
// It can be one of: "false positive", "won't fix", "used in tests".
DismissedReason *string `json:"dismissed_reason,omitempty"`
// DismissedComment is associated with the dismissal of the alert.
DismissedComment *string `json:"dismissed_comment,omitempty"`
}
// SarifID identifies a sarif analysis upload.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning
type SarifID struct {
ID *string `json:"id,omitempty"`
URL *string `json:"url,omitempty"`
}
// ListAlertsForOrg lists code scanning alerts for an org.
//
// You must use an access token with the security_events scope to use this endpoint. GitHub Apps must have the security_events
// read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-an-organization
//
//meta:operation GET /orgs/{org}/code-scanning/alerts
func (s *CodeScanningService) ListAlertsForOrg(ctx context.Context, org string, opts *AlertListOptions) ([]*Alert, *Response, error) {
u := fmt.Sprintf("orgs/%v/code-scanning/alerts", org)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var alerts []*Alert
resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, err
}
return alerts, resp, nil
}
// ListAlertsForRepo lists code scanning alerts for a repository.
//
// Lists all open code scanning alerts for the default branch (usually master) and protected branches in a repository.
// You must use an access token with the security_events scope to use this endpoint. GitHub Apps must have the security_events
// read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/alerts
func (s *CodeScanningService) ListAlertsForRepo(ctx context.Context, owner, repo string, opts *AlertListOptions) ([]*Alert, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/alerts", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var alerts []*Alert
resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, err
}
return alerts, resp, nil
}
// GetAlert gets a single code scanning alert for a repository.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// The security alert_id is the number at the end of the security alert's URL.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#get-a-code-scanning-alert
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}
func (s *CodeScanningService) GetAlert(ctx context.Context, owner, repo string, id int64) (*Alert, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/alerts/%v", owner, repo, id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
a := new(Alert)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// UpdateAlert updates the state of a single code scanning alert for a repository.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// The security alert_id is the number at the end of the security alert's URL.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#update-a-code-scanning-alert
//
//meta:operation PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}
func (s *CodeScanningService) UpdateAlert(ctx context.Context, owner, repo string, id int64, stateInfo *CodeScanningAlertState) (*Alert, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/alerts/%v", owner, repo, id)
req, err := s.client.NewRequest("PATCH", u, stateInfo)
if err != nil {
return nil, nil, err
}
a := new(Alert)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}
// ListAlertInstances lists instances of a code scanning alert.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#list-instances-of-a-code-scanning-alert
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances
func (s *CodeScanningService) ListAlertInstances(ctx context.Context, owner, repo string, id int64, opts *AlertInstancesListOptions) ([]*MostRecentInstance, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/alerts/%v/instances", owner, repo, id)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var alertInstances []*MostRecentInstance
resp, err := s.client.Do(ctx, req, &alertInstances)
if err != nil {
return nil, resp, err
}
return alertInstances, resp, nil
}
// UploadSarif uploads the result of code scanning job to GitHub.
//
// For the parameter sarif, you must first compress your SARIF file using gzip and then translate the contents of the file into a Base64 encoding string.
// You must use an access token with the security_events scope to use this endpoint. GitHub Apps must have the security_events
// write permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#upload-an-analysis-as-sarif-data
//
//meta:operation POST /repos/{owner}/{repo}/code-scanning/sarifs
func (s *CodeScanningService) UploadSarif(ctx context.Context, owner, repo string, sarif *SarifAnalysis) (*SarifID, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/sarifs", owner, repo)
req, err := s.client.NewRequest("POST", u, sarif)
if err != nil {
return nil, nil, err
}
sarifID := new(SarifID)
resp, err := s.client.Do(ctx, req, sarifID)
if err != nil {
return nil, resp, err
}
return sarifID, resp, nil
}
// SARIFUpload represents information about a SARIF upload.
type SARIFUpload struct {
// `pending` files have not yet been processed, while `complete` means results from the SARIF have been stored.
// `failed` files have either not been processed at all, or could only be partially processed.
ProcessingStatus *string `json:"processing_status,omitempty"`
// The REST API URL for getting the analyses associated with the upload.
AnalysesURL *string `json:"analyses_url,omitempty"`
}
// GetSARIF gets information about a SARIF upload.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#get-information-about-a-sarif-upload
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}
func (s *CodeScanningService) GetSARIF(ctx context.Context, owner, repo, sarifID string) (*SARIFUpload, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/sarifs/%v", owner, repo, sarifID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
sarifUpload := new(SARIFUpload)
resp, err := s.client.Do(ctx, req, sarifUpload)
if err != nil {
return nil, resp, err
}
return sarifUpload, resp, nil
}
// ListAnalysesForRepo lists code scanning analyses for a repository.
//
// Lists the details of all code scanning analyses for a repository, starting with the most recent.
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#list-code-scanning-analyses-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/analyses
func (s *CodeScanningService) ListAnalysesForRepo(ctx context.Context, owner, repo string, opts *AnalysesListOptions) ([]*ScanningAnalysis, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/analyses", owner, repo)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var analyses []*ScanningAnalysis
resp, err := s.client.Do(ctx, req, &analyses)
if err != nil {
return nil, resp, err
}
return analyses, resp, nil
}
// GetAnalysis gets a single code scanning analysis for a repository.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// The security analysis_id is the ID of the analysis, as returned from the ListAnalysesForRepo operation.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#get-a-code-scanning-analysis-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}
func (s *CodeScanningService) GetAnalysis(ctx context.Context, owner, repo string, id int64) (*ScanningAnalysis, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/analyses/%v", owner, repo, id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
analysis := new(ScanningAnalysis)
resp, err := s.client.Do(ctx, req, analysis)
if err != nil {
return nil, resp, err
}
return analysis, resp, nil
}
// DeleteAnalysis represents a successful deletion of a code scanning analysis.
type DeleteAnalysis struct {
// Next deletable analysis in chain, without last analysis deletion confirmation
NextAnalysisURL *string `json:"next_analysis_url,omitempty"`
// Next deletable analysis in chain, with last analysis deletion confirmation
ConfirmDeleteURL *string `json:"confirm_delete_url,omitempty"`
}
// DeleteAnalysis deletes a single code scanning analysis from a repository.
//
// You must use an access token with the repo scope to use this endpoint.
// GitHub Apps must have the security_events read permission to use this endpoint.
//
// The security analysis_id is the ID of the analysis, as returned from the ListAnalysesForRepo operation.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#delete-a-code-scanning-analysis-from-a-repository
//
//meta:operation DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}
func (s *CodeScanningService) DeleteAnalysis(ctx context.Context, owner, repo string, id int64) (*DeleteAnalysis, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/analyses/%v", owner, repo, id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, nil, err
}
deleteAnalysis := new(DeleteAnalysis)
resp, err := s.client.Do(ctx, req, deleteAnalysis)
if err != nil {
return nil, resp, err
}
return deleteAnalysis, resp, nil
}
// ListCodeQLDatabases lists the CodeQL databases that are available in a repository.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the contents read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#list-codeql-databases-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/codeql/databases
func (s *CodeScanningService) ListCodeQLDatabases(ctx context.Context, owner, repo string) ([]*CodeQLDatabase, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/codeql/databases", owner, repo)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var codeqlDatabases []*CodeQLDatabase
resp, err := s.client.Do(ctx, req, &codeqlDatabases)
if err != nil {
return nil, resp, err
}
return codeqlDatabases, resp, nil
}
// GetCodeQLDatabase gets a CodeQL database for a language in a repository.
//
// You must use an access token with the security_events scope to use this endpoint.
// GitHub Apps must have the contents read permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#get-a-codeql-database-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}
func (s *CodeScanningService) GetCodeQLDatabase(ctx context.Context, owner, repo, language string) (*CodeQLDatabase, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/code-scanning/codeql/databases/%v", owner, repo, language)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
codeqlDatabase := new(CodeQLDatabase)
resp, err := s.client.Do(ctx, req, codeqlDatabase)
if err != nil {
return nil, resp, err
}
return codeqlDatabase, resp, nil
}
// DefaultSetupConfiguration represents a code scanning default setup configuration.
type DefaultSetupConfiguration struct {
State *string `json:"state,omitempty"`
Languages []string `json:"languages,omitempty"`
QuerySuite *string `json:"query_suite,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
}
// GetDefaultSetupConfiguration gets a code scanning default setup configuration.
//
// You must use an access token with the repo scope to use this
// endpoint with private repos or the public_repo scope for public repos. GitHub Apps must have the repo write
// permission to use this endpoint.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#get-a-code-scanning-default-setup-configuration
//
//meta:operation GET /repos/{owner}/{repo}/code-scanning/default-setup
func (s *CodeScanningService) GetDefaultSetupConfiguration(ctx context.Context, owner, repo string) (*DefaultSetupConfiguration, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/code-scanning/default-setup", owner, repo)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
cfg := new(DefaultSetupConfiguration)
resp, err := s.client.Do(ctx, req, cfg)
if err != nil {
return nil, resp, err
}
return cfg, resp, nil
}
// UpdateDefaultSetupConfigurationOptions specifies parameters to the CodeScanningService.UpdateDefaultSetupConfiguration
// method.
type UpdateDefaultSetupConfigurationOptions struct {
State string `json:"state"`
QuerySuite *string `json:"query_suite,omitempty"`
Languages []string `json:"languages,omitempty"`
}
// UpdateDefaultSetupConfigurationResponse represents a response from updating a code scanning default setup configuration.
type UpdateDefaultSetupConfigurationResponse struct {
RunID *int64 `json:"run_id,omitempty"`
RunURL *string `json:"run_url,omitempty"`
}
// UpdateDefaultSetupConfiguration updates a code scanning default setup configuration.
//
// You must use an access token with the repo scope to use this
// endpoint with private repos or the public_repo scope for public repos. GitHub Apps must have the repo write
// permission to use this endpoint.
//
// This method might return an AcceptedError and a status code of 202. This is because this is the status that GitHub
// returns to signify that it has now scheduled the update of the pull request branch in a background task.
//
// GitHub API docs: https://docs.github.com/rest/code-scanning/code-scanning#update-a-code-scanning-default-setup-configuration
//
//meta:operation PATCH /repos/{owner}/{repo}/code-scanning/default-setup
func (s *CodeScanningService) UpdateDefaultSetupConfiguration(ctx context.Context, owner, repo string, options *UpdateDefaultSetupConfigurationOptions) (*UpdateDefaultSetupConfigurationResponse, *Response, error) {
u := fmt.Sprintf("repos/%s/%s/code-scanning/default-setup", owner, repo)
req, err := s.client.NewRequest("PATCH", u, options)
if err != nil {
return nil, nil, err
}
a := new(UpdateDefaultSetupConfigurationResponse)
resp, err := s.client.Do(ctx, req, a)
if err != nil {
return nil, resp, err
}
return a, resp, nil
}

View file

@ -1,87 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// CodesOfConductService provides access to code-of-conduct-related functions in the GitHub API.
type CodesOfConductService service
// CodeOfConduct represents a code of conduct.
type CodeOfConduct struct {
Name *string `json:"name,omitempty"`
Key *string `json:"key,omitempty"`
URL *string `json:"url,omitempty"`
Body *string `json:"body,omitempty"`
}
func (c *CodeOfConduct) String() string {
return Stringify(c)
}
// List returns all codes of conduct.
//
// GitHub API docs: https://docs.github.com/rest/codes-of-conduct/codes-of-conduct#get-all-codes-of-conduct
//
//meta:operation GET /codes_of_conduct
func (s *CodesOfConductService) List(ctx context.Context) ([]*CodeOfConduct, *Response, error) {
req, err := s.client.NewRequest("GET", "codes_of_conduct", nil)
if err != nil {
return nil, nil, err
}
// TODO: remove custom Accept header when this API fully launches.
req.Header.Set("Accept", mediaTypeCodesOfConductPreview)
var cs []*CodeOfConduct
resp, err := s.client.Do(ctx, req, &cs)
if err != nil {
return nil, resp, err
}
return cs, resp, nil
}
// ListCodesOfConduct returns all codes of conduct.
//
// Deprecated: Use CodesOfConductService.List instead
func (c *Client) ListCodesOfConduct(ctx context.Context) ([]*CodeOfConduct, *Response, error) {
return c.CodesOfConduct.List(ctx)
}
// Get returns an individual code of conduct.
//
// GitHub API docs: https://docs.github.com/rest/codes-of-conduct/codes-of-conduct#get-a-code-of-conduct
//
//meta:operation GET /codes_of_conduct/{key}
func (s *CodesOfConductService) Get(ctx context.Context, key string) (*CodeOfConduct, *Response, error) {
u := fmt.Sprintf("codes_of_conduct/%s", key)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
// TODO: remove custom Accept header when this API fully launches.
req.Header.Set("Accept", mediaTypeCodesOfConductPreview)
coc := new(CodeOfConduct)
resp, err := s.client.Do(ctx, req, coc)
if err != nil {
return nil, resp, err
}
return coc, resp, nil
}
// GetCodeOfConduct returns an individual code of conduct.
//
// Deprecated: Use CodesOfConductService.Get instead
func (c *Client) GetCodeOfConduct(ctx context.Context, key string) (*CodeOfConduct, *Response, error) {
return c.CodesOfConduct.Get(ctx, key)
}

View file

@ -1,176 +0,0 @@
// Copyright 2022 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// Dependency reprensents the vulnerable dependency.
type Dependency struct {
Package *VulnerabilityPackage `json:"package,omitempty"`
ManifestPath *string `json:"manifest_path,omitempty"`
Scope *string `json:"scope,omitempty"`
}
// AdvisoryCVSS represents the advisory pertaining to the Common Vulnerability Scoring System.
type AdvisoryCVSS struct {
Score *float64 `json:"score,omitempty"`
VectorString *string `json:"vector_string,omitempty"`
}
// AdvisoryCWEs reprensent the advisory pertaining to Common Weakness Enumeration.
type AdvisoryCWEs struct {
CWEID *string `json:"cwe_id,omitempty"`
Name *string `json:"name,omitempty"`
}
// DependabotSecurityAdvisory represents the GitHub Security Advisory.
type DependabotSecurityAdvisory struct {
GHSAID *string `json:"ghsa_id,omitempty"`
CVEID *string `json:"cve_id,omitempty"`
Summary *string `json:"summary,omitempty"`
Description *string `json:"description,omitempty"`
Vulnerabilities []*AdvisoryVulnerability `json:"vulnerabilities,omitempty"`
Severity *string `json:"severity,omitempty"`
CVSS *AdvisoryCVSS `json:"cvss,omitempty"`
CWEs []*AdvisoryCWEs `json:"cwes,omitempty"`
Identifiers []*AdvisoryIdentifier `json:"identifiers,omitempty"`
References []*AdvisoryReference `json:"references,omitempty"`
PublishedAt *Timestamp `json:"published_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
WithdrawnAt *Timestamp `json:"withdrawn_at,omitempty"`
}
// DependabotAlert represents a Dependabot alert.
type DependabotAlert struct {
Number *int `json:"number,omitempty"`
State *string `json:"state,omitempty"`
Dependency *Dependency `json:"dependency,omitempty"`
SecurityAdvisory *DependabotSecurityAdvisory `json:"security_advisory,omitempty"`
SecurityVulnerability *AdvisoryVulnerability `json:"security_vulnerability,omitempty"`
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
DismissedAt *Timestamp `json:"dismissed_at,omitempty"`
DismissedBy *User `json:"dismissed_by,omitempty"`
DismissedReason *string `json:"dismissed_reason,omitempty"`
DismissedComment *string `json:"dismissed_comment,omitempty"`
FixedAt *Timestamp `json:"fixed_at,omitempty"`
AutoDismissedAt *Timestamp `json:"auto_dismissed_at,omitempty"`
// The repository is always empty for events
Repository *Repository `json:"repository,omitempty"`
}
// DependabotAlertState represents the state of a Dependabot alert to update.
type DependabotAlertState struct {
// The state of the Dependabot alert. A dismissed_reason must be provided when setting the state to dismissed.
State string `json:"state"`
// Required when state is dismissed. A reason for dismissing the alert.
// Can be one of: fix_started, inaccurate, no_bandwidth, not_used, tolerable_risk
DismissedReason *string `json:"dismissed_reason,omitempty"`
// An optional comment associated with dismissing the alert.
DismissedComment *string `json:"dismissed_comment,omitempty"`
}
// ListAlertsOptions specifies the optional parameters to the DependabotService.ListRepoAlerts
// and DependabotService.ListOrgAlerts methods.
type ListAlertsOptions struct {
State *string `url:"state,omitempty"`
Severity *string `url:"severity,omitempty"`
Ecosystem *string `url:"ecosystem,omitempty"`
Package *string `url:"package,omitempty"`
Scope *string `url:"scope,omitempty"`
Sort *string `url:"sort,omitempty"`
Direction *string `url:"direction,omitempty"`
ListOptions
ListCursorOptions
}
func (s *DependabotService) listAlerts(ctx context.Context, url string, opts *ListAlertsOptions) ([]*DependabotAlert, *Response, error) {
u, err := addOptions(url, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var alerts []*DependabotAlert
resp, err := s.client.Do(ctx, req, &alerts)
if err != nil {
return nil, resp, err
}
return alerts, resp, nil
}
// ListRepoAlerts lists all Dependabot alerts of a repository.
//
// GitHub API docs: https://docs.github.com/rest/dependabot/alerts#list-dependabot-alerts-for-a-repository
//
//meta:operation GET /repos/{owner}/{repo}/dependabot/alerts
func (s *DependabotService) ListRepoAlerts(ctx context.Context, owner, repo string, opts *ListAlertsOptions) ([]*DependabotAlert, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/dependabot/alerts", owner, repo)
return s.listAlerts(ctx, url, opts)
}
// ListOrgAlerts lists all Dependabot alerts of an organization.
//
// GitHub API docs: https://docs.github.com/rest/dependabot/alerts#list-dependabot-alerts-for-an-organization
//
//meta:operation GET /orgs/{org}/dependabot/alerts
func (s *DependabotService) ListOrgAlerts(ctx context.Context, org string, opts *ListAlertsOptions) ([]*DependabotAlert, *Response, error) {
url := fmt.Sprintf("orgs/%v/dependabot/alerts", org)
return s.listAlerts(ctx, url, opts)
}
// GetRepoAlert gets a single repository Dependabot alert.
//
// GitHub API docs: https://docs.github.com/rest/dependabot/alerts#get-a-dependabot-alert
//
//meta:operation GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}
func (s *DependabotService) GetRepoAlert(ctx context.Context, owner, repo string, number int) (*DependabotAlert, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/dependabot/alerts/%v", owner, repo, number)
req, err := s.client.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
alert := new(DependabotAlert)
resp, err := s.client.Do(ctx, req, alert)
if err != nil {
return nil, resp, err
}
return alert, resp, nil
}
// UpdateAlert updates a Dependabot alert.
//
// GitHub API docs: https://docs.github.com/rest/dependabot/alerts#update-a-dependabot-alert
//
//meta:operation PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}
func (s *DependabotService) UpdateAlert(ctx context.Context, owner, repo string, number int, stateInfo *DependabotAlertState) (*DependabotAlert, *Response, error) {
url := fmt.Sprintf("repos/%v/%v/dependabot/alerts/%v", owner, repo, number)
req, err := s.client.NewRequest("PATCH", url, stateInfo)
if err != nil {
return nil, nil, err
}
alert := new(DependabotAlert)
resp, err := s.client.Do(ctx, req, alert)
if err != nil {
return nil, resp, err
}
return alert, resp, nil
}

View file

@ -1,194 +0,0 @@
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package github provides a client for using the GitHub API.
Usage:
import "github.com/google/go-github/v57/github" // with go modules enabled (GO111MODULE=on or outside GOPATH)
import "github.com/google/go-github/github" // with go modules disabled
Construct a new GitHub client, then use the various services on the client to
access different parts of the GitHub API. For example:
client := github.NewClient(nil)
// list all organizations for user "willnorris"
orgs, _, err := client.Organizations.List(ctx, "willnorris", nil)
Some API methods have optional parameters that can be passed. For example:
client := github.NewClient(nil)
// list public repositories for org "github"
opt := &github.RepositoryListByOrgOptions{Type: "public"}
repos, _, err := client.Repositories.ListByOrg(ctx, "github", opt)
The services of a client divide the API into logical chunks and correspond to
the structure of the GitHub API documentation at
https://docs.github.com/rest .
NOTE: Using the https://godoc.org/context package, one can easily
pass cancelation signals and deadlines to various services of the client for
handling a request. In case there is no context available, then context.Background()
can be used as a starting point.
For more sample code snippets, head over to the https://github.com/google/go-github/tree/master/example directory.
# Authentication
Use Client.WithAuthToken to configure your client to authenticate using an Oauth token
(for example, a personal access token). This is what is needed for a majority of use cases
aside from GitHub Apps.
client := github.NewClient(nil).WithAuthToken("... your access token ...")
Note that when using an authenticated Client, all calls made by the client will
include the specified OAuth token. Therefore, authenticated clients should
almost never be shared between different users.
For API methods that require HTTP Basic Authentication, use the
BasicAuthTransport.
GitHub Apps authentication can be provided by the
https://github.com/bradleyfalzon/ghinstallation package.
It supports both authentication as an installation, using an installation access token,
and as an app, using a JWT.
To authenticate as an installation:
import "github.com/bradleyfalzon/ghinstallation"
func main() {
// Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99.
itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem")
if err != nil {
// Handle error.
}
// Use installation transport with client
client := github.NewClient(&http.Client{Transport: itr})
// Use client...
}
To authenticate as an app, using a JWT:
import "github.com/bradleyfalzon/ghinstallation"
func main() {
// Wrap the shared transport for use with the application ID 1.
atr, err := ghinstallation.NewAppsTransportKeyFromFile(http.DefaultTransport, 1, "2016-10-19.private-key.pem")
if err != nil {
// Handle error.
}
// Use app transport with client
client := github.NewClient(&http.Client{Transport: atr})
// Use client...
}
# Rate Limiting
GitHub imposes a rate limit on all API clients. Unauthenticated clients are
limited to 60 requests per hour, while authenticated clients can make up to
5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated
clients are limited to 10 requests per minute, while authenticated clients
can make up to 30 requests per minute. To receive the higher rate limit when
making calls that are not issued on behalf of a user,
use UnauthenticatedRateLimitedTransport.
The returned Response.Rate value contains the rate limit information
from the most recent API call. If a recent enough response isn't
available, you can use RateLimits to fetch the most up-to-date rate
limit data for the client.
To detect an API rate limit error, you can check if its type is *github.RateLimitError.
For secondary rate limits, you can check if its type is *github.AbuseRateLimitError:
repos, _, err := client.Repositories.List(ctx, "", nil)
if _, ok := err.(*github.RateLimitError); ok {
log.Println("hit rate limit")
}
if _, ok := err.(*github.AbuseRateLimitError); ok {
log.Println("hit secondary rate limit")
}
Learn more about GitHub rate limiting at
https://docs.github.com/rest/rate-limit .
# Accepted Status
Some endpoints may return a 202 Accepted status code, meaning that the
information required is not yet ready and was scheduled to be gathered on
the GitHub side. Methods known to behave like this are documented specifying
this behavior.
To detect this condition of error, you can check if its type is
*github.AcceptedError:
stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo)
if _, ok := err.(*github.AcceptedError); ok {
log.Println("scheduled on GitHub side")
}
# Conditional Requests
The GitHub API has good support for conditional requests which will help
prevent you from burning through your rate limit, as well as help speed up your
application. go-github does not handle conditional requests directly, but is
instead designed to work with a caching http.Transport. We recommend using
https://github.com/gregjones/httpcache for that.
Learn more about GitHub conditional requests at
https://docs.github.com/rest/overview/resources-in-the-rest-api#conditional-requests.
# Creating and Updating Resources
All structs for GitHub resources use pointer values for all non-repeated fields.
This allows distinguishing between unset fields and those set to a zero-value.
Helper functions have been provided to easily create these pointers for string,
bool, and int values. For example:
// create a new private repository named "foo"
repo := &github.Repository{
Name: github.String("foo"),
Private: github.Bool(true),
}
client.Repositories.Create(ctx, "", repo)
Users who have worked with protocol buffers should find this pattern familiar.
# Pagination
All requests for resource collections (repos, pull requests, issues, etc.)
support pagination. Pagination options are described in the
github.ListOptions struct and passed to the list methods directly or as an
embedded type of a more specific list options struct (for example
github.PullRequestListOptions). Pages information is available via the
github.Response struct.
client := github.NewClient(nil)
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 10},
}
// get all pages of results
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt)
if err != nil {
return err
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
*/
package github

View file

@ -1,40 +0,0 @@
// Copyright 2023 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
)
// EmojisService provides access to emoji-related functions in the GitHub API.
type EmojisService service
// List returns the emojis available to use on GitHub.
//
// GitHub API docs: https://docs.github.com/rest/emojis/emojis#get-emojis
//
//meta:operation GET /emojis
func (s *EmojisService) List(ctx context.Context) (map[string]string, *Response, error) {
req, err := s.client.NewRequest("GET", "emojis", nil)
if err != nil {
return nil, nil, err
}
var emoji map[string]string
resp, err := s.client.Do(ctx, req, &emoji)
if err != nil {
return nil, resp, err
}
return emoji, resp, nil
}
// ListEmojis returns the emojis available to use on GitHub.
//
// Deprecated: Use EmojisService.List instead
func (c *Client) ListEmojis(ctx context.Context) (map[string]string, *Response, error) {
return c.Emojis.List(ctx)
}

View file

@ -1,118 +0,0 @@
// Copyright 2020 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// ListRunnerApplicationDownloads lists self-hosted runner application binaries that can be downloaded and run.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runners#list-runner-applications-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/runners/downloads
func (s *EnterpriseService) ListRunnerApplicationDownloads(ctx context.Context, enterprise string) ([]*RunnerApplicationDownload, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/runners/downloads", enterprise)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var rads []*RunnerApplicationDownload
resp, err := s.client.Do(ctx, req, &rads)
if err != nil {
return nil, resp, err
}
return rads, resp, nil
}
// GenerateEnterpriseJITConfig generates a just-in-time configuration for an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-an-enterprise
//
//meta:operation POST /enterprises/{enterprise}/actions/runners/generate-jitconfig
func (s *EnterpriseService) GenerateEnterpriseJITConfig(ctx context.Context, enterprise string, request *GenerateJITConfigRequest) (*JITRunnerConfig, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/runners/generate-jitconfig", enterprise)
req, err := s.client.NewRequest("POST", u, request)
if err != nil {
return nil, nil, err
}
jitConfig := new(JITRunnerConfig)
resp, err := s.client.Do(ctx, req, jitConfig)
if err != nil {
return nil, resp, err
}
return jitConfig, resp, nil
}
// CreateRegistrationToken creates a token that can be used to add a self-hosted runner.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runners#create-a-registration-token-for-an-enterprise
//
//meta:operation POST /enterprises/{enterprise}/actions/runners/registration-token
func (s *EnterpriseService) CreateRegistrationToken(ctx context.Context, enterprise string) (*RegistrationToken, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/runners/registration-token", enterprise)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
registrationToken := new(RegistrationToken)
resp, err := s.client.Do(ctx, req, registrationToken)
if err != nil {
return nil, resp, err
}
return registrationToken, resp, nil
}
// ListRunners lists all the self-hosted runners for a enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runners#list-self-hosted-runners-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/actions/runners
func (s *EnterpriseService) ListRunners(ctx context.Context, enterprise string, opts *ListOptions) (*Runners, *Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/runners", enterprise)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
runners := &Runners{}
resp, err := s.client.Do(ctx, req, &runners)
if err != nil {
return nil, resp, err
}
return runners, resp, nil
}
// RemoveRunner forces the removal of a self-hosted runner from an enterprise using the runner id.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/actions/self-hosted-runners#delete-a-self-hosted-runner-from-an-enterprise
//
//meta:operation DELETE /enterprises/{enterprise}/actions/runners/{runner_id}
func (s *EnterpriseService) RemoveRunner(ctx context.Context, enterprise string, runnerID int64) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/actions/runners/%v", enterprise, runnerID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

View file

@ -1,84 +0,0 @@
// Copyright 2022 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
)
// EnterpriseSecurityAnalysisSettings represents security analysis settings for an enterprise.
type EnterpriseSecurityAnalysisSettings struct {
AdvancedSecurityEnabledForNewRepositories *bool `json:"advanced_security_enabled_for_new_repositories,omitempty"`
SecretScanningEnabledForNewRepositories *bool `json:"secret_scanning_enabled_for_new_repositories,omitempty"`
SecretScanningPushProtectionEnabledForNewRepositories *bool `json:"secret_scanning_push_protection_enabled_for_new_repositories,omitempty"`
SecretScanningPushProtectionCustomLink *string `json:"secret_scanning_push_protection_custom_link,omitempty"`
}
// GetCodeSecurityAndAnalysis gets code security and analysis features for an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/code-security-and-analysis#get-code-security-and-analysis-features-for-an-enterprise
//
//meta:operation GET /enterprises/{enterprise}/code_security_and_analysis
func (s *EnterpriseService) GetCodeSecurityAndAnalysis(ctx context.Context, enterprise string) (*EnterpriseSecurityAnalysisSettings, *Response, error) {
u := fmt.Sprintf("enterprises/%v/code_security_and_analysis", enterprise)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
settings := new(EnterpriseSecurityAnalysisSettings)
resp, err := s.client.Do(ctx, req, settings)
if err != nil {
return nil, resp, err
}
return settings, resp, nil
}
// UpdateCodeSecurityAndAnalysis updates code security and analysis features for new repositories in an enterprise.
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/code-security-and-analysis#update-code-security-and-analysis-features-for-an-enterprise
//
//meta:operation PATCH /enterprises/{enterprise}/code_security_and_analysis
func (s *EnterpriseService) UpdateCodeSecurityAndAnalysis(ctx context.Context, enterprise string, settings *EnterpriseSecurityAnalysisSettings) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/code_security_and_analysis", enterprise)
req, err := s.client.NewRequest("PATCH", u, settings)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}
// EnableDisableSecurityFeature enables or disables a security feature for all repositories in an enterprise.
//
// Valid values for securityProduct: "advanced_security", "secret_scanning", "secret_scanning_push_protection".
// Valid values for enablement: "enable_all", "disable_all".
//
// GitHub API docs: https://docs.github.com/enterprise-cloud@latest/rest/enterprise-admin/code-security-and-analysis#enable-or-disable-a-security-feature
//
//meta:operation POST /enterprises/{enterprise}/{security_product}/{enablement}
func (s *EnterpriseService) EnableDisableSecurityFeature(ctx context.Context, enterprise, securityProduct, enablement string) (*Response, error) {
u := fmt.Sprintf("enterprises/%v/%v/%v", enterprise, securityProduct, enablement)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, err
}
resp, err := s.client.Do(ctx, req, nil)
if err != nil {
return resp, err
}
return resp, nil
}

File diff suppressed because it is too large Load diff

View file

@ -1,397 +0,0 @@
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"time"
)
// GistsService handles communication with the Gist related
// methods of the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/gists
type GistsService service
// Gist represents a GitHub's gist.
type Gist struct {
ID *string `json:"id,omitempty"`
Description *string `json:"description,omitempty"`
Public *bool `json:"public,omitempty"`
Owner *User `json:"owner,omitempty"`
Files map[GistFilename]GistFile `json:"files,omitempty"`
Comments *int `json:"comments,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
GitPullURL *string `json:"git_pull_url,omitempty"`
GitPushURL *string `json:"git_push_url,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
NodeID *string `json:"node_id,omitempty"`
}
func (g Gist) String() string {
return Stringify(g)
}
// GistFilename represents filename on a gist.
type GistFilename string
// GistFile represents a file on a gist.
type GistFile struct {
Size *int `json:"size,omitempty"`
Filename *string `json:"filename,omitempty"`
Language *string `json:"language,omitempty"`
Type *string `json:"type,omitempty"`
RawURL *string `json:"raw_url,omitempty"`
Content *string `json:"content,omitempty"`
}
func (g GistFile) String() string {
return Stringify(g)
}
// GistCommit represents a commit on a gist.
type GistCommit struct {
URL *string `json:"url,omitempty"`
Version *string `json:"version,omitempty"`
User *User `json:"user,omitempty"`
ChangeStatus *CommitStats `json:"change_status,omitempty"`
CommittedAt *Timestamp `json:"committed_at,omitempty"`
NodeID *string `json:"node_id,omitempty"`
}
func (gc GistCommit) String() string {
return Stringify(gc)
}
// GistFork represents a fork of a gist.
type GistFork struct {
URL *string `json:"url,omitempty"`
User *User `json:"user,omitempty"`
ID *string `json:"id,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
NodeID *string `json:"node_id,omitempty"`
}
func (gf GistFork) String() string {
return Stringify(gf)
}
// GistListOptions specifies the optional parameters to the
// GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods.
type GistListOptions struct {
// Since filters Gists by time.
Since time.Time `url:"since,omitempty"`
ListOptions
}
// List gists for a user. Passing the empty string will list
// all public gists if called anonymously. However, if the call
// is authenticated, it will returns all gists for the authenticated
// user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-gists-for-a-user
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-gists-for-the-authenticated-user
//
//meta:operation GET /gists
//meta:operation GET /users/{username}/gists
func (s *GistsService) List(ctx context.Context, user string, opts *GistListOptions) ([]*Gist, *Response, error) {
var u string
if user != "" {
u = fmt.Sprintf("users/%v/gists", user)
} else {
u = "gists"
}
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var gists []*Gist
resp, err := s.client.Do(ctx, req, &gists)
if err != nil {
return nil, resp, err
}
return gists, resp, nil
}
// ListAll lists all public gists.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-public-gists
//
//meta:operation GET /gists/public
func (s *GistsService) ListAll(ctx context.Context, opts *GistListOptions) ([]*Gist, *Response, error) {
u, err := addOptions("gists/public", opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var gists []*Gist
resp, err := s.client.Do(ctx, req, &gists)
if err != nil {
return nil, resp, err
}
return gists, resp, nil
}
// ListStarred lists starred gists of authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-starred-gists
//
//meta:operation GET /gists/starred
func (s *GistsService) ListStarred(ctx context.Context, opts *GistListOptions) ([]*Gist, *Response, error) {
u, err := addOptions("gists/starred", opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var gists []*Gist
resp, err := s.client.Do(ctx, req, &gists)
if err != nil {
return nil, resp, err
}
return gists, resp, nil
}
// Get a single gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#get-a-gist
//
//meta:operation GET /gists/{gist_id}
func (s *GistsService) Get(ctx context.Context, id string) (*Gist, *Response, error) {
u := fmt.Sprintf("gists/%v", id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
gist := new(Gist)
resp, err := s.client.Do(ctx, req, gist)
if err != nil {
return nil, resp, err
}
return gist, resp, nil
}
// GetRevision gets a specific revision of a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#get-a-gist-revision
//
//meta:operation GET /gists/{gist_id}/{sha}
func (s *GistsService) GetRevision(ctx context.Context, id, sha string) (*Gist, *Response, error) {
u := fmt.Sprintf("gists/%v/%v", id, sha)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
gist := new(Gist)
resp, err := s.client.Do(ctx, req, gist)
if err != nil {
return nil, resp, err
}
return gist, resp, nil
}
// Create a gist for authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#create-a-gist
//
//meta:operation POST /gists
func (s *GistsService) Create(ctx context.Context, gist *Gist) (*Gist, *Response, error) {
u := "gists"
req, err := s.client.NewRequest("POST", u, gist)
if err != nil {
return nil, nil, err
}
g := new(Gist)
resp, err := s.client.Do(ctx, req, g)
if err != nil {
return nil, resp, err
}
return g, resp, nil
}
// Edit a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#update-a-gist
//
//meta:operation PATCH /gists/{gist_id}
func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, *Response, error) {
u := fmt.Sprintf("gists/%v", id)
req, err := s.client.NewRequest("PATCH", u, gist)
if err != nil {
return nil, nil, err
}
g := new(Gist)
resp, err := s.client.Do(ctx, req, g)
if err != nil {
return nil, resp, err
}
return g, resp, nil
}
// ListCommits lists commits of a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-gist-commits
//
//meta:operation GET /gists/{gist_id}/commits
func (s *GistsService) ListCommits(ctx context.Context, id string, opts *ListOptions) ([]*GistCommit, *Response, error) {
u := fmt.Sprintf("gists/%v/commits", id)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var gistCommits []*GistCommit
resp, err := s.client.Do(ctx, req, &gistCommits)
if err != nil {
return nil, resp, err
}
return gistCommits, resp, nil
}
// Delete a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#delete-a-gist
//
//meta:operation DELETE /gists/{gist_id}
func (s *GistsService) Delete(ctx context.Context, id string) (*Response, error) {
u := fmt.Sprintf("gists/%v", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// Star a gist on behalf of authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#star-a-gist
//
//meta:operation PUT /gists/{gist_id}/star
func (s *GistsService) Star(ctx context.Context, id string) (*Response, error) {
u := fmt.Sprintf("gists/%v/star", id)
req, err := s.client.NewRequest("PUT", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// Unstar a gist on a behalf of authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#unstar-a-gist
//
//meta:operation DELETE /gists/{gist_id}/star
func (s *GistsService) Unstar(ctx context.Context, id string) (*Response, error) {
u := fmt.Sprintf("gists/%v/star", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// IsStarred checks if a gist is starred by authenticated user.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#check-if-a-gist-is-starred
//
//meta:operation GET /gists/{gist_id}/star
func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Response, error) {
u := fmt.Sprintf("gists/%v/star", id)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return false, nil, err
}
resp, err := s.client.Do(ctx, req, nil)
starred, err := parseBoolResponse(err)
return starred, resp, err
}
// Fork a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#fork-a-gist
//
//meta:operation POST /gists/{gist_id}/forks
func (s *GistsService) Fork(ctx context.Context, id string) (*Gist, *Response, error) {
u := fmt.Sprintf("gists/%v/forks", id)
req, err := s.client.NewRequest("POST", u, nil)
if err != nil {
return nil, nil, err
}
g := new(Gist)
resp, err := s.client.Do(ctx, req, g)
if err != nil {
return nil, resp, err
}
return g, resp, nil
}
// ListForks lists forks of a gist.
//
// GitHub API docs: https://docs.github.com/rest/gists/gists#list-gist-forks
//
//meta:operation GET /gists/{gist_id}/forks
func (s *GistsService) ListForks(ctx context.Context, id string, opts *ListOptions) ([]*GistFork, *Response, error) {
u := fmt.Sprintf("gists/%v/forks", id)
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var gistForks []*GistFork
resp, err := s.client.Do(ctx, req, &gistForks)
if err != nil {
return nil, resp, err
}
return gistForks, resp, nil
}

View file

@ -1,225 +0,0 @@
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
)
// SignatureVerification represents GPG signature verification.
type SignatureVerification struct {
Verified *bool `json:"verified,omitempty"`
Reason *string `json:"reason,omitempty"`
Signature *string `json:"signature,omitempty"`
Payload *string `json:"payload,omitempty"`
}
// MessageSigner is used by GitService.CreateCommit to sign a commit.
//
// To create a MessageSigner that signs a commit with a [golang.org/x/crypto/openpgp.Entity],
// or [github.com/ProtonMail/go-crypto/openpgp.Entity], use:
//
// commit.Signer = github.MessageSignerFunc(func(w io.Writer, r io.Reader) error {
// return openpgp.ArmoredDetachSign(w, openpgpEntity, r, nil)
// })
type MessageSigner interface {
Sign(w io.Writer, r io.Reader) error
}
// MessageSignerFunc is a single function implementation of MessageSigner.
type MessageSignerFunc func(w io.Writer, r io.Reader) error
func (f MessageSignerFunc) Sign(w io.Writer, r io.Reader) error {
return f(w, r)
}
// Commit represents a GitHub commit.
type Commit struct {
SHA *string `json:"sha,omitempty"`
Author *CommitAuthor `json:"author,omitempty"`
Committer *CommitAuthor `json:"committer,omitempty"`
Message *string `json:"message,omitempty"`
Tree *Tree `json:"tree,omitempty"`
Parents []*Commit `json:"parents,omitempty"`
Stats *CommitStats `json:"stats,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
URL *string `json:"url,omitempty"`
Verification *SignatureVerification `json:"verification,omitempty"`
NodeID *string `json:"node_id,omitempty"`
// CommentCount is the number of GitHub comments on the commit. This
// is only populated for requests that fetch GitHub data like
// Pulls.ListCommits, Repositories.ListCommits, etc.
CommentCount *int `json:"comment_count,omitempty"`
}
func (c Commit) String() string {
return Stringify(c)
}
// CommitAuthor represents the author or committer of a commit. The commit
// author may not correspond to a GitHub User.
type CommitAuthor struct {
Date *Timestamp `json:"date,omitempty"`
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
// The following fields are only populated by Webhook events.
Login *string `json:"username,omitempty"` // Renamed for go-github consistency.
}
func (c CommitAuthor) String() string {
return Stringify(c)
}
// GetCommit fetches the Commit object for a given SHA.
//
// GitHub API docs: https://docs.github.com/rest/git/commits#get-a-commit-object
//
//meta:operation GET /repos/{owner}/{repo}/git/commits/{commit_sha}
func (s *GitService) GetCommit(ctx context.Context, owner string, repo string, sha string) (*Commit, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/git/commits/%v", owner, repo, sha)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
c := new(Commit)
resp, err := s.client.Do(ctx, req, c)
if err != nil {
return nil, resp, err
}
return c, resp, nil
}
// createCommit represents the body of a CreateCommit request.
type createCommit struct {
Author *CommitAuthor `json:"author,omitempty"`
Committer *CommitAuthor `json:"committer,omitempty"`
Message *string `json:"message,omitempty"`
Tree *string `json:"tree,omitempty"`
Parents []string `json:"parents,omitempty"`
Signature *string `json:"signature,omitempty"`
}
type CreateCommitOptions struct {
// CreateCommit will sign the commit with this signer. See MessageSigner doc for more details.
// Ignored on commits where Verification.Signature is defined.
Signer MessageSigner
}
// CreateCommit creates a new commit in a repository.
// commit must not be nil.
//
// The commit.Committer is optional and will be filled with the commit.Author
// data if omitted. If the commit.Author is omitted, it will be filled in with
// the authenticated users information and the current date.
//
// GitHub API docs: https://docs.github.com/rest/git/commits#create-a-commit
//
//meta:operation POST /repos/{owner}/{repo}/git/commits
func (s *GitService) CreateCommit(ctx context.Context, owner string, repo string, commit *Commit, opts *CreateCommitOptions) (*Commit, *Response, error) {
if commit == nil {
return nil, nil, fmt.Errorf("commit must be provided")
}
if opts == nil {
opts = &CreateCommitOptions{}
}
u := fmt.Sprintf("repos/%v/%v/git/commits", owner, repo)
parents := make([]string, len(commit.Parents))
for i, parent := range commit.Parents {
parents[i] = *parent.SHA
}
body := &createCommit{
Author: commit.Author,
Committer: commit.Committer,
Message: commit.Message,
Parents: parents,
}
if commit.Tree != nil {
body.Tree = commit.Tree.SHA
}
switch {
case commit.Verification != nil:
body.Signature = commit.Verification.Signature
case opts.Signer != nil:
signature, err := createSignature(opts.Signer, body)
if err != nil {
return nil, nil, err
}
body.Signature = &signature
}
req, err := s.client.NewRequest("POST", u, body)
if err != nil {
return nil, nil, err
}
c := new(Commit)
resp, err := s.client.Do(ctx, req, c)
if err != nil {
return nil, resp, err
}
return c, resp, nil
}
func createSignature(signer MessageSigner, commit *createCommit) (string, error) {
if signer == nil {
return "", errors.New("createSignature: invalid parameters")
}
message, err := createSignatureMessage(commit)
if err != nil {
return "", err
}
var writer bytes.Buffer
err = signer.Sign(&writer, strings.NewReader(message))
if err != nil {
return "", err
}
return writer.String(), nil
}
func createSignatureMessage(commit *createCommit) (string, error) {
if commit == nil || commit.Message == nil || *commit.Message == "" || commit.Author == nil {
return "", errors.New("createSignatureMessage: invalid parameters")
}
var message []string
if commit.Tree != nil {
message = append(message, fmt.Sprintf("tree %s", *commit.Tree))
}
for _, parent := range commit.Parents {
message = append(message, fmt.Sprintf("parent %s", parent))
}
message = append(message, fmt.Sprintf("author %s <%s> %d %s", commit.Author.GetName(), commit.Author.GetEmail(), commit.Author.GetDate().Unix(), commit.Author.GetDate().Format("-0700")))
committer := commit.Committer
if committer == nil {
committer = commit.Author
}
// There needs to be a double newline after committer
message = append(message, fmt.Sprintf("committer %s <%s> %d %s\n", committer.GetName(), committer.GetEmail(), committer.GetDate().Unix(), committer.GetDate().Format("-0700")))
message = append(message, *commit.Message)
return strings.Join(message, "\n"), nil
}

View file

@ -1,185 +0,0 @@
// Copyright 2013 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package github
import (
"context"
"fmt"
"net/url"
"strings"
)
// Reference represents a GitHub reference.
type Reference struct {
Ref *string `json:"ref"`
URL *string `json:"url"`
Object *GitObject `json:"object"`
NodeID *string `json:"node_id,omitempty"`
}
func (r Reference) String() string {
return Stringify(r)
}
// GitObject represents a Git object.
type GitObject struct {
Type *string `json:"type"`
SHA *string `json:"sha"`
URL *string `json:"url"`
}
func (o GitObject) String() string {
return Stringify(o)
}
// createRefRequest represents the payload for creating a reference.
type createRefRequest struct {
Ref *string `json:"ref"`
SHA *string `json:"sha"`
}
// updateRefRequest represents the payload for updating a reference.
type updateRefRequest struct {
SHA *string `json:"sha"`
Force *bool `json:"force"`
}
// GetRef fetches a single reference in a repository.
//
// GitHub API docs: https://docs.github.com/rest/git/refs#get-a-reference
//
//meta:operation GET /repos/{owner}/{repo}/git/ref/{ref}
func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref string) (*Reference, *Response, error) {
ref = strings.TrimPrefix(ref, "refs/")
u := fmt.Sprintf("repos/%v/%v/git/ref/%v", owner, repo, refURLEscape(ref))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
r := new(Reference)
resp, err := s.client.Do(ctx, req, r)
if err != nil {
return nil, resp, err
}
return r, resp, nil
}
// refURLEscape escapes every path segment of the given ref. Those must
// not contain escaped "/" - as "%2F" - or github will not recognize it.
func refURLEscape(ref string) string {
parts := strings.Split(ref, "/")
for i, s := range parts {
parts[i] = url.PathEscape(s)
}
return strings.Join(parts, "/")
}
// ReferenceListOptions specifies optional parameters to the
// GitService.ListMatchingRefs method.
type ReferenceListOptions struct {
Ref string `url:"-"`
ListOptions
}
// ListMatchingRefs lists references in a repository that match a supplied ref.
// Use an empty ref to list all references.
//
// GitHub API docs: https://docs.github.com/rest/git/refs#list-matching-references
//
//meta:operation GET /repos/{owner}/{repo}/git/matching-refs/{ref}
func (s *GitService) ListMatchingRefs(ctx context.Context, owner, repo string, opts *ReferenceListOptions) ([]*Reference, *Response, error) {
var ref string
if opts != nil {
ref = strings.TrimPrefix(opts.Ref, "refs/")
}
u := fmt.Sprintf("repos/%v/%v/git/matching-refs/%v", owner, repo, refURLEscape(ref))
u, err := addOptions(u, opts)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var rs []*Reference
resp, err := s.client.Do(ctx, req, &rs)
if err != nil {
return nil, resp, err
}
return rs, resp, nil
}
// CreateRef creates a new ref in a repository.
//
// GitHub API docs: https://docs.github.com/rest/git/refs#create-a-reference
//
//meta:operation POST /repos/{owner}/{repo}/git/refs
func (s *GitService) CreateRef(ctx context.Context, owner string, repo string, ref *Reference) (*Reference, *Response, error) {
u := fmt.Sprintf("repos/%v/%v/git/refs", owner, repo)
req, err := s.client.NewRequest("POST", u, &createRefRequest{
// back-compat with previous behavior that didn't require 'refs/' prefix
Ref: String("refs/" + strings.TrimPrefix(*ref.Ref, "refs/")),
SHA: ref.Object.SHA,
})
if err != nil {
return nil, nil, err
}
r := new(Reference)
resp, err := s.client.Do(ctx, req, r)
if err != nil {
return nil, resp, err
}
return r, resp, nil
}
// UpdateRef updates an existing ref in a repository.
//
// GitHub API docs: https://docs.github.com/rest/git/refs#update-a-reference
//
//meta:operation PATCH /repos/{owner}/{repo}/git/refs/{ref}
func (s *GitService) UpdateRef(ctx context.Context, owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error) {
refPath := strings.TrimPrefix(*ref.Ref, "refs/")
u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refURLEscape(refPath))
req, err := s.client.NewRequest("PATCH", u, &updateRefRequest{
SHA: ref.Object.SHA,
Force: &force,
})
if err != nil {
return nil, nil, err
}
r := new(Reference)
resp, err := s.client.Do(ctx, req, r)
if err != nil {
return nil, resp, err
}
return r, resp, nil
}
// DeleteRef deletes a ref from a repository.
//
// GitHub API docs: https://docs.github.com/rest/git/refs#delete-a-reference
//
//meta:operation DELETE /repos/{owner}/{repo}/git/refs/{ref}
func (s *GitService) DeleteRef(ctx context.Context, owner string, repo string, ref string) (*Response, error) {
ref = strings.TrimPrefix(ref, "refs/")
u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refURLEscape(ref))
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more