Spellcheck "server/*" (#3753)

Co-authored-by: Anbraten <6918444+anbraten@users.noreply.github.com>
Co-authored-by: qwerty287 <80460567+qwerty287@users.noreply.github.com>
This commit is contained in:
6543 2024-06-04 08:30:54 +02:00 committed by GitHub
parent 9b859b3c9e
commit 4ec046e415
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 220 additions and 196 deletions

View file

@ -12,123 +12,133 @@
], ],
"words": [ "words": [
"abool", "abool",
"BUILDPLATFORM",
"Codeberg",
"Curr",
"DATASOURCE",
"Debugf",
"Fediverse",
"Fogas",
"GOARCH",
"GOBIN",
"GODEBUG",
"GOPATH",
"Georgiana",
"HEALTHCHECK",
"HTTPFS",
"Hetzner",
"Infof",
"Ionescu",
"Kaniko",
"Keyfunc",
"LASTEXITCODE",
"Laszlo",
"Msgf",
"Netrc",
"PROTOC",
"Pinia",
"Println",
"pwsh",
"Refspec",
"Reviewdog",
"Rydzewski",
"SSHURL",
"TARGETARCH",
"TARGETOS",
"Typeflag",
"Upsert",
"WORKDIR",
"Warnf",
"Weblate",
"Wrapf",
"anbraten", "anbraten",
"apimachinery", "apimachinery",
"autoincr", "autoincr",
"autoscaler", "autoscaler",
"binutils", "binutils",
"bitbucketdatacenter", "bitbucketdatacenter",
"Boguslawski",
"bradrydzewski", "bradrydzewski",
"BUILDPLATFORM",
"buildx", "buildx",
"ccmenu", "ccmenu",
"certmagic",
"charmbracelet", "charmbracelet",
"ciphertext", "ciphertext",
"Codeberg",
"compatiblelicenses", "compatiblelicenses",
"corepack", "corepack",
"cpuset", "cpuset",
"creativecommons", "creativecommons",
"Curr",
"datacenter", "datacenter",
"DATASOURCE",
"Debugf",
"desaturate", "desaturate",
"devx", "devx",
"doublestar", "doublestar",
"envsubst", "envsubst",
"estree",
"errgroup", "errgroup",
"estree",
"evenodd", "evenodd",
"excalidraw", "excalidraw",
"favicons", "favicons",
"Fediverse",
"Fogas",
"forbidigo", "forbidigo",
"Forgejo", "Forgejo",
"fsnotify", "fsnotify",
"Georgiana",
"gitea", "gitea",
"GOARCH",
"GOBIN",
"gocritic", "gocritic",
"GODEBUG",
"golangci", "golangci",
"gomod", "gomod",
"gonic", "gonic",
"GOPATH",
"HEALTHCHECK",
"healthz",
"Hetzner",
"HTMLURL",
"HTTPFS",
"httpsig", "httpsig",
"HTTPURL",
"httputil", "httputil",
"iconify", "iconify",
"Infof",
"Informatyka",
"intlify", "intlify",
"Ionescu",
"Kaniko",
"Keyfunc",
"kyvg", "kyvg",
"LASTEXITCODE",
"Laszlo",
"laszlocph", "laszlocph",
"logfile", "logfile",
"loglevel", "loglevel",
"LONGBLOB",
"LONGTEXT",
"mapstructure", "mapstructure",
"markdownlint", "markdownlint",
"memswap", "memswap",
"Metas",
"mhmxs",
"moby", "moby",
"Msgf",
"multiarch", "multiarch",
"multierr", "multierr",
"netdns", "netdns",
"Netrc",
"nfpm", "nfpm",
"nixos", "nixos",
"nocolor", "nocolor",
"nolint", "nolint",
"norunningpipelines",
"nosniff",
"octocat", "octocat",
"Pinia",
"pkce",
"posix", "posix",
"ppid", "ppid",
"Println",
"prismjs", "prismjs",
"proto", "proto",
"protobuf", "protobuf",
"protoc", "protoc",
"PROTOC",
"protoimpl", "protoimpl",
"protoreflect", "protoreflect",
"rawurl", "pullrequest",
"pullrequests",
"pwsh",
"Redirections",
"Refspec",
"regcred", "regcred",
"repology", "repology",
"reslimit", "reslimit",
"Reviewdog",
"riscv", "riscv",
"rundll32", "rundll32",
"Rydzewski",
"seccomp", "seccomp",
"secprofile", "secprofile",
"securecookie", "securecookie",
"sess", "sess",
"shellescape", "shellescape",
"SSHURL",
"stepbuilder", "stepbuilder",
"stretchr", "stretchr",
"sublicensable", "sublicensable",
"swaggo", "swaggo",
"TARGETARCH",
"TARGETOS",
"techknowlogick", "techknowlogick",
"testdata", "testdata",
"threadcreate",
"tink", "tink",
"tinycolor", "tinycolor",
"tmpfs", "tmpfs",
@ -136,18 +146,27 @@
"tolerations", "tolerations",
"ttlcache", "ttlcache",
"typecheck", "typecheck",
"Typeflag",
"unplugin", "unplugin",
"Upsert",
"urfave", "urfave",
"varchar", "varchar",
"varz",
"vueuse", "vueuse",
"waivable", "waivable",
"Warnf",
"Weblate",
"windi", "windi",
"windicss", "windicss",
"woodpeckerci", "woodpeckerci",
"WORKDIR",
"Wrapf",
"xlink",
"xlog", "xlog",
"xorm", "xorm",
"xormigrate", "xormigrate",
"xyaml", "xyaml",
"yamls",
"zerolog", "zerolog",
"zerologger" "zerologger"
], ],
@ -175,8 +194,7 @@
"**/fixtures/**", "**/fixtures/**",
"**/testdata/**", "**/testdata/**",
// TODO: remove the following // TODO: remove the following
"docs/", "docs/"
"server/"
], ],
// Exclude imports, because they are also strings. // Exclude imports, because they are also strings.
"ignoreRegExpList": [ "ignoreRegExpList": [

View file

@ -173,7 +173,7 @@ test-server-datastore: ## Test server datastore
go test -race -timeout 30s -skip TestMigrate go.woodpecker-ci.org/woodpecker/v2/server/store/... go test -race -timeout 30s -skip TestMigrate go.woodpecker-ci.org/woodpecker/v2/server/store/...
test-server-datastore-coverage: ## Test server datastore with coverage report test-server-datastore-coverage: ## Test server datastore with coverage report
go test -race -cover -coverprofile datastore-coverage.out -timeout 120s go.woodpecker-ci.org/woodpecker/v2/server/store/... go test -race -cover -coverprofile datastore-coverage.out -timeout 180s go.woodpecker-ci.org/woodpecker/v2/server/store/...
test-ui: ui-dependencies ## Test UI code test-ui: ui-dependencies ## Test UI code
(cd web/; pnpm run lint) (cd web/; pnpm run lint)

View file

@ -32,8 +32,8 @@ import (
// https://github.com/mozilla-services/Dockerflow // https://github.com/mozilla-services/Dockerflow
func initHealth() { func initHealth() {
http.HandleFunc("/varz", handleStats) // cspell:words varz http.HandleFunc("/varz", handleStats)
http.HandleFunc("/healthz", handleHeartbeat) // cspell:words healthz http.HandleFunc("/healthz", handleHeartbeat)
http.HandleFunc("/version", handleVersion) http.HandleFunc("/version", handleVersion)
} }

View file

@ -874,7 +874,7 @@ const docTemplate = `{
}, },
{ {
"type": "string", "type": "string",
"description": "the organziation's id", "description": "the organization's id",
"name": "org_id", "name": "org_id",
"in": "path", "in": "path",
"required": true "required": true
@ -913,7 +913,7 @@ const docTemplate = `{
}, },
{ {
"type": "string", "type": "string",
"description": "the organziation's id", "description": "the organization's id",
"name": "org_id", "name": "org_id",
"in": "path", "in": "path",
"required": true "required": true

View file

@ -38,7 +38,7 @@ var flags = append([]cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
EnvVars: []string{"WOODPECKER_HOST"}, EnvVars: []string{"WOODPECKER_HOST"},
Name: "server-host", Name: "server-host",
Usage: "server fully qualified url. Format: <scheme>://<host>[/<prefixpath>]", Usage: "server fully qualified url. Format: <scheme>://<host>[/<prefix path>]",
}, },
&cli.StringFlag{ &cli.StringFlag{
EnvVars: []string{"WOODPECKER_SERVER_ADDR"}, EnvVars: []string{"WOODPECKER_SERVER_ADDR"},
@ -114,7 +114,7 @@ var flags = append([]cli.Flag{
&cli.StringSliceFlag{ &cli.StringSliceFlag{
EnvVars: []string{"WOODPECKER_REPO_OWNERS"}, EnvVars: []string{"WOODPECKER_REPO_OWNERS"},
Name: "repo-owners", Name: "repo-owners",
Usage: "List of syncable repo owners", Usage: "Repositories by those owners will be allowed to be used in woodpecker",
}, },
&cli.BoolFlag{ &cli.BoolFlag{
EnvVars: []string{"WOODPECKER_OPEN"}, EnvVars: []string{"WOODPECKER_OPEN"},
@ -277,7 +277,7 @@ var flags = append([]cli.Flag{
&cli.Int64Flag{ &cli.Int64Flag{
EnvVars: []string{"WOODPECKER_LIMIT_MEM_SWAP"}, EnvVars: []string{"WOODPECKER_LIMIT_MEM_SWAP"},
Name: "limit-mem-swap", Name: "limit-mem-swap",
Usage: "maximum swappable memory allowed in bytes", Usage: "maximum memory used for swap in bytes",
}, },
&cli.Int64Flag{ &cli.Int64Flag{
EnvVars: []string{"WOODPECKER_LIMIT_MEM"}, EnvVars: []string{"WOODPECKER_LIMIT_MEM"},
@ -330,7 +330,7 @@ var flags = append([]cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
EnvVars: []string{"WOODPECKER_EXPERT_FORGE_OAUTH_HOST", "WOODPECKER_DEV_GITEA_OAUTH_URL"}, // TODO: remove WOODPECKER_DEV_GITEA_OAUTH_URL in next major release EnvVars: []string{"WOODPECKER_EXPERT_FORGE_OAUTH_HOST", "WOODPECKER_DEV_GITEA_OAUTH_URL"}, // TODO: remove WOODPECKER_DEV_GITEA_OAUTH_URL in next major release
Name: "forge-oauth-host", Name: "forge-oauth-host",
Usage: "!!!for experts!!! fully qualified public forge url. Use it if your forge url WOODPECKER_FORGE_URL or WOODPECKER_GITEA_URL, ... isn't a public url. Format: <scheme>://<host>[/<prefixpath>]", Usage: "!!!for experts!!! fully qualified public forge url. Use it if your forge url WOODPECKER_FORGE_URL or WOODPECKER_GITEA_URL, ... isn't a public url. Format: <scheme>://<host>[/<prefix path>]",
}, },
// //
// Addon // Addon
@ -427,13 +427,13 @@ var flags = append([]cli.Flag{
&cli.StringFlag{ &cli.StringFlag{
EnvVars: []string{"WOODPECKER_EXPERT_WEBHOOK_HOST", "WOODPECKER_WEBHOOK_HOST"}, // TODO: remove WOODPECKER_WEBHOOK_HOST in next major release EnvVars: []string{"WOODPECKER_EXPERT_WEBHOOK_HOST", "WOODPECKER_WEBHOOK_HOST"}, // TODO: remove WOODPECKER_WEBHOOK_HOST in next major release
Name: "server-webhook-host", Name: "server-webhook-host",
Usage: "!!!for experts!!! fully qualified woodpecker server url called by forge's webhooks. Format: <scheme>://<host>[/<prefixpath>]", Usage: "!!!for experts!!! fully qualified woodpecker server url called by forge's webhooks. Format: <scheme>://<host>[/<prefix path>]",
}, },
// TODO: remove in next major release // TODO: remove in next major release
&cli.StringFlag{ &cli.StringFlag{
EnvVars: []string{"WOODPECKER_DEV_OAUTH_HOST"}, EnvVars: []string{"WOODPECKER_DEV_OAUTH_HOST"},
Name: "server-dev-oauth-host-deprecated", Name: "server-dev-oauth-host-deprecated",
Usage: "DEPRECATED: use WOODPECKER_EXPERT_FORGE_OAUTH_HOST instead\nfully qualified url used for oauth redirects. Format: <scheme>://<host>[/<prefixpath>]", Usage: "DEPRECATED: use WOODPECKER_EXPERT_FORGE_OAUTH_HOST instead\nfully qualified url used for oauth redirects. Format: <scheme>://<host>[/<prefix path>]",
Value: "", Value: "",
Hidden: true, Hidden: true,
}, },

View file

@ -27,7 +27,7 @@ import (
"github.com/caddyserver/certmagic" "github.com/caddyserver/certmagic"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp" prometheus_http "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
@ -250,7 +250,7 @@ func run(c *cli.Context) error {
if metricsServerAddr := c.String("metrics-server-addr"); metricsServerAddr != "" { if metricsServerAddr := c.String("metrics-server-addr"); metricsServerAddr != "" {
g.Go(func() error { g.Go(func() error {
metricsRouter := gin.New() metricsRouter := gin.New()
metricsRouter.GET("/metrics", gin.WrapH(promhttp.Handler())) metricsRouter.GET("/metrics", gin.WrapH(prometheus_http.Handler()))
err := http.ListenAndServe(metricsServerAddr, metricsRouter) err := http.ListenAndServe(metricsServerAddr, metricsRouter)
if err != nil && !errors.Is(err, http.ErrServerClosed) { if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal().Err(err).Msg("could not start metrics server") //nolint:forbidigo log.Fatal().Err(err).Msg("could not start metrics server") //nolint:forbidigo
@ -270,11 +270,11 @@ func setupEvilGlobals(c *cli.Context, s store.Store) error {
server.Config.Services.Logs = logging.New() server.Config.Services.Logs = logging.New()
server.Config.Services.Pubsub = pubsub.New() server.Config.Services.Pubsub = pubsub.New()
server.Config.Services.Membership = setupMembershipService(c, s) server.Config.Services.Membership = setupMembershipService(c, s)
serviceMangager, err := services.NewManager(c, s, setup.Forge) serviceManager, err := services.NewManager(c, s, setup.Forge)
if err != nil { if err != nil {
return fmt.Errorf("could not setup service manager: %w", err) return fmt.Errorf("could not setup service manager: %w", err)
} }
server.Config.Services.Manager = serviceMangager server.Config.Services.Manager = serviceManager
// authentication // authentication
server.Config.Pipeline.AuthenticatePublicRepos = c.Bool("authenticate-public-repos") server.Config.Pipeline.AuthenticatePublicRepos = c.Bool("authenticate-public-repos")

View file

@ -22,7 +22,7 @@ import (
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto" prometheus_auto "github.com/prometheus/client_golang/prometheus/promauto"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
@ -96,37 +96,37 @@ func setupMembershipService(_ *cli.Context, _store store.Store) cache.Membership
} }
func setupMetrics(g *errgroup.Group, _store store.Store) { func setupMetrics(g *errgroup.Group, _store store.Store) {
pendingSteps := promauto.NewGauge(prometheus.GaugeOpts{ pendingSteps := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "pending_steps", Name: "pending_steps",
Help: "Total number of pending pipeline steps.", Help: "Total number of pending pipeline steps.",
}) })
waitingSteps := promauto.NewGauge(prometheus.GaugeOpts{ waitingSteps := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "waiting_steps", Name: "waiting_steps",
Help: "Total number of pipeline waiting on deps.", Help: "Total number of pipeline waiting on deps.",
}) })
runningSteps := promauto.NewGauge(prometheus.GaugeOpts{ runningSteps := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "running_steps", Name: "running_steps",
Help: "Total number of running pipeline steps.", Help: "Total number of running pipeline steps.",
}) })
workers := promauto.NewGauge(prometheus.GaugeOpts{ workers := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "worker_count", Name: "worker_count",
Help: "Total number of workers.", Help: "Total number of workers.",
}) })
pipelines := promauto.NewGauge(prometheus.GaugeOpts{ pipelines := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "pipeline_total_count", Name: "pipeline_total_count",
Help: "Total number of pipelines.", Help: "Total number of pipelines.",
}) })
users := promauto.NewGauge(prometheus.GaugeOpts{ users := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "user_count", Name: "user_count",
Help: "Total number of users.", Help: "Total number of users.",
}) })
repos := promauto.NewGauge(prometheus.GaugeOpts{ repos := prometheus_auto.NewGauge(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "repo_count", Name: "repo_count",
Help: "Total number of repos.", Help: "Total number of repos.",

View file

@ -55,7 +55,7 @@ func HandleAuth(c *gin.Context) {
// cannot, however, remember why, so need to revisit this line. // cannot, however, remember why, so need to revisit this line.
c.Writer.Header().Del("Content-Type") c.Writer.Header().Del("Content-Type")
tmpuser, redirectURL, err := _forge.Login(c, &forge_types.OAuthRequest{ tmpUser, redirectURL, err := _forge.Login(c, &forge_types.OAuthRequest{
Error: c.Request.FormValue("error"), Error: c.Request.FormValue("error"),
ErrorURI: c.Request.FormValue("error_uri"), ErrorURI: c.Request.FormValue("error_uri"),
ErrorDescription: c.Request.FormValue("error_description"), ErrorDescription: c.Request.FormValue("error_description"),
@ -67,13 +67,13 @@ func HandleAuth(c *gin.Context) {
return return
} }
// The user is not authorized yet -> redirect // The user is not authorized yet -> redirect
if tmpuser == nil { if tmpUser == nil {
http.Redirect(c.Writer, c.Request, redirectURL, http.StatusSeeOther) http.Redirect(c.Writer, c.Request, redirectURL, http.StatusSeeOther)
return return
} }
// get the user from the database // get the user from the database
u, err := _store.GetUserRemoteID(tmpuser.ForgeRemoteID, tmpuser.Login) u, err := _store.GetUserRemoteID(tmpUser.ForgeRemoteID, tmpUser.Login)
if err != nil && !errors.Is(err, types.RecordNotExist) { if err != nil && !errors.Is(err, types.RecordNotExist) {
_ = c.AbortWithError(http.StatusInternalServerError, err) _ = c.AbortWithError(http.StatusInternalServerError, err)
return return
@ -81,8 +81,8 @@ func HandleAuth(c *gin.Context) {
if errors.Is(err, types.RecordNotExist) { if errors.Is(err, types.RecordNotExist) {
// if self-registration is disabled we should return a not authorized error // if self-registration is disabled we should return a not authorized error
if !server.Config.Permissions.Open && !server.Config.Permissions.Admins.IsAdmin(tmpuser) { if !server.Config.Permissions.Open && !server.Config.Permissions.Admins.IsAdmin(tmpUser) {
log.Error().Msgf("cannot register %s. registration closed", tmpuser.Login) log.Error().Msgf("cannot register %s. registration closed", tmpUser.Login)
c.Redirect(http.StatusSeeOther, server.Config.Server.RootPath+"/login?error=access_denied") c.Redirect(http.StatusSeeOther, server.Config.Server.RootPath+"/login?error=access_denied")
return return
} }
@ -90,7 +90,7 @@ func HandleAuth(c *gin.Context) {
// if self-registration is enabled for allowed organizations we need to // if self-registration is enabled for allowed organizations we need to
// check the user's organization membership. // check the user's organization membership.
if server.Config.Permissions.Orgs.IsConfigured { if server.Config.Permissions.Orgs.IsConfigured {
teams, terr := _forge.Teams(c, tmpuser) teams, terr := _forge.Teams(c, tmpUser)
if terr != nil || !server.Config.Permissions.Orgs.IsMember(teams) { if terr != nil || !server.Config.Permissions.Orgs.IsMember(teams) {
log.Error().Err(terr).Msgf("cannot verify team membership for %s.", u.Login) log.Error().Err(terr).Msgf("cannot verify team membership for %s.", u.Login)
c.Redirect(http.StatusSeeOther, server.Config.Server.RootPath+"/login?error=access_denied") c.Redirect(http.StatusSeeOther, server.Config.Server.RootPath+"/login?error=access_denied")
@ -100,12 +100,12 @@ func HandleAuth(c *gin.Context) {
// create the user account // create the user account
u = &model.User{ u = &model.User{
Login: tmpuser.Login, Login: tmpUser.Login,
ForgeRemoteID: tmpuser.ForgeRemoteID, ForgeRemoteID: tmpUser.ForgeRemoteID,
Token: tmpuser.Token, Token: tmpUser.Token,
Secret: tmpuser.Secret, Secret: tmpUser.Secret,
Email: tmpuser.Email, Email: tmpUser.Email,
Avatar: tmpuser.Avatar, Avatar: tmpUser.Avatar,
ForgeID: forgeID, ForgeID: forgeID,
Hash: base32.StdEncoding.EncodeToString( Hash: base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(32), securecookie.GenerateRandomKey(32),
@ -146,7 +146,7 @@ func HandleAuth(c *gin.Context) {
} }
// update org name // update org name
if u.Login != tmpuser.Login { if u.Login != tmpUser.Login {
org, err := _store.OrgGet(u.OrgID) org, err := _store.OrgGet(u.OrgID)
if err != nil { if err != nil {
log.Error().Err(err).Msgf("cannot get org %s", u.Login) log.Error().Err(err).Msgf("cannot get org %s", u.Login)
@ -160,13 +160,13 @@ func HandleAuth(c *gin.Context) {
} }
// update the user meta data and authorization data. // update the user meta data and authorization data.
u.Token = tmpuser.Token u.Token = tmpUser.Token
u.Secret = tmpuser.Secret u.Secret = tmpUser.Secret
u.Email = tmpuser.Email u.Email = tmpUser.Email
u.Avatar = tmpuser.Avatar u.Avatar = tmpUser.Avatar
u.ForgeRemoteID = tmpuser.ForgeRemoteID u.ForgeRemoteID = tmpUser.ForgeRemoteID
u.Login = tmpuser.Login u.Login = tmpUser.Login
u.Admin = u.Admin || server.Config.Permissions.Admins.IsAdmin(tmpuser) u.Admin = u.Admin || server.Config.Permissions.Admins.IsAdmin(tmpUser)
// if self-registration is enabled for allowed organizations we need to // if self-registration is enabled for allowed organizations we need to
// check the user's organization membership. // check the user's organization membership.

View file

@ -20,7 +20,7 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp" prometheus_http "github.com/prometheus/client_golang/prometheus/promhttp"
"go.woodpecker-ci.org/woodpecker/v2/server" "go.woodpecker-ci.org/woodpecker/v2/server"
) )
@ -30,7 +30,7 @@ var errInvalidToken = errors.New("invalid or missing token")
// PromHandler will pass the call from /api/metrics/prometheus to prometheus. // PromHandler will pass the call from /api/metrics/prometheus to prometheus.
func PromHandler() gin.HandlerFunc { func PromHandler() gin.HandlerFunc {
handler := promhttp.Handler() handler := prometheus_http.Handler()
return func(c *gin.Context) { return func(c *gin.Context) {
token := server.Config.Prometheus.AuthToken token := server.Config.Prometheus.AuthToken

View file

@ -36,7 +36,7 @@ import (
// @Success 200 {array} Org // @Success 200 {array} Org
// @Tags Organization // @Tags Organization
// @Param Authorization header string true "Insert your personal access token" default(Bearer <personal access token>) // @Param Authorization header string true "Insert your personal access token" default(Bearer <personal access token>)
// @Param org_id path string true "the organziation's id" // @Param org_id path string true "the organization's id"
func GetOrg(c *gin.Context) { func GetOrg(c *gin.Context) {
_store := store.FromContext(c) _store := store.FromContext(c)
@ -63,7 +63,7 @@ func GetOrg(c *gin.Context) {
// @Success 200 {array} OrgPerm // @Success 200 {array} OrgPerm
// @Tags Organization permissions // @Tags Organization permissions
// @Param Authorization header string true "Insert your personal access token" default(Bearer <personal access token>) // @Param Authorization header string true "Insert your personal access token" default(Bearer <personal access token>)
// @Param org_id path string true "the organziation's id" // @Param org_id path string true "the organization's id"
func GetOrgPermissions(c *gin.Context) { func GetOrgPermissions(c *gin.Context) {
user := session.User(c) user := session.User(c)
_store := store.FromContext(c) _store := store.FromContext(c)

View file

@ -580,11 +580,11 @@ func PostPipeline(c *gin.Context) {
} }
} }
newpipeline, err := pipeline.Restart(c, _store, pl, user, repo, envs) newPipeline, err := pipeline.Restart(c, _store, pl, user, repo, envs)
if err != nil { if err != nil {
handlePipelineErr(c, err) handlePipelineErr(c, err)
} else { } else {
c.JSON(http.StatusOK, newpipeline) c.JSON(http.StatusOK, newPipeline)
} }
} }

View file

@ -220,7 +220,7 @@ func PatchRepo(c *gin.Context) {
} }
if in.Timeout != nil && *in.Timeout > server.Config.Pipeline.MaxTimeout && !user.Admin { if in.Timeout != nil && *in.Timeout > server.Config.Pipeline.MaxTimeout && !user.Admin {
c.String(http.StatusForbidden, fmt.Sprintf("Timeout is not allowed to be higher than max timeout (%dmin)", server.Config.Pipeline.MaxTimeout)) c.String(http.StatusForbidden, fmt.Sprintf("Timeout is not allowed to be higher than max timeout (%d min)", server.Config.Pipeline.MaxTimeout))
return return
} }
if in.IsTrusted != nil && *in.IsTrusted != repo.IsTrusted && !user.Admin { if in.IsTrusted != nil && *in.IsTrusted != repo.IsTrusted && !user.Admin {

View file

@ -71,14 +71,14 @@ func EventStreamSSE(c *gin.Context) {
} }
} }
eventc := make(chan []byte, 10) eventChan := make(chan []byte, 10)
ctx, cancel := context.WithCancelCause( ctx, cancel := context.WithCancelCause(
context.Background(), context.Background(),
) )
defer func() { defer func() {
cancel(nil) cancel(nil)
close(eventc) close(eventChan)
log.Debug().Msg("user feed: connection closed") log.Debug().Msg("user feed: connection closed")
}() }()
@ -95,7 +95,7 @@ func EventStreamSSE(c *gin.Context) {
case <-ctx.Done(): case <-ctx.Done():
return return
default: default:
eventc <- m.Data eventChan <- m.Data
} }
} }
}) })
@ -111,7 +111,7 @@ func EventStreamSSE(c *gin.Context) {
case <-time.After(time.Second * 30): case <-time.After(time.Second * 30):
logWriteStringErr(io.WriteString(rw, ": ping\n\n")) logWriteStringErr(io.WriteString(rw, ": ping\n\n"))
flusher.Flush() flusher.Flush()
case buf, ok := <-eventc: case buf, ok := <-eventChan:
if ok { if ok {
logWriteStringErr(io.WriteString(rw, "data: ")) logWriteStringErr(io.WriteString(rw, "data: "))
logWriteStringErr(rw.Write(buf)) logWriteStringErr(rw.Write(buf))
@ -192,7 +192,7 @@ func LogStreamSSE(c *gin.Context) {
return return
} }
logc := make(chan []byte, 10) logChan := make(chan []byte, 10)
ctx, cancel := context.WithCancelCause( ctx, cancel := context.WithCancelCause(
context.Background(), context.Background(),
) )
@ -201,7 +201,7 @@ func LogStreamSSE(c *gin.Context) {
defer func() { defer func() {
cancel(nil) cancel(nil)
close(logc) close(logChan)
log.Debug().Msg("log stream: connection closed") log.Debug().Msg("log stream: connection closed")
}() }()
@ -213,7 +213,7 @@ func LogStreamSSE(c *gin.Context) {
return return
default: default:
ee, _ := json.Marshal(entry) ee, _ := json.Marshal(entry)
logc <- ee logChan <- ee
} }
} }
}) })
@ -250,7 +250,7 @@ func LogStreamSSE(c *gin.Context) {
case <-time.After(time.Second * 30): case <-time.After(time.Second * 30):
logWriteStringErr(io.WriteString(rw, ": ping\n\n")) logWriteStringErr(io.WriteString(rw, ": ping\n\n"))
flusher.Flush() flusher.Flush()
case buf, ok := <-logc: case buf, ok := <-logChan:
if ok { if ok {
if id > last { if id > last {
logWriteStringErr(io.WriteString(rw, "id: "+strconv.Itoa(id))) logWriteStringErr(io.WriteString(rw, "id: "+strconv.Itoa(id)))

View file

@ -16,6 +16,8 @@ package badges
import "go.woodpecker-ci.org/woodpecker/v2/server/model" import "go.woodpecker-ci.org/woodpecker/v2/server/model"
// cspell:words Verdana
var ( var (
badgeSuccess = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="106" height="20" role="img" aria-label="pipeline: success"><title>pipeline: success</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="106" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="53" height="20" fill="#555"/><rect x="53" width="53" height="20" fill="#44cc11"/><rect width="106" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="275" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">pipeline</text><text x="275" y="140" transform="scale(.1)" fill="#fff" textLength="430">pipeline</text><text aria-hidden="true" x="785" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">success</text><text x="785" y="140" transform="scale(.1)" fill="#fff" textLength="430">success</text></g></svg>` badgeSuccess = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="106" height="20" role="img" aria-label="pipeline: success"><title>pipeline: success</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="106" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="53" height="20" fill="#555"/><rect x="53" width="53" height="20" fill="#44cc11"/><rect width="106" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="275" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">pipeline</text><text x="275" y="140" transform="scale(.1)" fill="#fff" textLength="430">pipeline</text><text aria-hidden="true" x="785" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">success</text><text x="785" y="140" transform="scale(.1)" fill="#fff" textLength="430">success</text></g></svg>`
badgeFailure = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="98" height="20" role="img" aria-label="pipeline: failure"><title>pipeline: failure</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="98" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="53" height="20" fill="#555"/><rect x="53" width="45" height="20" fill="#e05d44"/><rect width="98" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="275" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">pipeline</text><text x="275" y="140" transform="scale(.1)" fill="#fff" textLength="430">pipeline</text><text aria-hidden="true" x="745" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="350">failure</text><text x="745" y="140" transform="scale(.1)" fill="#fff" textLength="350">failure</text></g></svg>` badgeFailure = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="98" height="20" role="img" aria-label="pipeline: failure"><title>pipeline: failure</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="98" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="53" height="20" fill="#555"/><rect x="53" width="45" height="20" fill="#e05d44"/><rect width="98" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="275" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">pipeline</text><text x="275" y="140" transform="scale(.1)" fill="#fff" textLength="430">pipeline</text><text aria-hidden="true" x="745" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="350">failure</text><text x="745" y="140" transform="scale(.1)" fill="#fff" textLength="350">failure</text></g></svg>`

View file

@ -17,7 +17,7 @@ package addon
import ( import (
"bytes" "bytes"
"io" "io"
stdlog "log" std_log "log"
"github.com/hashicorp/go-hclog" "github.com/hashicorp/go-hclog"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -30,6 +30,8 @@ type clientLogger struct {
withArgs []any withArgs []any
} }
// cspell:words hclog
func convertLvl(level hclog.Level) zerolog.Level { func convertLvl(level hclog.Level) zerolog.Level {
switch level { switch level {
case hclog.Error: case hclog.Error:
@ -162,8 +164,8 @@ func (c *clientLogger) GetLevel() hclog.Level {
return hclog.NoLevel return hclog.NoLevel
} }
func (c *clientLogger) StandardLogger(opts *hclog.StandardLoggerOptions) *stdlog.Logger { func (c *clientLogger) StandardLogger(opts *hclog.StandardLoggerOptions) *std_log.Logger {
return stdlog.New(c.StandardWriter(opts), "", 0) return std_log.New(c.StandardWriter(opts), "", 0)
} }
func (c *clientLogger) StandardWriter(*hclog.StandardLoggerOptions) io.Writer { func (c *clientLogger) StandardWriter(*hclog.StandardLoggerOptions) io.Writer {

View file

@ -204,13 +204,13 @@ func (c *config) Repos(ctx context.Context, u *model.User) ([]*model.Repo, error
return nil, err return nil, err
} }
userPermisions, err := client.ListPermissionsAll() userPermissions, err := client.ListPermissionsAll()
if err != nil { if err != nil {
return nil, err return nil, err
} }
userPermissionsByRepo := make(map[string]*internal.RepoPerm) userPermissionsByRepo := make(map[string]*internal.RepoPerm)
for _, permission := range userPermisions { for _, permission := range userPermissions {
userPermissionsByRepo[permission.Repo.FullName] = permission userPermissionsByRepo[permission.Repo.FullName] = permission
} }
@ -313,7 +313,7 @@ func (c *config) Status(ctx context.Context, user *model.User, repo *model.Repo,
// the Bitbucket repository. Prior to registering hook, previously created hooks // the Bitbucket repository. Prior to registering hook, previously created hooks
// are deleted. // are deleted.
func (c *config) Activate(ctx context.Context, u *model.User, r *model.Repo, link string) error { func (c *config) Activate(ctx context.Context, u *model.User, r *model.Repo, link string) error {
rawurl, err := url.Parse(link) rawURL, err := url.Parse(link)
if err != nil { if err != nil {
return err return err
} }
@ -321,7 +321,7 @@ func (c *config) Activate(ctx context.Context, u *model.User, r *model.Repo, lin
return c.newClient(ctx, u).CreateHook(r.Owner, r.Name, &internal.Hook{ return c.newClient(ctx, u).CreateHook(r.Owner, r.Name, &internal.Hook{
Active: true, Active: true,
Desc: rawurl.Host, Desc: rawURL.Host,
Events: []string{"repo:push", "pullrequest:created"}, Events: []string{"repo:push", "pullrequest:created"},
URL: link, URL: link,
}) })
@ -468,14 +468,14 @@ func (c *config) newOAuth2Config() *oauth2.Config {
} }
// helper function to return matching hooks. // helper function to return matching hooks.
func matchingHooks(hooks []*internal.Hook, rawurl string) *internal.Hook { func matchingHooks(hooks []*internal.Hook, rawURL string) *internal.Hook {
link, err := url.Parse(rawurl) link, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil return nil
} }
for _, hook := range hooks { for _, hook := range hooks {
hookurl, err := url.Parse(hook.URL) hookURL, err := url.Parse(hook.URL)
if err == nil && hookurl.Host == link.Host { if err == nil && hookURL.Host == link.Host {
return hook return hook
} }
} }

View file

@ -28,7 +28,7 @@ import (
) )
const ( const (
statusPending = "INPROGRESS" statusPending = "INPROGRESS" // cspell:disable-line
statusSuccess = "SUCCESSFUL" statusSuccess = "SUCCESSFUL"
statusFailure = "FAILED" statusFailure = "FAILED"
) )
@ -60,7 +60,7 @@ func convertRepo(from *internal.Repo, perm *internal.RepoPerm) *model.Repo {
IsSCMPrivate: from.IsPrivate, IsSCMPrivate: from.IsPrivate,
Avatar: from.Owner.Links.Avatar.Href, Avatar: from.Owner.Links.Avatar.Href,
SCMKind: model.SCMKind(from.Scm), SCMKind: model.SCMKind(from.Scm),
Branch: from.Mainbranch.Name, Branch: from.MainBranch.Name,
Perm: convertPerm(perm), Perm: convertPerm(perm),
PREnabled: true, PREnabled: true,
} }
@ -107,10 +107,10 @@ func cloneLink(repo *internal.Repo) string {
// if bitbucket tries to automatically populate the user in the url we must // if bitbucket tries to automatically populate the user in the url we must
// strip it out. // strip it out.
cloneurl, err := url.Parse(clone) cloneURL, err := url.Parse(clone)
if err == nil { if err == nil {
cloneurl.User = nil cloneURL.User = nil
clone = cloneurl.String() clone = cloneURL.String()
} }
return clone return clone
@ -217,8 +217,8 @@ func convertPushHook(hook *internal.PushHook, change *internal.Change) *model.Pi
var reGitMail = regexp.MustCompile("<(.*)>") var reGitMail = regexp.MustCompile("<(.*)>")
// extracts the email from a git commit author string. // extracts the email from a git commit author string.
func extractEmail(gitauthor string) (author string) { func extractEmail(gitAuthor string) (author string) {
matches := reGitMail.FindAllStringSubmatch(gitauthor, -1) matches := reGitMail.FindAllStringSubmatch(gitAuthor, -1)
if len(matches) == 1 { if len(matches) == 1 {
author = matches[0][1] author = matches[0][1]
} }

View file

@ -258,8 +258,8 @@ func (c *Client) GetRepoFiles(owner, name, revision, path string, page *string)
return out, err return out, err
} }
func (c *Client) do(rawurl, method string, in, out any) (*string, error) { func (c *Client) do(rawURL, method string, in, out any) (*string, error) {
uri, err := url.Parse(rawurl) uri, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -20,6 +20,8 @@ import (
"time" "time"
) )
// cspell:words pagelen
type Account struct { type Account struct {
UUID string `json:"uuid"` UUID string `json:"uuid"`
Login string `json:"username"` Login string `json:"username"`
@ -108,10 +110,10 @@ type Repo struct {
Scm string `json:"scm"` Scm string `json:"scm"`
Desc string `json:"desc"` Desc string `json:"desc"`
Links Links `json:"links"` Links Links `json:"links"`
Mainbranch struct { MainBranch struct {
Type string `json:"type"` Type string `json:"type"`
Name string `json:"name"` Name string `json:"name"`
} `json:"mainbranch"` } `json:"mainbranch"` // cspell:ignore mainbranch
} }
type RepoResp struct { type RepoResp struct {

View file

@ -96,7 +96,7 @@ func (c *client) URL() string {
func (c *client) Login(ctx context.Context, req *forge_types.OAuthRequest) (*model.User, string, error) { func (c *client) Login(ctx context.Context, req *forge_types.OAuthRequest) (*model.User, string, error) {
config := c.newOAuth2Config() config := c.newOAuth2Config()
// TODO: Add proper state and pkce... // TODO: Add proper state and pkce (https://oauth.net/2/pkce/) ...
redirectURL := config.AuthCodeURL("woodpecker") redirectURL := config.AuthCodeURL("woodpecker")
if req.Error != "" { if req.Error != "" {
@ -298,12 +298,12 @@ func (c *client) Dir(ctx context.Context, u *model.User, r *model.Repo, p *model
return nil, err return nil, err
} }
for _, f := range list { for _, f := range list {
fullpath := fmt.Sprintf("%s/%s", path, f) fullPath := fmt.Sprintf("%s/%s", path, f)
data, err := c.File(ctx, u, r, p, fullpath) data, err := c.File(ctx, u, r, p, fullPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
all = append(all, &forge_types.FileMeta{Name: fullpath, Data: data}) all = append(all, &forge_types.FileMeta{Name: fullPath, Data: data})
} }
if resp.LastPage { if resp.LastPage {
break break
@ -423,7 +423,7 @@ func (c *client) Activate(ctx context.Context, u *model.User, r *model.Repo, lin
err = c.Deactivate(ctx, u, r, link) err = c.Deactivate(ctx, u, r, link)
if err != nil { if err != nil {
return fmt.Errorf("unable to deactive old webhooks: %w", err) return fmt.Errorf("unable to deactivate old webhooks: %w", err)
} }
webhook := &bb.Webhook{ webhook := &bb.Webhook{

View file

@ -25,7 +25,7 @@ import (
) )
const ( const (
currentUserID = "%s/plugins/servlet/applinks/whoami" currentUserID = "%s/plugins/servlet/applinks/whoami" // cspell:disable-line
) )
type Client struct { type Client struct {

View file

@ -231,36 +231,36 @@ func fixMalformedAvatar(url string) string {
// expandAvatar is a helper function that converts a relative avatar URL to the // expandAvatar is a helper function that converts a relative avatar URL to the
// absolute url. // absolute url.
func expandAvatar(repo, rawurl string) string { func expandAvatar(repo, rawURL string) string {
aurl, err := url.Parse(rawurl) aURL, err := url.Parse(rawURL)
if err != nil { if err != nil {
return rawurl return rawURL
} }
if aurl.IsAbs() { if aURL.IsAbs() {
// Url is already absolute // Url is already absolute
return aurl.String() return aURL.String()
} }
// Resolve to base // Resolve to base
burl, err := url.Parse(repo) burl, err := url.Parse(repo)
if err != nil { if err != nil {
return rawurl return rawURL
} }
aurl = burl.ResolveReference(aurl) aURL = burl.ResolveReference(aURL)
return aurl.String() return aURL.String()
} }
// helper function to return matching hooks. // helper function to return matching hooks.
func matchingHooks(hooks []*forgejo.Hook, rawurl string) *forgejo.Hook { func matchingHooks(hooks []*forgejo.Hook, rawURL string) *forgejo.Hook {
link, err := url.Parse(rawurl) link, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil return nil
} }
for _, hook := range hooks { for _, hook := range hooks {
if val, ok := hook.Config["url"]; ok { if val, ok := hook.Config["url"]; ok {
hookurl, err := url.Parse(val) hookURL, err := url.Parse(val)
if err == nil && hookurl.Host == link.Host { if err == nil && hookURL.Host == link.Host {
return hook return hook
} }
} }

View file

@ -230,36 +230,36 @@ func fixMalformedAvatar(url string) string {
} }
// expandAvatar converts a relative avatar URL to the absolute url. // expandAvatar converts a relative avatar URL to the absolute url.
func expandAvatar(repo, rawurl string) string { func expandAvatar(repo, rawURL string) string {
aurl, err := url.Parse(rawurl) aURL, err := url.Parse(rawURL)
if err != nil { if err != nil {
return rawurl return rawURL
} }
if aurl.IsAbs() { if aURL.IsAbs() {
// Url is already absolute // Url is already absolute
return aurl.String() return aURL.String()
} }
// Resolve to base // Resolve to base
burl, err := url.Parse(repo) burl, err := url.Parse(repo)
if err != nil { if err != nil {
return rawurl return rawURL
} }
aurl = burl.ResolveReference(aurl) aURL = burl.ResolveReference(aURL)
return aurl.String() return aURL.String()
} }
// matchingHooks return matching hooks. // matchingHooks return matching hooks.
func matchingHooks(hooks []*gitea.Hook, rawurl string) *gitea.Hook { func matchingHooks(hooks []*gitea.Hook, rawURL string) *gitea.Hook {
link, err := url.Parse(rawurl) link, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil return nil
} }
for _, hook := range hooks { for _, hook := range hooks {
if val, ok := hook.Config["url"]; ok { if val, ok := hook.Config["url"]; ok {
hookurl, err := url.Parse(val) hookURL, err := url.Parse(val)
if err == nil && hookurl.Host == link.Host { if err == nil && hookURL.Host == link.Host {
return hook return hook
} }
} }

View file

@ -260,7 +260,7 @@ func (c *client) Dir(ctx context.Context, u *model.User, r *model.Repo, b *model
} }
fc := make(chan *forge_types.FileMeta) fc := make(chan *forge_types.FileMeta)
errc := make(chan error) errChan := make(chan error)
for _, file := range data { for _, file := range data {
go func(path string) { go func(path string) {
@ -269,7 +269,7 @@ func (c *client) Dir(ctx context.Context, u *model.User, r *model.Repo, b *model
if errors.Is(err, &forge_types.ErrConfigNotFound{}) { if errors.Is(err, &forge_types.ErrConfigNotFound{}) {
err = fmt.Errorf("git tree reported existence of file but we got: %s", err.Error()) err = fmt.Errorf("git tree reported existence of file but we got: %s", err.Error())
} }
errc <- err errChan <- err
} else { } else {
fc <- &forge_types.FileMeta{ fc <- &forge_types.FileMeta{
Name: path, Name: path,
@ -283,7 +283,7 @@ func (c *client) Dir(ctx context.Context, u *model.User, r *model.Repo, b *model
for i := 0; i < len(data); i++ { for i := 0; i < len(data); i++ {
select { select {
case err := <-errc: case err := <-errChan:
return nil, err return nil, err
case fileMeta := <-fc: case fileMeta := <-fc:
files = append(files, fileMeta) files = append(files, fileMeta)
@ -291,7 +291,7 @@ func (c *client) Dir(ctx context.Context, u *model.User, r *model.Repo, b *model
} }
close(fc) close(fc)
close(errc) close(errChan)
return files, nil return files, nil
} }
@ -474,8 +474,8 @@ func matchingEmail(emails []*github.UserEmail, rawURL string) *github.UserEmail
} }
// matchingHooks returns matching hook. // matchingHooks returns matching hook.
func matchingHooks(hooks []*github.Hook, rawurl string) *github.Hook { func matchingHooks(hooks []*github.Hook, rawURL string) *github.Hook {
link, err := url.Parse(rawurl) link, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil return nil
} }

View file

@ -197,7 +197,7 @@ func parseReleaseHook(hook *github.ReleaseEvent) (*model.Repo, *model.Pipeline)
Event: model.EventRelease, Event: model.EventRelease,
ForgeURL: hook.GetRelease().GetHTMLURL(), ForgeURL: hook.GetRelease().GetHTMLURL(),
Ref: fmt.Sprintf("refs/tags/%s", hook.GetRelease().GetTagName()), Ref: fmt.Sprintf("refs/tags/%s", hook.GetRelease().GetTagName()),
Branch: hook.GetRelease().GetTargetCommitish(), Branch: hook.GetRelease().GetTargetCommitish(), // cspell:disable-line
Message: fmt.Sprintf("created release %s", name), Message: fmt.Sprintf("created release %s", name),
Author: hook.GetRelease().GetAuthor().GetLogin(), Author: hook.GetRelease().GetAuthor().GetLogin(),
Avatar: hook.GetRelease().GetAuthor().GetAvatarURL(), Avatar: hook.GetRelease().GetAuthor().GetAvatarURL(),

View file

@ -19,7 +19,7 @@ import (
"encoding/json" "encoding/json"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto" prometheus_auto "github.com/prometheus/client_golang/prometheus/promauto"
"go.woodpecker-ci.org/woodpecker/v2/pipeline/rpc" "go.woodpecker-ci.org/woodpecker/v2/pipeline/rpc"
"go.woodpecker-ci.org/woodpecker/v2/pipeline/rpc/proto" "go.woodpecker-ci.org/woodpecker/v2/pipeline/rpc/proto"
@ -37,12 +37,12 @@ type WoodpeckerServer struct {
} }
func NewWoodpeckerServer(queue queue.Queue, logger logging.Log, pubsub *pubsub.Publisher, store store.Store) proto.WoodpeckerServer { func NewWoodpeckerServer(queue queue.Queue, logger logging.Log, pubsub *pubsub.Publisher, store store.Store) proto.WoodpeckerServer {
pipelineTime := promauto.NewGaugeVec(prometheus.GaugeOpts{ pipelineTime := prometheus_auto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "pipeline_time", Name: "pipeline_time",
Help: "Pipeline time.", Help: "Pipeline time.",
}, []string{"repo", "branch", "status", "pipeline"}) }, []string{"repo", "branch", "status", "pipeline"})
pipelineCount := promauto.NewCounterVec(prometheus.CounterOpts{ pipelineCount := prometheus_auto.NewCounterVec(prometheus.CounterOpts{
Namespace: "woodpecker", Namespace: "woodpecker",
Name: "pipeline_count", Name: "pipeline_count",
Help: "Pipeline count.", Help: "Pipeline count.",

View file

@ -97,9 +97,9 @@ func createPipelineItems(c context.Context, forge forge.Forge, store store.Store
) (*model.Pipeline, []*stepbuilder.Item, error) { ) (*model.Pipeline, []*stepbuilder.Item, error) {
pipelineItems, err := parsePipeline(forge, store, currentPipeline, user, repo, yamls, envs) pipelineItems, err := parsePipeline(forge, store, currentPipeline, user, repo, yamls, envs)
if pipeline_errors.HasBlockingErrors(err) { if pipeline_errors.HasBlockingErrors(err) {
currentPipeline, uerr := UpdateToStatusError(store, *currentPipeline, err) currentPipeline, uErr := UpdateToStatusError(store, *currentPipeline, err)
if uerr != nil { if uErr != nil {
log.Error().Err(uerr).Msgf("error setting error status of pipeline for %s#%d", repo.FullName, currentPipeline.Number) log.Error().Err(uErr).Msgf("error setting error status of pipeline for %s#%d", repo.FullName, currentPipeline.Number)
} else { } else {
updatePipelineStatus(c, forge, currentPipeline, repo, user) updatePipelineStatus(c, forge, currentPipeline, repo, user)
} }

View file

@ -74,9 +74,9 @@ func Restart(ctx context.Context, store store.Store, lastPipeline *model.Pipelin
} }
if len(configs) == 0 { if len(configs) == 0 {
newPipeline, uerr := UpdateToStatusError(store, *newPipeline, errors.New("pipeline definition not found")) newPipeline, uErr := UpdateToStatusError(store, *newPipeline, errors.New("pipeline definition not found"))
if uerr != nil { if uErr != nil {
log.Debug().Err(uerr).Msg("failure to update pipeline status") log.Debug().Err(uErr).Msg("failure to update pipeline status")
} else { } else {
updatePipelineStatus(ctx, forge, newPipeline, repo, user) updatePipelineStatus(ctx, forge, newPipeline, repo, user)
} }

View file

@ -18,7 +18,7 @@ import (
"context" "context"
"crypto" "crypto"
"fmt" "fmt"
nethttp "net/http" net_http "net/http"
"go.woodpecker-ci.org/woodpecker/v2/server/forge" "go.woodpecker-ci.org/woodpecker/v2/server/forge"
"go.woodpecker-ci.org/woodpecker/v2/server/forge/types" "go.woodpecker-ci.org/woodpecker/v2/server/forge/types"
@ -76,7 +76,7 @@ func (h *http) Fetch(ctx context.Context, forge forge.Forge, user *model.User, r
return nil, fmt.Errorf("failed to fetch config via http (%d) %w", status, err) return nil, fmt.Errorf("failed to fetch config via http (%d) %w", status, err)
} }
if status != nethttp.StatusOK { if status != net_http.StatusOK {
return oldConfigData, nil return oldConfigData, nil
} }

View file

@ -36,10 +36,10 @@ func (svc *aesEncryptionService) Encrypt(plaintext, associatedData string) (stri
msg := []byte(plaintext) msg := []byte(plaintext)
aad := []byte(associatedData) aad := []byte(associatedData)
nonce := random.GetRandomBytes(uint32(AESGCMSIVNonceSize)) nonce := random.GetRandomBytes(uint32(AES_GCM_SIV_NonceSize))
ciphertext := svc.cipher.Seal(nil, nonce, msg, aad) ciphertext := svc.cipher.Seal(nil, nonce, msg, aad)
result := make([]byte, 0, AESGCMSIVNonceSize+len(ciphertext)) result := make([]byte, 0, AES_GCM_SIV_NonceSize+len(ciphertext))
result = append(result, nonce...) result = append(result, nonce...)
result = append(result, ciphertext...) result = append(result, ciphertext...)
@ -52,8 +52,8 @@ func (svc *aesEncryptionService) Decrypt(ciphertext, associatedData string) (str
return "", fmt.Errorf(errTemplateBase64DecryptionFailed, err) return "", fmt.Errorf(errTemplateBase64DecryptionFailed, err)
} }
nonce := bytes[:AESGCMSIVNonceSize] nonce := bytes[:AES_GCM_SIV_NonceSize]
message := bytes[AESGCMSIVNonceSize:] message := bytes[AES_GCM_SIV_NonceSize:]
plaintext, err := svc.cipher.Open(nil, nonce, message, []byte(associatedData)) plaintext, err := svc.cipher.Open(nil, nonce, message, []byte(associatedData))
if err != nil { if err != nil {

View file

@ -28,8 +28,8 @@ const (
keyTypeRaw = "raw" keyTypeRaw = "raw"
keyTypeNone = "none" keyTypeNone = "none"
keyIDAssociatedData = "Primary key id" keyIDAssociatedData = "Primary key id"
AESGCMSIVNonceSize = 12 AES_GCM_SIV_NonceSize = 12 //nolint:revive,stylecheck
) )
var ( var (

View file

@ -21,7 +21,7 @@ import (
"strconv" "strconv"
"github.com/google/tink/go/aead" "github.com/google/tink/go/aead"
"github.com/google/tink/go/insecurecleartextkeyset" insecure_clear_text_keyset "github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset" "github.com/google/tink/go/keyset"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -42,7 +42,7 @@ func (svc *tinkEncryptionService) loadKeyset() error {
}(file) }(file)
jsonKeyset := keyset.NewJSONReader(file) jsonKeyset := keyset.NewJSONReader(file)
keysetHandle, err := insecurecleartextkeyset.Read(jsonKeyset) keysetHandle, err := insecure_clear_text_keyset.Read(jsonKeyset)
if err != nil { if err != nil {
return fmt.Errorf(errTemplateTinkFailedReadingKeyset, err) return fmt.Errorf(errTemplateTinkFailedReadingKeyset, err)
} }

View file

@ -21,7 +21,7 @@ import (
"os" "os"
"strings" "strings"
"github.com/docker/cli/cli/config/configfile" config_file "github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types" "github.com/docker/cli/cli/config/types"
"go.woodpecker-ci.org/woodpecker/v2/server/model" "go.woodpecker-ci.org/woodpecker/v2/server/model"
@ -46,7 +46,7 @@ func parseDockerConfig(path string) ([]*model.Registry, error) {
} }
defer f.Close() defer f.Close()
configFile := configfile.ConfigFile{ configFile := config_file.ConfigFile{
AuthConfigs: make(map[string]types.AuthConfig), AuthConfigs: make(map[string]types.AuthConfig),
} }
@ -73,16 +73,16 @@ func parseDockerConfig(path string) ([]*model.Registry, error) {
} }
} }
var auths []*model.Registry var registries []*model.Registry
for key, auth := range configFile.AuthConfigs { for key, auth := range configFile.AuthConfigs {
auths = append(auths, &model.Registry{ registries = append(registries, &model.Registry{
Address: key, Address: key,
Username: auth.Username, Username: auth.Username,
Password: auth.Password, Password: auth.Password,
}) })
} }
return auths, nil return registries, nil
} }
func (f *filesystem) RegistryFind(*model.Repo, string) (*model.Registry, error) { func (f *filesystem) RegistryFind(*model.Repo, string) (*model.Registry, error) {

View file

@ -80,28 +80,28 @@ func (c *client) SetLogLevel(in *LogLevel) (*LogLevel, error) {
// //
// Helper function for making an http GET request. // Helper function for making an http GET request.
func (c *client) get(rawurl string, out any) error { func (c *client) get(rawURL string, out any) error {
return c.do(rawurl, http.MethodGet, nil, out) return c.do(rawURL, http.MethodGet, nil, out)
} }
// Helper function for making an http POST request. // Helper function for making an http POST request.
func (c *client) post(rawurl string, in, out any) error { func (c *client) post(rawURL string, in, out any) error {
return c.do(rawurl, http.MethodPost, in, out) return c.do(rawURL, http.MethodPost, in, out)
} }
// Helper function for making an http PATCH request. // Helper function for making an http PATCH request.
func (c *client) patch(rawurl string, in, out any) error { func (c *client) patch(rawURL string, in, out any) error {
return c.do(rawurl, http.MethodPatch, in, out) return c.do(rawURL, http.MethodPatch, in, out)
} }
// Helper function for making an http DELETE request. // Helper function for making an http DELETE request.
func (c *client) delete(rawurl string) error { func (c *client) delete(rawURL string) error {
return c.do(rawurl, http.MethodDelete, nil, nil) return c.do(rawURL, http.MethodDelete, nil, nil)
} }
// Helper function to make an http request. // Helper function to make an http request.
func (c *client) do(rawurl, method string, in, out any) error { func (c *client) do(rawURL, method string, in, out any) error {
body, err := c.open(rawurl, method, in) body, err := c.open(rawURL, method, in)
if err != nil { if err != nil {
return err return err
} }
@ -113,8 +113,8 @@ func (c *client) do(rawurl, method string, in, out any) error {
} }
// Helper function to open an http request. // Helper function to open an http request.
func (c *client) open(rawurl, method string, in any) (io.ReadCloser, error) { func (c *client) open(rawURL, method string, in any) (io.ReadCloser, error) {
uri, err := url.Parse(rawurl) uri, err := url.Parse(rawURL)
if err != nil { if err != nil {
return nil, err return nil, err
} }