Detailed changes
@@ -30,6 +30,10 @@ linters:
- text: '(slog|log)\.\w+'
linters:
- noctx
+ - text: 'var-naming: avoid meaningless package names'
+ linters:
+ - revive
+ path: 'pkg/ui/common/'
generated: lax
presets:
- common-false-positives
@@ -1,3 +1,4 @@
+// Package cmd provides common command functionality for soft-serve.
package cmd
import (
@@ -21,7 +22,7 @@ func InitBackendContext(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
cfg := config.FromContext(ctx)
if _, err := os.Stat(cfg.DataPath); errors.Is(err, fs.ErrNotExist) {
- if err := os.MkdirAll(cfg.DataPath, os.ModePerm); err != nil {
+ if err := os.MkdirAll(cfg.DataPath, os.ModePerm); err != nil { //nolint:gosec
return fmt.Errorf("create data directory: %w", err)
}
}
@@ -58,12 +59,12 @@ func CloseDBContext(cmd *cobra.Command, _ []string) error {
func InitializeHooks(ctx context.Context, cfg *config.Config, be *backend.Backend) error {
repos, err := be.Repositories(ctx)
if err != nil {
- return err
+ return fmt.Errorf("failed to get repositories: %w", err)
}
for _, repo := range repos {
if err := hooks.GenerateHooks(ctx, cfg, repo.Name()); err != nil {
- return err
+ return fmt.Errorf("failed to generate hooks for repo %s: %w", repo.Name(), err)
}
}
@@ -1,3 +1,4 @@
+// Package admin provides administrative commands for soft-serve.
package admin
import (
@@ -1,3 +1,4 @@
+// Package browse provides the browse command for soft-serve.
package browse
import (
@@ -29,7 +30,7 @@ var Command = &cobra.Command{
abs, err := filepath.Abs(rp)
if err != nil {
- return err
+ return fmt.Errorf("failed to get absolute path for %s: %w", rp, err)
}
r, err := git.Open(abs)
@@ -64,7 +65,7 @@ var Command = &cobra.Command{
)
_, err = p.Run()
- return err
+ return err //nolint:wrapcheck
},
}
@@ -102,7 +103,7 @@ func (m *model) SetSize(w, h int) {
// ShortHelp implements help.KeyMap.
func (m model) ShortHelp() []key.Binding {
- switch m.state {
+ switch m.state { //nolint:exhaustive
case errorState:
return []key.Binding{
m.common.KeyMap.Back,
@@ -116,7 +117,7 @@ func (m model) ShortHelp() []key.Binding {
// FullHelp implements help.KeyMap.
func (m model) FullHelp() [][]key.Binding {
- switch m.state {
+ switch m.state { //nolint:exhaustive
case errorState:
return [][]key.Binding{
{
@@ -1,3 +1,4 @@
+// Package hook provides git hook commands for soft-serve.
package hook
import (
@@ -168,5 +169,5 @@ func runCommand(ctx context.Context, in io.Reader, out io.Writer, err io.Writer,
cmd.Stdin = in
cmd.Stdout = out
cmd.Stderr = err
- return cmd.Run()
+ return cmd.Run() //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package main is the entry point for the soft-serve CLI.
package main
import (
@@ -54,7 +55,7 @@ var (
RunE: func(_ *cobra.Command, _ []string) error {
manPage, err := mcobra.NewManPage(1, rootCmd) //.
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
manPage = manPage.WithSection("Copyright", "(C) 2021-2023 Charmbracelet, Inc.\n"+
@@ -118,7 +119,7 @@ func main() {
ctx = log.WithContext(ctx, logger)
if f != nil {
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint: errcheck
}
// Set global logger
@@ -1,3 +1,4 @@
+// Package serve provides the serve command for soft-serve.
package serve
import (
@@ -50,10 +51,10 @@ var (
// Create custom hooks directory if it doesn't exist
customHooksPath := filepath.Join(cfg.DataPath, "hooks")
if _, err := os.Stat(customHooksPath); err != nil && os.IsNotExist(err) {
- os.MkdirAll(customHooksPath, os.ModePerm) // nolint: errcheck
+ os.MkdirAll(customHooksPath, os.ModePerm) //nolint:errcheck,gosec
// Generate update hook example without executable permissions
hookPath := filepath.Join(customHooksPath, "update.sample")
- // nolint: gosec
+ //nolint: gosec
if err := os.WriteFile(hookPath, []byte(updateHookExample), 0o744); err != nil {
return fmt.Errorf("failed to generate update hook example: %w", err)
}
@@ -62,7 +63,7 @@ var (
// Create log directory if it doesn't exist
logPath := filepath.Join(cfg.DataPath, "log")
if _, err := os.Stat(logPath); err != nil && os.IsNotExist(err) {
- os.MkdirAll(logPath, os.ModePerm) // nolint: errcheck
+ os.MkdirAll(logPath, os.ModePerm) //nolint:errcheck,gosec
}
db := db.FromContext(ctx)
@@ -99,7 +99,7 @@ func (s *Server) Start() error {
errg.Go(func() error {
s.logger.Print("Starting SSH server", "addr", s.Config.SSH.ListenAddr)
if err := s.SSHServer.ListenAndServe(); !errors.Is(err, ssh.ErrServerClosed) {
- return err
+ return err //nolint:wrapcheck
}
return nil
})
@@ -110,7 +110,7 @@ func (s *Server) Start() error {
errg.Go(func() error {
s.logger.Print("Starting Git daemon", "addr", s.Config.Git.ListenAddr)
if err := s.GitDaemon.ListenAndServe(); !errors.Is(err, daemon.ErrServerClosed) {
- return err
+ return err //nolint:wrapcheck
}
return nil
})
@@ -121,7 +121,7 @@ func (s *Server) Start() error {
errg.Go(func() error {
s.logger.Print("Starting HTTP server", "addr", s.Config.HTTP.ListenAddr)
if err := s.HTTPServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
- return err
+ return err //nolint:wrapcheck
}
return nil
})
@@ -132,7 +132,7 @@ func (s *Server) Start() error {
errg.Go(func() error {
s.logger.Print("Starting Stats server", "addr", s.Config.Stats.ListenAddr)
if err := s.StatsServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
- return err
+ return err //nolint:wrapcheck
}
return nil
})
@@ -142,7 +142,7 @@ func (s *Server) Start() error {
s.Cron.Start()
return nil
})
- return errg.Wait()
+ return errg.Wait() //nolint:wrapcheck
}
// Shutdown lets the server gracefully shutdown.
@@ -168,7 +168,7 @@ func (s *Server) Shutdown(ctx context.Context) error {
return nil
})
// defer s.DB.Close() // nolint: errcheck
- return errg.Wait()
+ return errg.Wait() //nolint:wrapcheck
}
// Close closes the SSH server.
@@ -183,5 +183,5 @@ func (s *Server) Close() error {
return nil
})
// defer s.DB.Close() // nolint: errcheck
- return errg.Wait()
+ return errg.Wait() //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package git provides git repository operations and utilities.
package git
import (
@@ -18,22 +19,22 @@ type Attribute struct {
// CheckAttributes checks the attributes of the given ref and path.
func (r *Repository) CheckAttributes(ref *Reference, path string) ([]Attribute, error) {
rnd := rand.NewSource(time.Now().UnixNano())
- fn := "soft-serve-index-" + strconv.Itoa(rand.New(rnd).Int()) // nolint: gosec
+ fn := "soft-serve-index-" + strconv.Itoa(rand.New(rnd).Int()) //nolint: gosec
tmpindex := filepath.Join(os.TempDir(), fn)
- defer os.Remove(tmpindex) // nolint: errcheck
+ defer os.Remove(tmpindex) //nolint: errcheck
readTree := NewCommand("read-tree", "--reset", "-i", ref.Name().String()).
AddEnvs("GIT_INDEX_FILE=" + tmpindex)
if _, err := readTree.RunInDir(r.Path); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
checkAttr := NewCommand("check-attr", "--cached", "-a", "--", path).
AddEnvs("GIT_INDEX_FILE=" + tmpindex)
out, err := checkAttr.RunInDir(r.Path)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return parseAttributes(path, out), nil
@@ -12,14 +12,14 @@ func (r *Repository) Config() (*gcfg.Config, error) {
cp := filepath.Join(r.Path, "config")
f, err := os.Open(cp)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint: errcheck
d := gcfg.NewDecoder(f)
cfg := gcfg.New()
if err := d.Decode(cfg); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return cfg, nil
@@ -30,10 +30,10 @@ func (r *Repository) SetConfig(cfg *gcfg.Config) error {
cp := filepath.Join(r.Path, "config")
f, err := os.Create(cp)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint: errcheck
e := gcfg.NewEncoder(f)
- return e.Encode(cfg)
+ return e.Encode(cfg) //nolint:wrapcheck
}
@@ -26,7 +26,7 @@ func (s *DiffSection) diffFor(line *git.DiffLine) string {
// Find equivalent diff line, ignore when not found.
var diff1, diff2 string
- switch line.Type {
+ switch line.Type { //nolint:exhaustive
case git.DiffLineAdd:
compareLine := s.Line(git.DiffLineDelete, line.RightLine)
if compareLine == nil {
@@ -64,7 +64,7 @@ func diffsToString(diffs []diffmatchpatch.Diff, lineType git.DiffLineType) strin
buf := bytes.NewBuffer(nil)
// Reproduce signs which are cutted for inline diff before.
- switch lineType {
+ switch lineType { //nolint:exhaustive
case git.DiffLineAdd:
buf.WriteByte('+')
case git.DiffLineDelete:
@@ -132,7 +132,7 @@ func (f *DiffFile) Files() (from *DiffFileChange, to *DiffFileChange) {
return
}
-// FileStats
+// FileStats represents a collection of diff files.
type FileStats []*DiffFile
// String returns a string representation of file stats.
@@ -233,7 +233,7 @@ type Diff struct {
Files []*DiffFile
}
-// FileStats returns the diff file stats.
+// Stats returns the diff file stats.
func (d *Diff) Stats() FileStats {
return d.Files
}
@@ -8,7 +8,7 @@ import (
)
var (
- // DiffMaxFile is the maximum number of files to show in a diff.
+ // DiffMaxFiles is the maximum number of files to show in a diff.
DiffMaxFiles = 1000
// DiffMaxFileLines is the maximum number of lines to show in a file diff.
DiffMaxFileLines = 1000
@@ -25,7 +25,7 @@ type Repository struct {
// Clone clones a repository.
func Clone(src, dst string, opts ...git.CloneOptions) error {
- return git.Clone(src, dst, opts...)
+ return git.Clone(src, dst, opts...) //nolint:wrapcheck
}
// Init initializes and opens a new git repository.
@@ -36,20 +36,20 @@ func Init(path string, bare bool) (*Repository, error) {
err := git.Init(path, git.InitOptions{Bare: bare})
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return Open(path)
}
func gitDir(r *git.Repository) (string, error) {
- return r.RevParse("--git-dir")
+ return r.RevParse("--git-dir") //nolint:wrapcheck
}
// Open opens a git repository at the given path.
func Open(path string) (*Repository, error) {
repo, err := git.Open(path)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
gp, err := gitDir(repo)
if err != nil || (gp != "." && gp != ".git") {
@@ -66,11 +66,11 @@ func Open(path string) (*Repository, error) {
func (r *Repository) HEAD() (*Reference, error) {
rn, err := r.Repository.SymbolicRef(git.SymbolicRefOptions{Name: "HEAD"})
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
hash, err := r.ShowRefVerify(rn)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &Reference{
Reference: &git.Reference{
@@ -85,7 +85,7 @@ func (r *Repository) HEAD() (*Reference, error) {
func (r *Repository) References() ([]*Reference, error) {
refs, err := r.ShowRef()
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
rrefs := make([]*Reference, 0, len(refs))
for _, ref := range refs {
@@ -101,7 +101,7 @@ func (r *Repository) References() ([]*Reference, error) {
func (r *Repository) LsTree(ref string) (*Tree, error) {
tree, err := r.Repository.LsTree(ref)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &Tree{
Tree: tree,
@@ -146,7 +146,7 @@ func (r *Repository) Diff(commit *Commit) (*Diff, error) {
},
})
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return toDiff(diff), nil
}
@@ -162,14 +162,14 @@ func (r *Repository) Patch(commit *Commit) (string, error) {
// CountCommits returns the number of commits in the repository.
func (r *Repository) CountCommits(ref *Reference) (int64, error) {
- return r.RevListCount([]string{ref.Name().String()})
+ return r.RevListCount([]string{ref.Name().String()}) //nolint:wrapcheck
}
// CommitsByPage returns the commits for a given page and size.
func (r *Repository) CommitsByPage(ref *Reference, page, size int) (Commits, error) {
cs, err := r.Repository.CommitsByPage(ref.Name().String(), page, size)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
commits := make(Commits, len(cs))
copy(commits, cs)
@@ -186,5 +186,5 @@ func (r *Repository) SymbolicRef(name string, ref string, opts ...git.SymbolicRe
opt.Name = name
opt.Ref = ref
- return r.Repository.SymbolicRef(opt)
+ return r.Repository.SymbolicRef(opt) //nolint:wrapcheck
}
@@ -14,5 +14,5 @@ func UpdateServerInfo(ctx context.Context, path string) error {
cmd := git.NewCommand("update-server-info").WithContext(ctx).WithTimeout(-1)
_, err := cmd.RunInDir(path)
- return err
+ return err //nolint:wrapcheck
}
@@ -10,7 +10,7 @@ func (r *Repository) StashDiff(index int) (*Diff, error) {
},
})
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return toDiff(diff), nil
}
@@ -84,7 +84,7 @@ func (f *File) Path() string {
func (t *Tree) SubTree(path string) (*Tree, error) {
tree, err := t.Subtree(path)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &Tree{
Tree: tree,
@@ -97,7 +97,7 @@ func (t *Tree) SubTree(path string) (*Tree, error) {
func (t *Tree) Entries() (Entries, error) {
entries, err := t.Tree.Entries()
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
ret := make(Entries, len(entries))
for i, e := range entries {
@@ -113,7 +113,7 @@ func (t *Tree) Entries() (Entries, error) {
func (t *Tree) TreeEntry(path string) (*TreeEntry, error) {
entry, err := t.Tree.TreeEntry(path)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &TreeEntry{
TreeEntry: entry,
@@ -128,17 +128,13 @@ const sniffLen = 8000
func IsBinary(r io.Reader) (bool, error) {
reader := bufio.NewReader(r)
c := 0
- for {
- if c == sniffLen {
- break
- }
-
+ for c != sniffLen {
b, err := reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
- return false, err
+ return false, err //nolint:wrapcheck
}
if b == byte(0) {
@@ -157,7 +153,7 @@ func (f *File) IsBinary() (bool, error) {
stderr := new(bytes.Buffer)
err := f.Pipeline(stdout, stderr)
if err != nil {
- return false, err
+ return false, err //nolint:wrapcheck
}
r := bufio.NewReader(stdout)
return IsBinary(r)
@@ -166,7 +162,7 @@ func (f *File) IsBinary() (bool, error) {
// Mode returns the mode of the file in fs.FileMode format.
func (e *TreeEntry) Mode() fs.FileMode {
m := e.Blob().Mode()
- switch m {
+ switch m { //nolint:exhaustive
case git.EntryTree:
return fs.ModeDir | fs.ModePerm
default:
@@ -190,5 +186,5 @@ func (e *TreeEntry) Contents() ([]byte, error) {
// Contents returns the contents of the file.
func (f *File) Contents() ([]byte, error) {
- return f.Blob.Bytes()
+ return f.Bytes() //nolint:wrapcheck
}
@@ -32,7 +32,7 @@ func LatestFile(repo *Repository, ref *Reference, pattern string) (string, strin
if te.IsTree() {
continue
}
- if g.Match(fp) {
+ if g.Match(fp) { //nolint:nestif
if te.IsSymlink() {
bts, err := te.Contents()
if err != nil {
@@ -1,3 +1,4 @@
+// Package access provides access control functionality.
package access
import (
@@ -6,7 +7,7 @@ import (
)
// AccessLevel is the level of access allowed to a repo.
-type AccessLevel int // nolint: revive
+type AccessLevel int //nolint: revive
const (
// NoAccess does not allow access to the repo.
@@ -1,3 +1,4 @@
+// Package backend provides backend functionality for soft-serve.
package backend
import (
@@ -22,7 +23,7 @@ func (b *Backend) CreateAccessToken(ctx context.Context, user proto.User, name s
return nil
}); err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return token, nil
@@ -45,7 +46,7 @@ func (b *Backend) DeleteAccessToken(ctx context.Context, user proto.User, id int
if errors.Is(err, db.ErrRecordNotFound) {
return proto.ErrTokenNotFound
}
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -55,10 +56,10 @@ func (b *Backend) DeleteAccessToken(ctx context.Context, user proto.User, id int
func (b *Backend) ListAccessTokens(ctx context.Context, user proto.User) ([]proto.AccessToken, error) {
accessTokens, err := b.store.GetAccessTokensByUserID(ctx, b.db, user.ID())
if err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
- var tokens []proto.AccessToken
+ tokens := make([]proto.AccessToken, 0, len(accessTokens))
for _, t := range accessTokens {
token := proto.AccessToken{
ID: t.ID,
@@ -15,7 +15,7 @@ const saltySalt = "salty-soft-serve"
func HashPassword(password string) (string, error) {
crypt, err := bcrypt.GenerateFromPassword([]byte(password+saltySalt), bcrypt.DefaultCost)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return string(crypt), nil
@@ -19,7 +19,7 @@ import (
func (d *Backend) AddCollaborator(ctx context.Context, repo string, username string, level access.AccessLevel) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
repo = utils.SanitizeRepo(repo)
@@ -37,15 +37,15 @@ func (d *Backend) AddCollaborator(ctx context.Context, repo string, username str
return proto.ErrCollaboratorExist
}
- return err
+ return err //nolint:wrapcheck
}
wh, err := webhook.NewCollaboratorEvent(ctx, proto.UserFromContext(ctx), r, username, webhook.CollaboratorEventAdded)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return webhook.SendEvent(ctx, wh)
+ return webhook.SendEvent(ctx, wh) //nolint:wrapcheck
}
// Collaborators returns a list of collaborators for a repository.
@@ -57,12 +57,12 @@ func (d *Backend) Collaborators(ctx context.Context, repo string) ([]string, err
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
users, err = d.store.ListCollabsByRepoAsUsers(ctx, tx, repo)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
- var usernames []string
+ usernames := make([]string, 0, len(users))
for _, u := range users {
usernames = append(usernames, u.Username)
}
@@ -83,9 +83,9 @@ func (d *Backend) IsCollaborator(ctx context.Context, repo string, username stri
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
m, err = d.store.GetCollabByUsernameAndRepo(ctx, tx, username, repo)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return -1, false, db.WrapError(err)
+ return -1, false, db.WrapError(err) //nolint:wrapcheck
}
return m.AccessLevel, m.ID > 0, nil
@@ -103,7 +103,7 @@ func (d *Backend) RemoveCollaborator(ctx context.Context, repo string, username
wh, err := webhook.NewCollaboratorEvent(ctx, proto.UserFromContext(ctx), r, username, webhook.CollaboratorEventRemoved)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := db.WrapError(
@@ -115,8 +115,8 @@ func (d *Backend) RemoveCollaborator(ctx context.Context, repo string, username
return proto.ErrCollaboratorNotFound
}
- return err
+ return err //nolint:wrapcheck
}
- return webhook.SendEvent(ctx, wh)
+ return webhook.SendEvent(ctx, wh) //nolint:wrapcheck
}
@@ -37,7 +37,7 @@ func (d *Backend) Update(ctx context.Context, _ io.Writer, _ io.Writer, repo str
// Find user
var user proto.User
- if pubkey := os.Getenv("SOFT_SERVE_PUBLIC_KEY"); pubkey != "" {
+ if pubkey := os.Getenv("SOFT_SERVE_PUBLIC_KEY"); pubkey != "" { //nolint:nestif
pk, _, err := sshutils.ParseAuthorizedKey(pubkey)
if err != nil {
d.logger.Error("error parsing public key", "err", err)
@@ -127,7 +127,7 @@ func populateLastModified(ctx context.Context, d *Backend, name string) error {
c, err := r.LatestCommitTime()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return rr.writeLastModified(c)
@@ -28,7 +28,7 @@ func StoreRepoMissingLFSObjects(ctx context.Context, repo proto.Repository, dbx
errChan := make(chan error, 1)
r, err := repo.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
go lfs.SearchPointerBlobs(ctx, r, pointerChan, errChan)
@@ -39,14 +39,14 @@ func StoreRepoMissingLFSObjects(ctx context.Context, repo proto.Repository, dbx
return objectError
}
- defer content.Close() // nolint: errcheck
+ defer content.Close() //nolint: errcheck
return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
if err := store.CreateLFSObject(ctx, tx, repo.ID(), p.Oid, p.Size); err != nil {
return db.WrapError(err)
}
_, err := strg.Put(path.Join("objects", p.RelativePath()), content)
- return err
+ return err //nolint:wrapcheck
})
})
}
@@ -55,17 +55,17 @@ func StoreRepoMissingLFSObjects(ctx context.Context, repo proto.Repository, dbx
for pointer := range pointerChan {
obj, err := store.GetLFSObjectByOid(ctx, dbx, repo.ID(), pointer.Oid)
if err != nil && !errors.Is(err, db.ErrRecordNotFound) {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
exist, err := strg.Exists(path.Join("objects", pointer.RelativePath()))
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- if exist && obj.ID == 0 {
+ if exist && obj.ID == 0 { //nolint:nestif
if err := store.CreateLFSObject(ctx, dbx, repo.ID(), pointer.Oid, pointer.Size); err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
} else {
batch = append(batch, pointer.Pointer)
@@ -31,7 +31,7 @@ import (
func (d *Backend) CreateRepository(ctx context.Context, name string, user proto.User, opts proto.RepositoryOptions) (proto.Repository, error) {
name = utils.SanitizeRepo(name)
if err := utils.ValidateRepo(name); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
rp := filepath.Join(d.repoPath(name))
@@ -53,24 +53,24 @@ func (d *Backend) CreateRepository(ctx context.Context, name string, user proto.
opts.Hidden,
opts.Mirror,
); err != nil {
- return err
+ return err //nolint:wrapcheck
}
_, err := git.Init(rp, true)
if err != nil {
d.logger.Debug("failed to create repository", "err", err)
- return err
+ return err //nolint:wrapcheck
}
if err := os.WriteFile(filepath.Join(rp, "description"), []byte(opts.Description), fs.ModePerm); err != nil {
d.logger.Error("failed to write description", "repo", name, "err", err)
- return err
+ return err //nolint:wrapcheck
}
if !opts.Private {
if err := os.WriteFile(filepath.Join(rp, "git-daemon-export-ok"), []byte{}, fs.ModePerm); err != nil {
d.logger.Error("failed to write git-daemon-export-ok", "repo", name, "err", err)
- return err
+ return err //nolint:wrapcheck
}
}
@@ -82,7 +82,7 @@ func (d *Backend) CreateRepository(ctx context.Context, name string, user proto.
return nil, proto.ErrRepoExist
}
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return d.Repository(ctx, name)
@@ -93,7 +93,7 @@ func (d *Backend) CreateRepository(ctx context.Context, name string, user proto.
func (d *Backend) ImportRepository(_ context.Context, name string, user proto.User, remote string, opts proto.RepositoryOptions) (proto.Repository, error) {
name = utils.SanitizeRepo(name)
if err := utils.ValidateRepo(name); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
rp := filepath.Join(d.repoPath(name))
@@ -156,7 +156,7 @@ func (d *Backend) ImportRepository(_ context.Context, name string, user proto.Us
rr, err := r.Open()
if err != nil {
d.logger.Error("failed to open repository", "err", err, "path", rp)
- return err
+ return err //nolint:wrapcheck
}
repoc <- r
@@ -164,7 +164,7 @@ func (d *Backend) ImportRepository(_ context.Context, name string, user proto.Us
rcfg, err := rr.Config()
if err != nil {
d.logger.Error("failed to get repository config", "err", err, "path", rp)
- return err
+ return err //nolint:wrapcheck
}
endpoint := remote
@@ -176,13 +176,13 @@ func (d *Backend) ImportRepository(_ context.Context, name string, user proto.Us
if err := rr.SetConfig(rcfg); err != nil {
d.logger.Error("failed to set repository config", "err", err, "path", rp)
- return err
+ return err //nolint:wrapcheck
}
ep, err := lfs.NewEndpoint(endpoint)
if err != nil {
d.logger.Error("failed to create lfs endpoint", "err", err, "path", rp)
- return err
+ return err //nolint:wrapcheck
}
client := lfs.NewClient(ep)
@@ -224,7 +224,7 @@ func (d *Backend) DeleteRepository(ctx context.Context, name string) error {
// send the event after deleting the repository.
wh, err := webhook.NewRepositoryEvent(ctx, user, r, webhook.RepositoryEventActionDelete)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
@@ -273,10 +273,10 @@ func (d *Backend) DeleteRepository(ctx context.Context, name string) error {
return proto.ErrRepoNotFound
}
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
- return webhook.SendEvent(ctx, wh)
+ return webhook.SendEvent(ctx, wh) //nolint:wrapcheck
}
// DeleteUserRepositories deletes all user repositories.
@@ -284,12 +284,12 @@ func (d *Backend) DeleteUserRepositories(ctx context.Context, username string) e
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
user, err := d.store.FindUserByUsername(ctx, tx, username)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
repos, err := d.store.GetUserRepos(ctx, tx, user.ID)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, repo := range repos {
@@ -300,7 +300,7 @@ func (d *Backend) DeleteUserRepositories(ctx context.Context, username string) e
return nil
}); err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
return nil
@@ -312,12 +312,12 @@ func (d *Backend) DeleteUserRepositories(ctx context.Context, username string) e
func (d *Backend) RenameRepository(ctx context.Context, oldName string, newName string) error {
oldName = utils.SanitizeRepo(oldName)
if err := utils.ValidateRepo(oldName); err != nil {
- return err
+ return err //nolint:wrapcheck
}
newName = utils.SanitizeRepo(newName)
if err := utils.ValidateRepo(newName); err != nil {
- return err
+ return err //nolint:wrapcheck
}
if oldName == newName {
@@ -339,17 +339,17 @@ func (d *Backend) RenameRepository(ctx context.Context, oldName string, newName
defer d.cache.Delete(oldName)
if err := d.store.SetRepoNameByName(ctx, tx, oldName, newName); err != nil {
- return err
+ return err //nolint:wrapcheck
}
// Make sure the new repository parent directory exists.
- if err := os.MkdirAll(filepath.Dir(np), os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(filepath.Dir(np), os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
return os.Rename(op, np)
}); err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
user := proto.UserFromContext(ctx)
@@ -360,10 +360,10 @@ func (d *Backend) RenameRepository(ctx context.Context, oldName string, newName
wh, err := webhook.NewRepositoryEvent(ctx, user, repo, webhook.RepositoryEventActionRename)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return webhook.SendEvent(ctx, wh)
+ return webhook.SendEvent(ctx, wh) //nolint:wrapcheck
}
// Repositories returns a list of repositories per page.
@@ -375,7 +375,7 @@ func (d *Backend) Repositories(ctx context.Context) ([]proto.Repository, error)
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
ms, err := d.store.GetAllRepos(ctx, tx)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, m := range ms {
@@ -393,7 +393,7 @@ func (d *Backend) Repositories(ctx context.Context) ([]proto.Repository, error)
return nil
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
return repos, nil
@@ -426,7 +426,7 @@ func (d *Backend) Repository(ctx context.Context, name string) (proto.Repository
if errors.Is(err, db.ErrRecordNotFound) {
return nil, proto.ErrRepoNotFound
}
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
r := &repo{
@@ -450,9 +450,9 @@ func (d *Backend) Description(ctx context.Context, name string) (string, error)
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
desc, err = d.store.GetRepoDescriptionByName(ctx, tx, name)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return "", db.WrapError(err)
+ return "", db.WrapError(err) //nolint:wrapcheck
}
return desc, nil
@@ -467,9 +467,9 @@ func (d *Backend) IsMirror(ctx context.Context, name string) (bool, error) {
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
mirror, err = d.store.GetRepoIsMirrorByName(ctx, tx, name)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return false, db.WrapError(err)
+ return false, db.WrapError(err) //nolint:wrapcheck
}
return mirror, nil
}
@@ -483,9 +483,9 @@ func (d *Backend) IsPrivate(ctx context.Context, name string) (bool, error) {
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
private, err = d.store.GetRepoIsPrivateByName(ctx, tx, name)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return false, db.WrapError(err)
+ return false, db.WrapError(err) //nolint:wrapcheck
}
return private, nil
@@ -500,9 +500,9 @@ func (d *Backend) IsHidden(ctx context.Context, name string) (bool, error) {
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
hidden, err = d.store.GetRepoIsHiddenByName(ctx, tx, name)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return false, db.WrapError(err)
+ return false, db.WrapError(err) //nolint:wrapcheck
}
return hidden, nil
@@ -517,9 +517,9 @@ func (d *Backend) ProjectName(ctx context.Context, name string) (string, error)
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
pname, err = d.store.GetRepoProjectNameByName(ctx, tx, name)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return "", db.WrapError(err)
+ return "", db.WrapError(err) //nolint:wrapcheck
}
return pname, nil
@@ -534,7 +534,7 @@ func (d *Backend) SetHidden(ctx context.Context, name string, hidden bool) error
// Delete cache
d.cache.Delete(name)
- return db.WrapError(d.db.TransactionContext(ctx, func(tx *db.Tx) error {
+ return db.WrapError(d.db.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
return d.store.SetRepoIsHiddenByName(ctx, tx, name, hidden)
}))
}
@@ -549,10 +549,10 @@ func (d *Backend) SetDescription(ctx context.Context, name string, desc string)
// Delete cache
d.cache.Delete(name)
- return d.db.TransactionContext(ctx, func(tx *db.Tx) error {
+ return d.db.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
if err := os.WriteFile(filepath.Join(rp, "description"), []byte(desc), fs.ModePerm); err != nil {
d.logger.Error("failed to write description", "repo", name, "err", err)
- return err
+ return err //nolint:wrapcheck
}
return d.store.SetRepoDescriptionByName(ctx, tx, name, desc)
@@ -575,13 +575,13 @@ func (d *Backend) SetPrivate(ctx context.Context, name string, private bool) err
if !private {
if err := os.WriteFile(fp, []byte{}, fs.ModePerm); err != nil {
d.logger.Error("failed to write git-daemon-export-ok", "repo", name, "err", err)
- return err
+ return err //nolint:wrapcheck
}
} else {
if _, err := os.Stat(fp); err == nil {
if err := os.Remove(fp); err != nil {
d.logger.Error("failed to remove git-daemon-export-ok", "repo", name, "err", err)
- return err
+ return err //nolint:wrapcheck
}
}
}
@@ -589,7 +589,7 @@ func (d *Backend) SetPrivate(ctx context.Context, name string, private bool) err
return d.store.SetRepoIsPrivateByName(ctx, tx, name, private)
}),
); err != nil {
- return err
+ return err //nolint:wrapcheck
}
user := proto.UserFromContext(ctx)
@@ -601,11 +601,11 @@ func (d *Backend) SetPrivate(ctx context.Context, name string, private bool) err
if repo.IsPrivate() != !private {
wh, err := webhook.NewRepositoryEvent(ctx, user, repo, webhook.RepositoryEventActionVisibilityChange)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := webhook.SendEvent(ctx, wh); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -621,7 +621,7 @@ func (d *Backend) SetProjectName(ctx context.Context, repo string, name string)
// Delete cache
d.cache.Delete(repo)
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.SetRepoProjectNameByName(ctx, tx, repo, name)
}),
@@ -694,7 +694,7 @@ func (r *repo) Name() string {
//
// It implements backend.Repository.
func (r *repo) Open() (*git.Repository, error) {
- return git.Open(r.path)
+ return git.Open(r.path) //nolint:wrapcheck
}
// ProjectName returns the repository's project name.
@@ -738,20 +738,20 @@ func (r *repo) UpdatedAt() time.Time {
func (r *repo) writeLastModified(t time.Time) error {
fp := filepath.Join(r.path, "info", "last-modified")
- if err := os.MkdirAll(filepath.Dir(fp), os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(filepath.Dir(fp), os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
- return os.WriteFile(fp, []byte(t.Format(time.RFC3339)), os.ModePerm) //nolint:gosec
+ return os.WriteFile(fp, []byte(t.Format(time.RFC3339)), os.ModePerm) //nolint:gosec,wrapcheck
}
func readOneline(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint: errcheck
s := bufio.NewScanner(f)
s.Scan()
return s.Text(), s.Err()
@@ -15,7 +15,7 @@ func (b *Backend) AllowKeyless(ctx context.Context) bool {
if err := b.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
allow, err = b.store.GetAllowKeylessAccess(ctx, tx)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
return false
}
@@ -27,7 +27,7 @@ func (b *Backend) AllowKeyless(ctx context.Context) bool {
//
// It implements backend.Backend.
func (b *Backend) SetAllowKeyless(ctx context.Context, allow bool) error {
- return b.db.TransactionContext(ctx, func(tx *db.Tx) error {
+ return b.db.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
return b.store.SetAllowKeylessAccess(ctx, tx, allow)
})
}
@@ -40,7 +40,7 @@ func (b *Backend) AnonAccess(ctx context.Context) access.AccessLevel {
if err := b.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
level, err = b.store.GetAnonAccess(ctx, tx)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
return access.NoAccess
}
@@ -52,7 +52,7 @@ func (b *Backend) AnonAccess(ctx context.Context) access.AccessLevel {
//
// It implements backend.Backend.
func (b *Backend) SetAnonAccess(ctx context.Context, level access.AccessLevel) error {
- return b.db.TransactionContext(ctx, func(tx *db.Tx) error {
+ return b.db.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
return b.store.SetAnonAccess(ctx, tx, level)
})
}
@@ -42,7 +42,7 @@ func (d *Backend) AccessLevelByPublicKey(ctx context.Context, repo string, pk ss
}
// AccessLevelForUser returns the access level of a user for a repository.
-// TODO: user repository ownership
+// TODO: user repository ownership.
func (d *Backend) AccessLevelForUser(ctx context.Context, repo string, user proto.User) access.AccessLevel {
var username string
anon := d.AnonAccess(ctx)
@@ -61,7 +61,7 @@ func (d *Backend) AccessLevelForUser(ctx context.Context, repo string, user prot
r, _ = d.Repository(ctx, repo)
}
- if r != nil {
+ if r != nil { //nolint:nestif
if user != nil {
// If the user is the owner, they have admin access.
if r.UserID() == user.ID() {
@@ -110,7 +110,7 @@ func (d *Backend) AccessLevelForUser(ctx context.Context, repo string, user prot
func (d *Backend) User(ctx context.Context, username string) (proto.User, error) {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
var m models.User
@@ -119,18 +119,18 @@ func (d *Backend) User(ctx context.Context, username string) (proto.User, error)
var err error
m, err = d.store.FindUserByUsername(ctx, tx, username)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
pks, err = d.store.ListPublicKeysByUserID(ctx, tx, m.ID)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
err = db.WrapError(err)
if errors.Is(err, db.ErrRecordNotFound) {
return nil, proto.ErrUserNotFound
}
d.logger.Error("error finding user", "username", username, "error", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &user{
@@ -147,18 +147,18 @@ func (d *Backend) UserByID(ctx context.Context, id int64) (proto.User, error) {
var err error
m, err = d.store.GetUserByID(ctx, tx, id)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
pks, err = d.store.ListPublicKeysByUserID(ctx, tx, m.ID)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
err = db.WrapError(err)
if errors.Is(err, db.ErrRecordNotFound) {
return nil, proto.ErrUserNotFound
}
d.logger.Error("error finding user", "id", id, "error", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &user{
@@ -181,14 +181,14 @@ func (d *Backend) UserByPublicKey(ctx context.Context, pk ssh.PublicKey) (proto.
}
pks, err = d.store.ListPublicKeysByUserID(ctx, tx, m.ID)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
err = db.WrapError(err)
if errors.Is(err, db.ErrRecordNotFound) {
return nil, proto.ErrUserNotFound
}
d.logger.Error("error finding user", "pk", sshutils.MarshalAuthorizedKey(pk), "error", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &user{
@@ -220,14 +220,14 @@ func (d *Backend) UserByAccessToken(ctx context.Context, token string) (proto.Us
}
pks, err = d.store.ListPublicKeysByUserID(ctx, tx, m.ID)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
err = db.WrapError(err)
if errors.Is(err, db.ErrRecordNotFound) {
return nil, proto.ErrUserNotFound
}
d.logger.Error("failed to find user by access token", "err", err, "token", token)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return &user{
@@ -244,7 +244,7 @@ func (d *Backend) Users(ctx context.Context) ([]string, error) {
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
ms, err := d.store.GetAllUsers(ctx, tx)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, m := range ms {
@@ -253,7 +253,7 @@ func (d *Backend) Users(ctx context.Context) ([]string, error) {
return nil
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
return users, nil
@@ -265,10 +265,10 @@ func (d *Backend) Users(ctx context.Context) ([]string, error) {
func (d *Backend) AddPublicKey(ctx context.Context, username string, pk ssh.PublicKey) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.AddPublicKeyByUsername(ctx, tx, username, pk)
}),
@@ -281,13 +281,13 @@ func (d *Backend) AddPublicKey(ctx context.Context, username string, pk ssh.Publ
func (d *Backend) CreateUser(ctx context.Context, username string, opts proto.UserOptions) (proto.User, error) {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.CreateUser(ctx, tx, username, opts.Admin, opts.PublicKeys)
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
return d.User(ctx, username)
@@ -299,10 +299,10 @@ func (d *Backend) CreateUser(ctx context.Context, username string, opts proto.Us
func (d *Backend) DeleteUser(ctx context.Context, username string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return d.db.TransactionContext(ctx, func(tx *db.Tx) error {
+ return d.db.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
if err := d.store.DeleteUserByUsername(ctx, tx, username); err != nil {
return db.WrapError(err)
}
@@ -315,7 +315,7 @@ func (d *Backend) DeleteUser(ctx context.Context, username string) error {
//
// It implements backend.Backend.
func (d *Backend) RemovePublicKey(ctx context.Context, username string, pk ssh.PublicKey) error {
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.RemovePublicKeyByUsername(ctx, tx, username, pk)
}),
@@ -326,16 +326,16 @@ func (d *Backend) RemovePublicKey(ctx context.Context, username string, pk ssh.P
func (d *Backend) ListPublicKeys(ctx context.Context, username string) ([]ssh.PublicKey, error) {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
var keys []ssh.PublicKey
if err := d.db.TransactionContext(ctx, func(tx *db.Tx) error {
var err error
keys, err = d.store.ListPublicKeysByUsername(ctx, tx, username)
- return err
+ return err //nolint:wrapcheck
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
return keys, nil
@@ -347,10 +347,10 @@ func (d *Backend) ListPublicKeys(ctx context.Context, username string) ([]ssh.Pu
func (d *Backend) SetUsername(ctx context.Context, username string, newUsername string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.SetUsernameByUsername(ctx, tx, username, newUsername)
}),
@@ -363,10 +363,10 @@ func (d *Backend) SetUsername(ctx context.Context, username string, newUsername
func (d *Backend) SetAdmin(ctx context.Context, username string, admin bool) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.SetAdminByUsername(ctx, tx, username, admin)
}),
@@ -377,7 +377,7 @@ func (d *Backend) SetAdmin(ctx context.Context, username string, admin bool) err
func (d *Backend) SetPassword(ctx context.Context, username string, rawPassword string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
password, err := HashPassword(rawPassword)
@@ -385,7 +385,7 @@ func (d *Backend) SetPassword(ctx context.Context, username string, rawPassword
return err
}
- return db.WrapError(
+ return db.WrapError( //nolint:wrapcheck
d.db.TransactionContext(ctx, func(tx *db.Tx) error {
return d.store.SetUserPasswordByUsername(ctx, tx, username, password)
}),
@@ -399,17 +399,17 @@ type user struct {
var _ proto.User = (*user)(nil)
-// IsAdmin implements proto.User
+// IsAdmin implements proto.User.
func (u *user) IsAdmin() bool {
return u.user.Admin
}
-// PublicKeys implements proto.User
+// PublicKeys implements proto.User.
func (u *user) PublicKeys() []ssh.PublicKey {
return u.publicKeys
}
-// Username implements proto.User
+// Username implements proto.User.
func (u *user) Username() string {
return u.user.Username
}
@@ -10,9 +10,9 @@ import (
func LatestFile(r proto.Repository, ref *git.Reference, pattern string) (string, string, error) {
repo, err := r.Open()
if err != nil {
- return "", "", err
+ return "", "", err //nolint:wrapcheck
}
- return git.LatestFile(repo, ref, pattern)
+ return git.LatestFile(repo, ref, pattern) //nolint:wrapcheck
}
// Readme returns the repository's README.
@@ -18,7 +18,7 @@ func (b *Backend) CreateWebhook(ctx context.Context, repo proto.Repository, url
dbx := db.FromContext(ctx)
datastore := store.FromContext(ctx)
- return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
+ return dbx.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
lastID, err := datastore.CreateWebhook(ctx, tx, repo.ID(), url, secret, int(contentType), active)
if err != nil {
return db.WrapError(err)
@@ -63,7 +63,7 @@ func (b *Backend) Webhook(ctx context.Context, repo proto.Repository, id int64)
return nil
}); err != nil {
- return webhook.Hook{}, db.WrapError(err)
+ return webhook.Hook{}, db.WrapError(err) //nolint:wrapcheck
}
return wh, nil
@@ -80,20 +80,20 @@ func (b *Backend) ListWebhooks(ctx context.Context, repo proto.Repository) ([]we
var err error
webhooks, err = datastore.GetWebhooksByRepoID(ctx, tx, repo.ID())
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, h := range webhooks {
events, err := datastore.GetWebhookEventsByWebhookID(ctx, tx, h.ID)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
webhookEvents[h.ID] = events
}
return nil
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
hooks := make([]webhook.Hook, len(webhooks))
@@ -118,7 +118,7 @@ func (b *Backend) UpdateWebhook(ctx context.Context, repo proto.Repository, id i
dbx := db.FromContext(ctx)
datastore := store.FromContext(ctx)
- return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
+ return dbx.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
if err := datastore.UpdateWebhookByID(ctx, tx, repo.ID(), id, url, secret, int(contentType), active); err != nil {
return db.WrapError(err)
}
@@ -175,7 +175,7 @@ func (b *Backend) DeleteWebhook(ctx context.Context, repo proto.Repository, id i
dbx := db.FromContext(ctx)
datastore := store.FromContext(ctx)
- return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
+ return dbx.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
_, err := datastore.GetWebhookByID(ctx, tx, repo.ID(), id)
if err != nil {
return db.WrapError(err)
@@ -203,7 +203,7 @@ func (b *Backend) ListWebhookDeliveries(ctx context.Context, id int64) ([]webhoo
return nil
}); err != nil {
- return nil, db.WrapError(err)
+ return nil, db.WrapError(err) //nolint:wrapcheck
}
ds := make([]webhook.Delivery, len(deliveries))
@@ -239,7 +239,7 @@ func (b *Backend) RedeliverWebhookDelivery(ctx context.Context, repo proto.Repos
return nil
}); err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
log.Infof("redelivering webhook delivery %s for webhook %d\n\n%s\n\n", delID, id, delivery.RequestBody)
@@ -247,10 +247,10 @@ func (b *Backend) RedeliverWebhookDelivery(ctx context.Context, repo proto.Repos
var payload json.RawMessage
if err := json.Unmarshal([]byte(delivery.RequestBody), &payload); err != nil {
log.Errorf("error unmarshaling webhook payload: %v", err)
- return err
+ return err //nolint:wrapcheck
}
- return webhook.SendWebhook(ctx, wh, webhook.Event(delivery.Event), payload)
+ return webhook.SendWebhook(ctx, wh, webhook.Event(delivery.Event), payload) //nolint:wrapcheck
}
// WebhookDelivery returns a webhook delivery.
@@ -272,7 +272,7 @@ func (b *Backend) WebhookDelivery(ctx context.Context, webhookID int64, id uuid.
return nil
}); err != nil {
- return webhook.Delivery{}, db.WrapError(err)
+ return webhook.Delivery{}, db.WrapError(err) //nolint:wrapcheck
}
return delivery, nil
@@ -1,3 +1,4 @@
+// Package config provides configuration management for soft-serve.
package config
import (
@@ -228,10 +229,10 @@ func IsVerbose() bool {
func parseFile(cfg *Config, path string) error {
f, err := os.Open(path)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint:errcheck
if err := yaml.NewDecoder(f).Decode(cfg); err != nil {
return fmt.Errorf("decode config: %w", err)
}
@@ -283,10 +284,10 @@ func (c *Config) Parse() error {
// writeConfig writes the configuration to the given file.
func writeConfig(cfg *Config, path string) error {
- if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
- return os.WriteFile(path, []byte(newConfigFile(cfg)), 0o644) // nolint: errcheck, gosec
+ return os.WriteFile(path, []byte(newConfigFile(cfg)), 0o644) //nolint:gosec,wrapcheck
}
// WriteConfig writes the configuration to the default file.
@@ -307,7 +308,7 @@ func DefaultDataPath() string {
}
// ConfigPath returns the path to the config file.
-func (c *Config) ConfigPath() string { // nolint:revive
+func (c *Config) ConfigPath() string {
// If we have a custom config location set, then use that.
if path := os.Getenv("SOFT_SERVE_CONFIG_LOCATION"); exist(path) {
return path
@@ -386,7 +387,7 @@ func (c *Config) Validate() error {
if !filepath.IsAbs(c.DataPath) {
dp, err := filepath.Abs(c.DataPath)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
c.DataPath = dp
}
@@ -125,6 +125,6 @@ jobs:
func newConfigFile(cfg *Config) string {
var b bytes.Buffer
- configFileTmpl.Execute(&b, cfg) // nolint: errcheck
+ configFileTmpl.Execute(&b, cfg) //nolint:errcheck,gosec
return b.String()
}
@@ -24,5 +24,5 @@ func KeyPair(cfg *Config) (*keygen.SSHKeyPair, error) {
return nil, ErrEmptySSHKeyPath
}
- return keygen.New(cfg.SSH.KeyPath, keygen.WithKeyType(keygen.Ed25519))
+ return keygen.New(cfg.SSH.KeyPath, keygen.WithKeyType(keygen.Ed25519)) //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package cron provides scheduled task management functionality.
package cron
import (
@@ -37,9 +38,9 @@ func NewScheduler(ctx context.Context) *Scheduler {
}
}
-// Shutdonw gracefully shuts down the Scheduler.
+// Shutdown gracefully shuts down the Scheduler.
func (s *Scheduler) Shutdown() {
- ctx, cancel := context.WithTimeout(s.Cron.Stop(), 30*time.Second)
+ ctx, cancel := context.WithTimeout(s.Stop(), 30*time.Second)
defer func() { cancel() }()
<-ctx.Done()
}
@@ -1,3 +1,4 @@
+// Package daemon provides Git daemon server functionality.
package daemon
import (
@@ -25,7 +26,7 @@ func (m *connections) Close(c net.Conn) error {
defer m.mu.Unlock()
err := c.Close()
delete(m.m, c)
- return err
+ return err //nolint:wrapcheck
}
func (m *connections) Size() int {
@@ -91,15 +92,15 @@ func (c *serverConn) updateDeadline() {
initTimeout := time.Now().Add(c.initTimeout)
c.initTimeout = 0
if initTimeout.Unix() < c.maxDeadline.Unix() || c.maxDeadline.IsZero() {
- c.Conn.SetDeadline(initTimeout) // nolint: errcheck
+ c.SetDeadline(initTimeout) //nolint:errcheck,gosec
return
}
case c.idleTimeout > 0:
idleDeadline := time.Now().Add(c.idleTimeout)
if idleDeadline.Unix() < c.maxDeadline.Unix() || c.maxDeadline.IsZero() {
- c.Conn.SetDeadline(idleDeadline) // nolint: errcheck
+ c.SetDeadline(idleDeadline) //nolint:errcheck,gosec
return
}
}
- c.Conn.SetDeadline(c.maxDeadline) // nolint: errcheck
+ c.SetDeadline(c.maxDeadline) //nolint:errcheck,gosec
}
@@ -58,7 +58,7 @@ type GitDaemon struct {
liMu sync.Mutex
}
-// NewDaemon returns a new Git daemon.
+// NewGitDaemon returns a new Git daemon.
func NewGitDaemon(ctx context.Context) (*GitDaemon, error) {
cfg := config.FromContext(ctx)
addr := cfg.Git.ListenAddr
@@ -79,9 +79,9 @@ func (d *GitDaemon) ListenAndServe() error {
if d.done.Load() {
return ErrServerClosed
}
- listener, err := net.Listen("tcp", d.addr)
+ listener, err := net.Listen("tcp", d.addr) //nolint:noctx
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return d.Serve(listener)
}
@@ -101,14 +101,14 @@ func (d *GitDaemon) Serve(listener net.Listener) error {
var tempDelay time.Duration
for {
conn, err := listener.Accept()
- if err != nil {
+ if err != nil { //nolint:nestif
select {
case <-d.finished:
return ErrServerClosed
default:
d.logger.Debugf("git: error accepting connection: %v", err)
}
- if ne, ok := err.(net.Error); ok && ne.Temporary() { // nolint: staticcheck
+ if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
@@ -120,7 +120,7 @@ func (d *GitDaemon) Serve(listener net.Listener) error {
time.Sleep(tempDelay)
continue
}
- return err
+ return err //nolint:wrapcheck
}
// Close connection if there are too many open connections.
@@ -139,7 +139,7 @@ func (d *GitDaemon) Serve(listener net.Listener) error {
}
func (d *GitDaemon) fatal(c net.Conn, err error) {
- git.WritePktlineErr(c, err) // nolint: errcheck
+ git.WritePktlineErr(c, err) //nolint:errcheck,gosec
if err := c.Close(); err != nil {
d.logger.Debugf("git: error closing connection: %v", err)
}
@@ -160,7 +160,7 @@ func (d *GitDaemon) handleClient(conn net.Conn) {
}
d.conns.Add(c)
defer func() {
- d.conns.Close(c) // nolint: errcheck
+ d.conns.Close(c) //nolint:errcheck,gosec
}()
errc := make(chan error, 1)
@@ -201,7 +201,7 @@ func (d *GitDaemon) handleClient(conn net.Conn) {
var counter *prometheus.CounterVec
service := git.Service(split[0])
- switch service {
+ switch service { //nolint:exhaustive
case git.UploadPackService:
counter = uploadPackGitCounter
case git.UploadArchiveService:
@@ -213,7 +213,7 @@ func (d *GitDaemon) handleClient(conn net.Conn) {
opts := bytes.SplitN(split[1], []byte{0}, 3)
if len(opts) < 2 {
- d.fatal(c, git.ErrInvalidRequest) // nolint: errcheck
+ d.fatal(c, git.ErrInvalidRequest)
return
}
@@ -317,7 +317,7 @@ func (d *GitDaemon) handleClient(conn net.Conn) {
// Close closes the underlying listener.
func (d *GitDaemon) Close() error {
err := d.closeListener()
- d.conns.CloseAll() // nolint: errcheck
+ d.conns.CloseAll() //nolint:errcheck,gosec
return err
}
@@ -356,7 +356,7 @@ func (d *GitDaemon) Shutdown(ctx context.Context) error {
}()
select {
case <-ctx.Done():
- return ctx.Err()
+ return ctx.Err() //nolint:wrapcheck
case <-finished:
return err
}
@@ -1,3 +1,4 @@
+// Package db provides database operations and context management.
package db
import "context"
@@ -23,7 +23,7 @@ type DB struct {
func Open(ctx context.Context, driverName string, dsn string) (*DB, error) {
db, err := sqlx.ConnectContext(ctx, driverName, dsn)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
d := &DB{
@@ -40,7 +40,7 @@ func Open(ctx context.Context, driverName string, dsn string) (*DB, error) {
// Close implements db.DB.
func (d *DB) Close() error {
- return d.DB.Close()
+ return d.DB.Close() //nolint:wrapcheck
}
// Tx is a database transaction.
@@ -56,7 +56,7 @@ func (d *DB) Transaction(fn func(tx *Tx) error) error {
// TransactionContext implements db.DB.
func (d *DB) TransactionContext(ctx context.Context, fn func(tx *Tx) error) error {
- txx, err := d.DB.BeginTxx(ctx, nil)
+ txx, err := d.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
@@ -20,7 +20,7 @@ var (
// WrapError is a convenient function that unite various database driver
// errors to consistent errors.
func WrapError(err error) error {
- if err != nil {
+ if err != nil { //nolint:nestif
if errors.Is(err, sql.ErrNoRows) {
return ErrRecordNotFound
}
@@ -1,3 +1,4 @@
+// Package test provides testing utilities for database operations.
package test
import (
@@ -18,7 +19,7 @@ func OpenSqlite(ctx context.Context, tb testing.TB) (*db.DB, error) {
dbpath := filepath.Join(tb.TempDir(), "test.db")
dbx, err := db.Open(ctx, "sqlite", dbpath)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
tb.Cleanup(func() {
if err := dbx.Close(); err != nil {
@@ -21,19 +21,19 @@ func trace(l *log.Logger, query string, args ...interface{}) {
// Select is a wrapper around sqlx.Select that logs the query and arguments.
func (d *DB) Select(dest interface{}, query string, args ...interface{}) error {
trace(d.logger, query, args...)
- return d.DB.Select(dest, query, args...)
+ return d.DB.Select(dest, query, args...) //nolint:wrapcheck
}
// Get is a wrapper around sqlx.Get that logs the query and arguments.
func (d *DB) Get(dest interface{}, query string, args ...interface{}) error {
trace(d.logger, query, args...)
- return d.DB.Get(dest, query, args...)
+ return d.DB.Get(dest, query, args...) //nolint:wrapcheck
}
// Queryx is a wrapper around sqlx.Queryx that logs the query and arguments.
func (d *DB) Queryx(query string, args ...interface{}) (*sqlx.Rows, error) {
trace(d.logger, query, args...)
- return d.DB.Queryx(query, args...)
+ return d.DB.Queryx(query, args...) //nolint:wrapcheck
}
// QueryRowx is a wrapper around sqlx.QueryRowx that logs the query and arguments.
@@ -45,25 +45,25 @@ func (d *DB) QueryRowx(query string, args ...interface{}) *sqlx.Row {
// Exec is a wrapper around sqlx.Exec that logs the query and arguments.
func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
trace(d.logger, query, args...)
- return d.DB.Exec(query, args...)
+ return d.DB.Exec(query, args...) //nolint:noctx,wrapcheck
}
// SelectContext is a wrapper around sqlx.SelectContext that logs the query and arguments.
func (d *DB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
trace(d.logger, query, args...)
- return d.DB.SelectContext(ctx, dest, query, args...)
+ return d.DB.SelectContext(ctx, dest, query, args...) //nolint:wrapcheck
}
// GetContext is a wrapper around sqlx.GetContext that logs the query and arguments.
func (d *DB) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
trace(d.logger, query, args...)
- return d.DB.GetContext(ctx, dest, query, args...)
+ return d.DB.GetContext(ctx, dest, query, args...) //nolint:wrapcheck
}
// QueryxContext is a wrapper around sqlx.QueryxContext that logs the query and arguments.
func (d *DB) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) {
trace(d.logger, query, args...)
- return d.DB.QueryxContext(ctx, query, args...)
+ return d.DB.QueryxContext(ctx, query, args...) //nolint:wrapcheck
}
// QueryRowxContext is a wrapper around sqlx.QueryRowxContext that logs the query and arguments.
@@ -75,25 +75,25 @@ func (d *DB) QueryRowxContext(ctx context.Context, query string, args ...interfa
// ExecContext is a wrapper around sqlx.ExecContext that logs the query and arguments.
func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
trace(d.logger, query, args...)
- return d.DB.ExecContext(ctx, query, args...)
+ return d.DB.ExecContext(ctx, query, args...) //nolint:wrapcheck
}
// Select is a wrapper around sqlx.Select that logs the query and arguments.
func (t *Tx) Select(dest interface{}, query string, args ...interface{}) error {
trace(t.logger, query, args...)
- return t.Tx.Select(dest, query, args...)
+ return t.Tx.Select(dest, query, args...) //nolint:wrapcheck
}
// Get is a wrapper around sqlx.Get that logs the query and arguments.
func (t *Tx) Get(dest interface{}, query string, args ...interface{}) error {
trace(t.logger, query, args...)
- return t.Tx.Get(dest, query, args...)
+ return t.Tx.Get(dest, query, args...) //nolint:wrapcheck
}
// Queryx is a wrapper around sqlx.Queryx that logs the query and arguments.
func (t *Tx) Queryx(query string, args ...interface{}) (*sqlx.Rows, error) {
trace(t.logger, query, args...)
- return t.Tx.Queryx(query, args...)
+ return t.Tx.Queryx(query, args...) //nolint:wrapcheck
}
// QueryRowx is a wrapper around sqlx.QueryRowx that logs the query and arguments.
@@ -105,25 +105,25 @@ func (t *Tx) QueryRowx(query string, args ...interface{}) *sqlx.Row {
// Exec is a wrapper around sqlx.Exec that logs the query and arguments.
func (t *Tx) Exec(query string, args ...interface{}) (sql.Result, error) {
trace(t.logger, query, args...)
- return t.Tx.Exec(query, args...)
+ return t.Tx.Exec(query, args...) //nolint:noctx,wrapcheck
}
// SelectContext is a wrapper around sqlx.SelectContext that logs the query and arguments.
func (t *Tx) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
trace(t.logger, query, args...)
- return t.Tx.SelectContext(ctx, dest, query, args...)
+ return t.Tx.SelectContext(ctx, dest, query, args...) //nolint:wrapcheck
}
// GetContext is a wrapper around sqlx.GetContext that logs the query and arguments.
func (t *Tx) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
trace(t.logger, query, args...)
- return t.Tx.GetContext(ctx, dest, query, args...)
+ return t.Tx.GetContext(ctx, dest, query, args...) //nolint:wrapcheck
}
// QueryxContext is a wrapper around sqlx.QueryxContext that logs the query and arguments.
func (t *Tx) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) {
trace(t.logger, query, args...)
- return t.Tx.QueryxContext(ctx, query, args...)
+ return t.Tx.QueryxContext(ctx, query, args...) //nolint:wrapcheck
}
// QueryRowxContext is a wrapper around sqlx.QueryRowxContext that logs the query and arguments.
@@ -135,5 +135,5 @@ func (t *Tx) QueryRowxContext(ctx context.Context, query string, args ...interfa
// ExecContext is a wrapper around sqlx.ExecContext that logs the query and arguments.
func (t *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
trace(t.logger, query, args...)
- return t.Tx.ExecContext(ctx, query, args...)
+ return t.Tx.ExecContext(ctx, query, args...) //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package migrate provides database migration functionality.
package migrate
import (
@@ -34,25 +35,25 @@ var createTables = Migration{
hasUserTable := hasTable(tx, "user")
if hasUserTable {
if _, err := tx.ExecContext(ctx, "ALTER TABLE user RENAME TO user_old"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if hasTable(tx, "public_key") {
if _, err := tx.ExecContext(ctx, "ALTER TABLE public_key RENAME TO public_key_old"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if hasTable(tx, "collab") {
if _, err := tx.ExecContext(ctx, "ALTER TABLE collab RENAME TO collab_old"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if hasTable(tx, "repo") {
if _, err := tx.ExecContext(ctx, "ALTER TABLE repo RENAME TO repo_old"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
}
@@ -65,7 +66,7 @@ var createTables = Migration{
case "sqlite3", "sqlite":
if _, err := tx.ExecContext(ctx, "PRAGMA foreign_keys = OFF"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
if hasTable(tx, "user_old") {
@@ -74,7 +75,7 @@ var createTables = Migration{
SELECT id, username, admin, updated_at FROM user_old;
`
if _, err := tx.ExecContext(ctx, sqlm); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -85,7 +86,7 @@ var createTables = Migration{
PublicKey string `db:"public_key"`
}{}
if err := tx.SelectContext(ctx, &pks, "SELECT id, public_key FROM public_key_old"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
pkss := map[string]struct{}{}
@@ -101,7 +102,7 @@ var createTables = Migration{
SELECT id, user_id, public_key, created_at, updated_at FROM public_key_old;
`
if _, err := tx.ExecContext(ctx, sqlm); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -113,7 +114,7 @@ var createTables = Migration{
) FROM repo_old;
`
if _, err := tx.ExecContext(ctx, sqlm); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -123,19 +124,19 @@ var createTables = Migration{
SELECT id, user_id, repo_id, ` + strconv.Itoa(int(access.ReadWriteAccess)) + `, created_at, updated_at FROM collab_old;
`
if _, err := tx.ExecContext(ctx, sqlm); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if _, err := tx.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
// Insert default user
insertUser := tx.Rebind(insert + "INTO users (username, admin, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)")
if _, err := tx.ExecContext(ctx, insertUser, "admin", true); err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, k := range cfg.AdminKeys() {
@@ -150,7 +151,7 @@ var createTables = Migration{
if errors.Is(db.WrapError(err), db.ErrDuplicateKey) {
continue
}
- return err
+ return err //nolint:wrapcheck
}
}
@@ -29,12 +29,12 @@ var migrateLfsObjects = Migration{
var repoIDs []int64
if err := tx.Select(&repoIDs, "SELECT id FROM repos"); err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, r := range repoIDs {
var objs []models.LFSObject
if err := tx.Select(&objs, "SELECT * FROM lfs_objects WHERE repo_id = ?", r); err != nil {
- return err
+ return err //nolint:wrapcheck
}
objsp := filepath.Join(cfg.DataPath, "lfs", strconv.FormatInt(r, 10), "objects")
for _, obj := range objs {
@@ -10,8 +10,14 @@ import (
"github.com/charmbracelet/soft-serve/pkg/db"
)
+const (
+ postgresDriver = "postgres"
+ sqliteDriver = "sqlite"
+ sqlite3Driver = "sqlite3"
+)
+
// MigrateFunc is a function that executes a migration.
-type MigrateFunc func(ctx context.Context, tx *db.Tx) error // nolint:revive
+type MigrateFunc func(ctx context.Context, tx *db.Tx) error //nolint:revive
// Migration is a struct that contains the name of the migration and the
// function to execute it.
@@ -31,14 +37,14 @@ type Migrations struct {
func (Migrations) schema(driverName string) string {
switch driverName {
- case "sqlite3", "sqlite":
+ case sqlite3Driver, sqliteDriver:
return `CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
version INTEGER NOT NULL UNIQUE
);
`
- case "postgres":
+ case postgresDriver:
return `CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
@@ -62,17 +68,17 @@ func (Migrations) schema(driverName string) string {
// Migrate runs the migrations.
func Migrate(ctx context.Context, dbx *db.DB) error {
logger := log.FromContext(ctx).WithPrefix("migrate")
- return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
+ return dbx.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
if !hasTable(tx, "migrations") {
if _, err := tx.Exec(Migrations{}.schema(tx.DriverName())); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
var migrs Migrations
if err := tx.Get(&migrs, tx.Rebind("SELECT * FROM migrations ORDER BY version DESC LIMIT 1")); err != nil {
if !errors.Is(err, sql.ErrNoRows) {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -87,7 +93,7 @@ func Migrate(ctx context.Context, dbx *db.DB) error {
}
if _, err := tx.Exec(tx.Rebind("INSERT INTO migrations (name, version) VALUES (?, ?)"), m.Name, m.Version); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -98,7 +104,7 @@ func Migrate(ctx context.Context, dbx *db.DB) error {
// Rollback rolls back a migration.
func Rollback(ctx context.Context, dbx *db.DB) error {
logger := log.FromContext(ctx).WithPrefix("migrate")
- return dbx.TransactionContext(ctx, func(tx *db.Tx) error {
+ return dbx.TransactionContext(ctx, func(tx *db.Tx) error { //nolint:wrapcheck
var migrs Migrations
if err := tx.Get(&migrs, tx.Rebind("SELECT * FROM migrations ORDER BY version DESC LIMIT 1")); err != nil {
if !errors.Is(err, sql.ErrNoRows) {
@@ -117,7 +123,7 @@ func Rollback(ctx context.Context, dbx *db.DB) error {
}
if _, err := tx.Exec(tx.Rebind("DELETE FROM migrations WHERE version = ?"), migrs.Version); err != nil {
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -127,9 +133,9 @@ func Rollback(ctx context.Context, dbx *db.DB) error {
func hasTable(tx *db.Tx, tableName string) bool {
var query string
switch tx.DriverName() {
- case "sqlite3", "sqlite":
+ case sqlite3Driver, sqliteDriver:
query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
- case "postgres":
+ case postgresDriver:
fallthrough
case "mysql":
query = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = ?"
@@ -27,18 +27,18 @@ func execMigration(ctx context.Context, tx *db.Tx, version int, name string, dow
}
driverName := tx.DriverName()
- if driverName == "sqlite3" {
- driverName = "sqlite"
+ if driverName == sqlite3Driver {
+ driverName = sqliteDriver
}
fn := fmt.Sprintf("%04d_%s_%s.%s.sql", version, toSnakeCase(name), driverName, direction)
sqlstr, err := sqls.ReadFile(fn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if _, err := tx.ExecContext(ctx, string(sqlstr)); err != nil {
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -1,3 +1,4 @@
+// Package models provides database model definitions.
package models
import (
@@ -1,3 +1,4 @@
+// Package git provides Git service operations and utilities.
package git
import "errors"
@@ -64,14 +64,14 @@ func EnsureWithin(reposDir string, repo string) error {
func EnsureDefaultBranch(ctx context.Context, repoPath string) error {
r, err := git.Open(repoPath)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
brs, err := r.Branches()
if len(brs) == 0 {
return ErrNoBranches
}
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
// Rename the default branch to the first branch available
_, err = r.HEAD()
@@ -90,11 +90,11 @@ func EnsureDefaultBranch(ctx context.Context, repoPath string) error {
Context: ctx,
},
}); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if err != nil && err != git.ErrReferenceNotExist {
- return err
+ return err //nolint:wrapcheck
}
return nil
}
@@ -62,13 +62,13 @@ func LFSTransfer(ctx context.Context, cmd ServiceCommand) error {
for _, cap := range transfer.Capabilities {
if err := handler.WritePacketText(cap); err != nil {
logger.Errorf("error sending capability: %s: %v", cap, err)
- return err
+ return err //nolint:wrapcheck
}
}
if err := handler.WriteFlush(); err != nil {
logger.Error("error sending flush", "err", err)
- return err
+ return err //nolint:wrapcheck
}
repoID := strconv.FormatInt(repo.ID(), 10)
@@ -83,7 +83,7 @@ func LFSTransfer(ctx context.Context, cmd ServiceCommand) error {
repo: repo,
}, &lfsLogger{logger})
- return processor.ProcessCommands(op)
+ return processor.ProcessCommands(op) //nolint:wrapcheck
}
// Batch implements transfer.Backend.
@@ -91,17 +91,17 @@ func (t *lfsTransfer) Batch(_ string, pointers []transfer.BatchItem, _ transfer.
for i := range pointers {
obj, err := t.store.GetLFSObjectByOid(t.ctx, t.dbx, t.repo.ID(), pointers[i].Oid)
if err != nil && !errors.Is(err, db.ErrRecordNotFound) {
- return pointers, db.WrapError(err)
+ return pointers, db.WrapError(err) //nolint:wrapcheck
}
pointers[i].Present, err = t.storage.Exists(path.Join("objects", pointers[i].RelativePath()))
if err != nil {
- return pointers, err
+ return pointers, err //nolint:wrapcheck
}
if pointers[i].Present && obj.ID == 0 {
if err := t.store.CreateLFSObject(t.ctx, t.dbx, t.repo.ID(), pointers[i].Oid, pointers[i].Size); err != nil {
- return pointers, db.WrapError(err)
+ return pointers, db.WrapError(err) //nolint:wrapcheck
}
}
}
@@ -117,11 +117,11 @@ func (t *lfsTransfer) Download(oid string, _ transfer.Args) (io.ReadCloser, int6
pointer := transfer.Pointer{Oid: oid}
obj, err := strg.Open(path.Join("objects", pointer.RelativePath()))
if err != nil {
- return nil, 0, err
+ return nil, 0, err //nolint:wrapcheck
}
stat, err := obj.Stat()
if err != nil {
- return nil, 0, err
+ return nil, 0, err //nolint:wrapcheck
}
return obj, stat.Size(), nil
}
@@ -135,7 +135,7 @@ func (t *lfsTransfer) Upload(oid string, size int64, r io.Reader, _ transfer.Arg
tempDir := "incomplete"
randBytes := make([]byte, 12)
if _, err := rand.Read(randBytes); err != nil {
- return err
+ return err //nolint:wrapcheck
}
tempName := fmt.Sprintf("%s%x", oid, randBytes)
@@ -144,13 +144,13 @@ func (t *lfsTransfer) Upload(oid string, size int64, r io.Reader, _ transfer.Arg
written, err := t.storage.Put(tempName, r)
if err != nil {
t.logger.Errorf("error putting object: %v", err)
- return err
+ return err //nolint:wrapcheck
}
obj, err := t.storage.Open(tempName)
if err != nil {
t.logger.Errorf("error opening object: %v", err)
- return err
+ return err //nolint:wrapcheck
}
pointer := transfer.Pointer{
@@ -163,14 +163,14 @@ func (t *lfsTransfer) Upload(oid string, size int64, r io.Reader, _ transfer.Arg
}
if err := t.store.CreateLFSObject(t.ctx, t.dbx, t.repo.ID(), pointer.Oid, pointer.Size); err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
expectedPath := path.Join("objects", pointer.RelativePath())
if err := t.storage.Rename(obj.Name(), expectedPath); err != nil {
t.logger.Errorf("error renaming object: %v", err)
_ = t.store.DeleteLFSObjectByOid(t.ctx, t.dbx, t.repo.ID(), pointer.Oid)
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -184,7 +184,7 @@ func (t *lfsTransfer) Verify(oid string, size int64, _ transfer.Args) (transfer.
return transfer.NewStatus(transfer.StatusNotFound, "object not found"), nil
}
t.logger.Errorf("error getting object: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
if obj.Size != size {
@@ -236,7 +236,7 @@ func (l *lfsLockBackend) Create(path string, refname string) (transfer.Lock, err
return nil, transfer.ErrConflict
}
l.logger.Errorf("error creating lock: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
lock.backend = l
@@ -249,7 +249,7 @@ func (l *lfsLockBackend) FromID(id string) (transfer.Lock, error) {
var lock LFSLock
iid, err := strconv.ParseInt(id, 10, 64)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
if err := l.dbx.TransactionContext(l.ctx, func(tx *db.Tx) error {
@@ -266,7 +266,7 @@ func (l *lfsLockBackend) FromID(id string) (transfer.Lock, error) {
return nil, transfer.ErrNotFound
}
l.logger.Errorf("error getting lock: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
lock.backend = l
@@ -292,7 +292,7 @@ func (l *lfsLockBackend) FromPath(path string) (transfer.Lock, error) {
return nil, transfer.ErrNotFound
}
l.logger.Errorf("error getting lock: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
lock.backend = l
@@ -344,7 +344,7 @@ func (l *lfsLockBackend) Range(cursor string, limit int, fn func(transfer.Lock)
return nil
}); err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
for _, lock := range locks {
@@ -360,7 +360,7 @@ func (l *lfsLockBackend) Range(cursor string, limit int, fn func(transfer.Lock)
func (l *lfsLockBackend) Unlock(lock transfer.Lock) error {
id, err := strconv.ParseInt(lock.ID(), 10, 64)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
err = l.dbx.TransactionContext(l.ctx, func(tx *db.Tx) error {
@@ -373,7 +373,7 @@ func (l *lfsLockBackend) Unlock(lock transfer.Lock) error {
return transfer.ErrNotFound
}
l.logger.Error("error unlocking lock", "err", err)
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -15,7 +15,7 @@ import (
"github.com/golang-jwt/jwt/v5"
)
-// LFSAuthenticate implements teh Git LFS SSH authentication command.
+// LFSAuthenticate implements the Git LFS SSH authentication command.
// Context must have *config.Config, *log.Logger, proto.User.
// cmd.Args should have the repo path and operation as arguments.
func LFSAuthenticate(ctx context.Context, cmd ServiceCommand) error {
@@ -46,7 +46,7 @@ func LFSAuthenticate(ctx context.Context, cmd ServiceCommand) error {
kp, err := jwk.NewPair(cfg)
if err != nil {
logger.Error("failed to get JWK pair", "err", err)
- return err
+ return err //nolint:wrapcheck
}
now := time.Now()
@@ -68,13 +68,13 @@ func LFSAuthenticate(ctx context.Context, cmd ServiceCommand) error {
j, err := token.SignedString(kp.PrivateKey())
if err != nil {
logger.Error("failed to sign token", "err", err)
- return err
+ return err //nolint:wrapcheck
}
href := fmt.Sprintf("%s/%s.git/info/lfs", cfg.HTTP.PublicURL, repo.Name())
logger.Debug("generated token", "token", j, "href", href, "expires_at", expiresAt)
- return json.NewEncoder(cmd.Stdout).Encode(lfs.AuthenticateResponse{
+ return json.NewEncoder(cmd.Stdout).Encode(lfs.AuthenticateResponse{ //nolint:wrapcheck
Header: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", j),
},
@@ -94,21 +94,21 @@ func gitServiceHandler(ctx context.Context, svc Service, scmd ServiceCommand) er
if scmd.Stdin != nil {
stdin, err = cmd.StdinPipe()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if scmd.Stdout != nil {
stdout, err = cmd.StdoutPipe()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
if scmd.Stderr != nil {
stderr, err = cmd.StderrPipe()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -116,7 +116,7 @@ func gitServiceHandler(ctx context.Context, svc Service, scmd ServiceCommand) er
if errors.Is(err, os.ErrNotExist) {
return ErrInvalidRepo
}
- return err
+ return err //nolint:wrapcheck
}
wg := &sync.WaitGroup{}
@@ -124,7 +124,7 @@ func gitServiceHandler(ctx context.Context, svc Service, scmd ServiceCommand) er
// stdin
if scmd.Stdin != nil {
go func() {
- defer stdin.Close() // nolint: errcheck
+ defer stdin.Close() //nolint: errcheck
if _, err := io.Copy(stdin, scmd.Stdin); err != nil {
log.Errorf("gitServiceHandler: failed to copy stdin: %v", err)
}
@@ -167,7 +167,7 @@ func gitServiceHandler(ctx context.Context, svc Service, scmd ServiceCommand) er
return fmt.Errorf("%s: %s", exitErr, exitErr.Stderr)
}
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -1,3 +1,4 @@
+// Package hooks provides Git hook generation and management.
package hooks
import (
@@ -31,8 +32,8 @@ const (
func GenerateHooks(_ context.Context, cfg *config.Config, repo string) error {
repo = utils.SanitizeRepo(repo) + ".git"
hooksPath := filepath.Join(cfg.DataPath, "repos", repo, "hooks")
- if err := os.MkdirAll(hooksPath, os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(hooksPath, os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
for _, hook := range []string{
@@ -49,13 +50,13 @@ func GenerateHooks(_ context.Context, cfg *config.Config, repo string) error {
// Write the hooks primary script
if err := os.WriteFile(hp, []byte(hookTemplate), os.ModePerm); err != nil { //nolint:gosec
- return err
+ return err //nolint:wrapcheck
}
// Create ${hook}.d directory.
hp += ".d"
- if err := os.MkdirAll(hp, os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(hp, os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
switch hook {
@@ -1,3 +1,4 @@
+// Package jobs provides background job processing functionality.
package jobs
import (
@@ -53,7 +53,7 @@ func (m mirrorPull) Func(ctx context.Context) func() {
logger.Debug("updating mirror repos")
for _, repo := range repos {
- if repo.IsMirror() {
+ if repo.IsMirror() { //nolint:nestif
r, err := repo.Open()
if err != nil {
logger.Error("error opening repository", "repo", repo.Name(), "err", err)
@@ -1,3 +1,4 @@
+// Package jwk provides JSON Web Key functionality.
package jwk
import (
@@ -34,7 +35,7 @@ func (p Pair) JWK() jose.JSONWebKey {
func NewPair(cfg *config.Config) (Pair, error) {
kp, err := config.KeyPair(cfg)
if err != nil {
- return Pair{}, err
+ return Pair{}, err //nolint:wrapcheck
}
sum := sha256.Sum256(kp.RawPrivateKey())
@@ -1,3 +1,4 @@
+// Package lfs provides Git LFS (Large File Storage) functionality.
package lfs
import (
@@ -12,17 +13,17 @@ import (
"github.com/charmbracelet/log/v2"
)
-// BasicTransferAdapter implements the "basic" adapter
+// BasicTransferAdapter implements the "basic" adapter.
type BasicTransferAdapter struct {
client *http.Client
}
-// Name returns the name of the adapter
+// Name returns the name of the adapter.
func (a *BasicTransferAdapter) Name() string {
return "basic"
}
-// Download reads the download location and downloads the data
+// Download reads the download location and downloads the data.
func (a *BasicTransferAdapter) Download(ctx context.Context, _ Pointer, l *Link) (io.ReadCloser, error) {
resp, err := a.performRequest(ctx, "GET", l, nil, nil)
if err != nil {
@@ -31,7 +32,7 @@ func (a *BasicTransferAdapter) Download(ctx context.Context, _ Pointer, l *Link)
return resp.Body, nil
}
-// Upload sends the content to the LFS server
+// Upload sends the content to the LFS server.
func (a *BasicTransferAdapter) Upload(ctx context.Context, p Pointer, r io.Reader, l *Link) error {
res, err := a.performRequest(ctx, "PUT", l, r, func(req *http.Request) {
if len(req.Header.Get("Content-Type")) == 0 {
@@ -47,16 +48,16 @@ func (a *BasicTransferAdapter) Upload(ctx context.Context, p Pointer, r io.Reade
if err != nil {
return err
}
- return res.Body.Close()
+ return res.Body.Close() //nolint:wrapcheck
}
-// Verify calls the verify handler on the LFS server
+// Verify calls the verify handler on the LFS server.
func (a *BasicTransferAdapter) Verify(ctx context.Context, p Pointer, l *Link) error {
logger := log.FromContext(ctx).WithPrefix("lfs")
b, err := json.Marshal(p)
if err != nil {
logger.Errorf("Error encoding json: %v", err)
- return err
+ return err //nolint:wrapcheck
}
res, err := a.performRequest(ctx, "POST", l, bytes.NewReader(b), func(req *http.Request) {
@@ -65,7 +66,7 @@ func (a *BasicTransferAdapter) Verify(ctx context.Context, p Pointer, l *Link) e
if err != nil {
return err
}
- return res.Body.Close()
+ return res.Body.Close() //nolint:wrapcheck
}
func (a *BasicTransferAdapter) performRequest(ctx context.Context, method string, l *Link, body io.Reader, callback func(*http.Request)) (*http.Response, error) {
@@ -75,7 +76,7 @@ func (a *BasicTransferAdapter) performRequest(ctx context.Context, method string
req, err := http.NewRequestWithContext(ctx, method, l.Href, body)
if err != nil {
logger.Errorf("Error creating request: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
for key, value := range l.Header {
req.Header.Set(key, value)
@@ -90,11 +91,11 @@ func (a *BasicTransferAdapter) performRequest(ctx context.Context, method string
if err != nil {
select {
case <-ctx.Done():
- return res, ctx.Err()
+ return res, ctx.Err() //nolint:wrapcheck
default:
}
logger.Errorf("Error while processing request: %v", err)
- return res, err
+ return res, err //nolint:wrapcheck
}
if res.StatusCode != http.StatusOK {
@@ -105,11 +106,11 @@ func (a *BasicTransferAdapter) performRequest(ctx context.Context, method string
}
func handleErrorResponse(resp *http.Response) error {
- defer resp.Body.Close() // nolint: errcheck
+ defer resp.Body.Close() //nolint: errcheck
er, err := decodeResponseError(resp.Body)
if err != nil {
- return fmt.Errorf("Request failed with status %s", resp.Status)
+ return fmt.Errorf("request failed with status %s", resp.Status)
}
return errors.New(er.Message)
}
@@ -120,5 +121,5 @@ func decodeResponseError(r io.Reader) (ErrorResponse, error) {
if err != nil {
log.Error("Error decoding json: %v", err)
}
- return er, err
+ return er, err //nolint:wrapcheck
}
@@ -5,10 +5,15 @@ import (
"io"
)
-// DownloadCallback gets called for every requested LFS object to process its content
+const (
+ httpScheme = "http"
+ httpsScheme = "https"
+)
+
+// DownloadCallback gets called for every requested LFS object to process its content.
type DownloadCallback func(p Pointer, content io.ReadCloser, objectError error) error
-// UploadCallback gets called for every requested LFS object to provide its content
+// UploadCallback gets called for every requested LFS object to provide its content.
type UploadCallback func(p Pointer, objectError error) (io.ReadCloser, error)
// Client is a Git LFS client to communicate with a LFS source API.
@@ -19,7 +24,7 @@ type Client interface {
// NewClient returns a new Git LFS client.
func NewClient(e Endpoint) Client {
- if e.Scheme == "http" || e.Scheme == "https" {
+ if e.Scheme == httpScheme || e.Scheme == httpsScheme {
return newHTTPClient(e)
}
// TODO: support ssh client
@@ -28,7 +28,7 @@ const (
DefaultLocksLimit = 20
)
-// Pointer contains LFS pointer data
+// Pointer contains LFS pointer data.
type Pointer struct {
Oid string `json:"oid"`
Size int64 `json:"size"`
@@ -25,12 +25,12 @@ func NewEndpoint(rawurl string) (Endpoint, error) {
switch u.Scheme {
case "git":
// Use https for git:// URLs and strip the port if it exists.
- u.Scheme = "https"
+ u.Scheme = httpsScheme
if u.Port() != "" {
u.Host = u.Hostname()
}
fallthrough
- case "http", "https":
+ case httpScheme, httpsScheme:
if strings.HasSuffix(u.Path, ".git") {
u.Path += "/info/lfs"
} else {
@@ -52,7 +52,7 @@ func endpointFromBareSSH(rawurl string) (*url.URL, error) {
parts := strings.Split(rawurl, ":")
partsLen := len(parts)
if partsLen < 2 {
- return url.Parse(rawurl)
+ return url.Parse(rawurl) //nolint:wrapcheck
}
// Treat presence of ':' as a bare URL
@@ -66,5 +66,5 @@ func endpointFromBareSSH(rawurl string) (*url.URL, error) {
newPath = strings.Join(parts, "/")
}
newrawurl := fmt.Sprintf("ssh://%v", newPath)
- return url.Parse(newrawurl)
+ return url.Parse(newrawurl) //nolint:wrapcheck
}
@@ -63,7 +63,7 @@ func (c *httpClient) batch(ctx context.Context, operation string, objects []Poin
err := json.NewEncoder(payload).Encode(request)
if err != nil {
logger.Errorf("Error encoding json: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
logger.Debugf("Calling: %s", url)
@@ -71,7 +71,7 @@ func (c *httpClient) batch(ctx context.Context, operation string, objects []Poin
req, err := http.NewRequestWithContext(ctx, "POST", url, payload)
if err != nil {
logger.Errorf("Error creating request: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
req.Header.Set("Content-type", MediaType)
req.Header.Set("Accept", MediaType)
@@ -80,23 +80,23 @@ func (c *httpClient) batch(ctx context.Context, operation string, objects []Poin
if err != nil {
select {
case <-ctx.Done():
- return nil, ctx.Err()
+ return nil, ctx.Err() //nolint:wrapcheck
default:
}
logger.Errorf("Error while processing request: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
- defer res.Body.Close() // nolint: errcheck
+ defer res.Body.Close() //nolint: errcheck
if res.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("Unexpected server response: %s", res.Status)
+ return nil, fmt.Errorf("unexpected server response: %s", res.Status)
}
var response BatchResponse
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
logger.Errorf("Error decoding json: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
if len(response.Transfer) == 0 {
@@ -128,7 +128,7 @@ func (c *httpClient) performOperation(ctx context.Context, objects []Pointer, dc
}
for _, object := range result.Objects {
- if object.Error != nil {
+ if object.Error != nil { //nolint:nestif
objectError := errors.New(object.Error.Message)
logger.Debugf("Error on object %v: %v", object.Pointer, objectError)
if uc != nil {
@@ -143,7 +143,7 @@ func (c *httpClient) performOperation(ctx context.Context, objects []Pointer, dc
continue
}
- if uc != nil {
+ if uc != nil { //nolint:nestif
if len(object.Actions) == 0 {
logger.Debugf("%v already present on server", object.Pointer)
continue
@@ -152,7 +152,7 @@ func (c *httpClient) performOperation(ctx context.Context, objects []Pointer, dc
link, ok := object.Actions[ActionUpload]
if !ok {
logger.Debugf("%+v", object)
- return errors.New("Missing action 'upload'")
+ return errors.New("missing action 'upload'")
}
content, err := uc(object.Pointer, nil)
@@ -162,28 +162,28 @@ func (c *httpClient) performOperation(ctx context.Context, objects []Pointer, dc
err = transferAdapter.Upload(ctx, object.Pointer, content, link)
- content.Close() // nolint: errcheck
+ content.Close() //nolint:errcheck,gosec
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
link, ok = object.Actions[ActionVerify]
if ok {
if err := transferAdapter.Verify(ctx, object.Pointer, link); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
} else {
link, ok := object.Actions[ActionDownload]
if !ok {
logger.Debugf("%+v", object)
- return errors.New("Missing action 'download'")
+ return errors.New("missing action 'download'")
}
content, err := transferAdapter.Download(ctx, object.Pointer, link)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := dc(object.Pointer, content, nil); err != nil {
@@ -27,22 +27,22 @@ const (
)
var (
- // ErrMissingPrefix occurs if the content lacks the LFS prefix
- ErrMissingPrefix = errors.New("Content lacks the LFS prefix")
+ // ErrMissingPrefix occurs if the content lacks the LFS prefix.
+ ErrMissingPrefix = errors.New("content lacks the LFS prefix")
- // ErrInvalidStructure occurs if the content has an invalid structure
- ErrInvalidStructure = errors.New("Content has an invalid structure")
+ // ErrInvalidStructure occurs if the content has an invalid structure.
+ ErrInvalidStructure = errors.New("content has an invalid structure")
- // ErrInvalidOIDFormat occurs if the oid has an invalid format
+ // ErrInvalidOIDFormat occurs if the oid has an invalid format.
ErrInvalidOIDFormat = errors.New("OID has an invalid format")
)
-// ReadPointer tries to read LFS pointer data from the reader
+// ReadPointer tries to read LFS pointer data from the reader.
func ReadPointer(reader io.Reader) (Pointer, error) {
buf := make([]byte, blobSizeCutoff)
n, err := io.ReadFull(reader, buf)
if err != nil && err != io.ErrUnexpectedEOF {
- return Pointer{}, err
+ return Pointer{}, err //nolint:wrapcheck
}
buf = buf[:n]
@@ -71,7 +71,7 @@ func ReadPointerFromBuffer(buf []byte) (Pointer, error) {
}
size, err := strconv.ParseInt(strings.TrimPrefix(splitLines[2], "size "), 10, 64)
if err != nil {
- return p, err
+ return p, err //nolint:wrapcheck
}
p.Oid = oid
@@ -111,12 +111,12 @@ func (p Pointer) RelativePath() string {
return path.Join(p.Oid[0:2], p.Oid[2:4], p.Oid)
}
-// GeneratePointer generates a pointer for arbitrary content
+// GeneratePointer generates a pointer for arbitrary content.
func GeneratePointer(content io.Reader) (Pointer, error) {
h := sha256.New()
c, err := io.Copy(h, content)
if err != nil {
- return Pointer{}, err
+ return Pointer{}, err //nolint:wrapcheck
}
sum := h.Sum(nil)
return Pointer{Oid: hex.EncodeToString(sum), Size: c}, nil
@@ -14,7 +14,7 @@ import (
"github.com/charmbracelet/soft-serve/git"
)
-// SearchPointerBlobs scans the whole repository for LFS pointer files
+// SearchPointerBlobs scans the whole repository for LFS pointer files.
func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan chan<- PointerBlob, errChan chan<- error) {
basePath := repo.Path
@@ -51,7 +51,7 @@ func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan c
func createPointerResultsFromCatFileBatch(ctx context.Context, catFileBatchReader *io.PipeReader, wg *sync.WaitGroup, pointerChan chan<- PointerBlob) {
defer wg.Done()
- defer catFileBatchReader.Close() // nolint: errcheck
+ defer catFileBatchReader.Close() //nolint: errcheck
bufferedReader := bufio.NewReader(catFileBatchReader)
buf := make([]byte, 1025)
@@ -104,8 +104,8 @@ loop:
func catFileBatch(ctx context.Context, shasToBatchReader *io.PipeReader, catFileBatchWriter *io.PipeWriter, wg *sync.WaitGroup, basePath string) {
defer wg.Done()
- defer shasToBatchReader.Close() // nolint: errcheck
- defer catFileBatchWriter.Close() // nolint: errcheck
+ defer shasToBatchReader.Close() //nolint: errcheck
+ defer catFileBatchWriter.Close() //nolint: errcheck
stderr := new(bytes.Buffer)
var errbuf strings.Builder
@@ -122,7 +122,7 @@ func catFileBatch(ctx context.Context, shasToBatchReader *io.PipeReader, catFile
func blobsLessThan1024FromCatFileBatchCheck(catFileCheckReader *io.PipeReader, shasToBatchWriter *io.PipeWriter, wg *sync.WaitGroup) {
defer wg.Done()
- defer catFileCheckReader.Close() // nolint: errcheck
+ defer catFileCheckReader.Close() //nolint: errcheck
scanner := bufio.NewScanner(catFileCheckReader)
defer func() {
_ = shasToBatchWriter.CloseWithError(scanner.Err())
@@ -154,8 +154,8 @@ func blobsLessThan1024FromCatFileBatchCheck(catFileCheckReader *io.PipeReader, s
func catFileBatchCheck(ctx context.Context, shasToCheckReader *io.PipeReader, catFileCheckWriter *io.PipeWriter, wg *sync.WaitGroup, basePath string) {
defer wg.Done()
- defer shasToCheckReader.Close() // nolint: errcheck
- defer catFileCheckWriter.Close() // nolint: errcheck
+ defer shasToCheckReader.Close() //nolint: errcheck
+ defer catFileCheckWriter.Close() //nolint: errcheck
stderr := new(bytes.Buffer)
var errbuf strings.Builder
@@ -172,7 +172,7 @@ func catFileBatchCheck(ctx context.Context, shasToCheckReader *io.PipeReader, ca
func blobsFromRevListObjects(revListReader *io.PipeReader, shasToCheckWriter *io.PipeWriter, wg *sync.WaitGroup) {
defer wg.Done()
- defer revListReader.Close() // nolint: errcheck
+ defer revListReader.Close() //nolint: errcheck
scanner := bufio.NewScanner(revListReader)
defer func() {
_ = shasToCheckWriter.CloseWithError(scanner.Err())
@@ -201,7 +201,7 @@ func blobsFromRevListObjects(revListReader *io.PipeReader, shasToCheckWriter *io
func revListAllObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync.WaitGroup, basePath string, errChan chan<- error) {
defer wg.Done()
- defer revListWriter.Close() // nolint: errcheck
+ defer revListWriter.Close() //nolint: errcheck
stderr := new(bytes.Buffer)
var errbuf strings.Builder
@@ -8,7 +8,7 @@ import (
// TransferBasic is the name of the Git LFS basic transfer protocol.
const TransferBasic = "basic"
-// TransferAdapter represents an adapter for downloading/uploading LFS objects
+// TransferAdapter represents an adapter for downloading/uploading LFS objects.
type TransferAdapter interface {
Name() string
Download(ctx context.Context, p Pointer, l *Link) (io.ReadCloser, error)
@@ -1,3 +1,4 @@
+// Package log provides logging functionality for soft-serve.
package log
import (
@@ -41,9 +42,9 @@ func NewLogger(cfg *config.Config) (*log.Logger, *os.File, error) {
var f *os.File
if cfg.Log.Path != "" {
var err error
- f, err = os.OpenFile(cfg.Log.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
+ f, err = os.OpenFile(cfg.Log.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) //nolint:gosec
if err != nil {
- return nil, nil, err
+ return nil, nil, err //nolint:wrapcheck
}
logger.SetOutput(f)
}
@@ -1,3 +1,4 @@
+// Package proto provides protocol buffer definitions and utilities.
package proto
import "time"
@@ -49,12 +49,12 @@ type RepositoryOptions struct {
func RepositoryDefaultBranch(repo Repository) (string, error) {
r, err := repo.Open()
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
ref, err := r.HEAD()
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return ref.Name().Short(), nil
@@ -1,3 +1,4 @@
+// Package cmd provides SSH command implementations.
package cmd
import (
@@ -44,30 +45,30 @@ func blobCommand() *cobra.Command {
repo, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := repo.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if ref == "" {
head, err := r.HEAD()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
ref = head.ID
}
tree, err := r.LsTree(ref)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
te, err := tree.TreeEntry(fp)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if te.Type() != "blob" {
@@ -76,12 +77,12 @@ func blobCommand() *cobra.Command {
bts, err := te.Contents()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
c := string(bts)
isBin, _ := te.File().IsBinary()
- if isBin {
+ if isBin { //nolint:nestif
if raw {
cmd.Println(c)
} else {
@@ -91,7 +92,7 @@ func blobCommand() *cobra.Command {
if color && !noColor {
c, err = common.FormatHighlight(fp, c)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -39,12 +39,12 @@ func branchListCommand() *cobra.Command {
rn := strings.TrimSuffix(args[0], ".git")
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
branches, _ := r.Branches()
@@ -73,17 +73,17 @@ func branchDefaultCommand() *cobra.Command {
case 1:
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
head, err := r.HEAD()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(head.Name().Short())
@@ -94,12 +94,12 @@ func branchDefaultCommand() *cobra.Command {
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
branch := args[1]
@@ -121,14 +121,14 @@ func branchDefaultCommand() *cobra.Command {
Context: ctx,
},
}); err != nil {
- return err
+ return err //nolint:wrapcheck
}
// TODO: move this to backend?
user := proto.UserFromContext(ctx)
wh, err := webhook.NewRepositoryEvent(ctx, user, rr, webhook.RepositoryEventActionDefaultBranchChange)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return webhook.SendEvent(ctx, wh)
@@ -154,12 +154,12 @@ func branchDeleteCommand() *cobra.Command {
rn := strings.TrimSuffix(args[0], ".git")
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
branch := args[1]
@@ -178,7 +178,7 @@ func branchDeleteCommand() *cobra.Command {
head, err := r.HEAD()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if head.Name().Short() == branch {
@@ -187,16 +187,16 @@ func branchDeleteCommand() *cobra.Command {
branchCommit, err := r.BranchCommit(branch)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := r.DeleteBranch(branch, gitm.DeleteBranchOptions{Force: true}); err != nil {
- return err
+ return err //nolint:wrapcheck
}
wh, err := webhook.NewBranchTagEvent(ctx, proto.UserFromContext(ctx), rr, git.RefsHeads+branch, branchCommit.ID.String(), git.ZeroID)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return webhook.SendEvent(ctx, wh)
@@ -82,7 +82,7 @@ func UsageFunc(c *cobra.Command) error {
t := template.New("usage")
t.Funcs(templateFuncs)
template.Must(t.Parse(c.UsageTemplate()))
- return t.Execute(c.OutOrStderr(), struct {
+ return t.Execute(c.OutOrStderr(), struct { //nolint:wrapcheck
*cobra.Command
SSHCommand string
}{
@@ -80,7 +80,7 @@ func collabListCommand() *cobra.Command {
repo := args[0]
collabs, err := be.Collaborators(ctx, repo)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, c := range collabs {
@@ -31,27 +31,27 @@ func commitCommand() *cobra.Command {
rr, err := be.Repository(ctx, repoName)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
commit, err := r.CommitByRevision(commitSHA)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
patch, err := r.Patch(commit)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
diff, err := r.Diff(commit)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
commonStyle := styles.DefaultStyles()
@@ -34,7 +34,7 @@ func createCommand() *cobra.Command {
Hidden: hidden,
})
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cloneurl := fmt.Sprintf("%s/%s.git", cfg.SSH.PublicURL, r.Name())
@@ -22,7 +22,7 @@ func descriptionCommand() *cobra.Command {
case 1:
desc, err := be.Description(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(desc)
@@ -31,7 +31,7 @@ func descriptionCommand() *cobra.Command {
return err
}
if err := be.SetDescription(ctx, rn, strings.Join(args[1:], " ")); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -182,7 +182,7 @@ func gitRunE(cmd *cobra.Command, args []string) error {
repoDir := name + ".git"
reposDir := filepath.Join(cfg.DataPath, "repos")
if err := git.EnsureWithin(reposDir, repoDir); err != nil {
- return err
+ return err //nolint:wrapcheck
}
// Set repo in context
@@ -240,7 +240,7 @@ func gitRunE(cmd *cobra.Command, args []string) error {
if repo == nil {
if _, err := be.CreateRepository(ctx, name, user, proto.RepositoryOptions{Private: false}); err != nil {
log.Errorf("failed to create repo: %s", err)
- return err
+ return err //nolint:wrapcheck
}
createRepoCounter.WithLabelValues(name).Inc()
}
@@ -250,7 +250,7 @@ func gitRunE(cmd *cobra.Command, args []string) error {
defer func() {
if repo == nil {
// If the repo was created, but the request failed, delete it.
- be.DeleteRepository(ctx, name) // nolint: errcheck
+ be.DeleteRepository(ctx, name) //nolint:errcheck,gosec
}
}()
@@ -274,7 +274,7 @@ func gitRunE(cmd *cobra.Command, args []string) error {
return git.ErrInvalidRepo
}
- switch service {
+ switch service { //nolint:exhaustive
case git.UploadArchiveService:
uploadArchiveCounter.WithLabelValues(name).Inc()
defer func() {
@@ -320,7 +320,7 @@ func gitRunE(cmd *cobra.Command, args []string) error {
args[1],
}
- switch service {
+ switch service { //nolint:exhaustive
case git.LFSTransferService:
lfsTransferCounter.WithLabelValues(name, operation).Inc()
defer func() {
@@ -20,7 +20,7 @@ func hiddenCommand() *cobra.Command {
case 1:
hidden, err := be.IsHidden(ctx, repo)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(hidden)
@@ -31,7 +31,7 @@ func hiddenCommand() *cobra.Command {
hidden := args[1] == "true"
if err := be.SetHidden(ctx, repo, hidden); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -43,7 +43,7 @@ func importCommand() *cobra.Command {
return errors.New("import already in progress")
}
- return err
+ return err //nolint:wrapcheck
}
return nil
@@ -6,7 +6,7 @@ import (
"github.com/spf13/cobra"
)
-// InfoCommand returns a command that shows the user's info
+// InfoCommand returns a command that shows the user's info.
func InfoCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "info",
@@ -18,7 +18,7 @@ func InfoCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
user, err := be.UserByPublicKey(ctx, pk)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Printf("Username: %s\n", user.Username())
@@ -22,7 +22,7 @@ func JWTCommand() *cobra.Command {
cfg := config.FromContext(ctx)
kp, err := jwk.NewPair(cfg)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
user := proto.UserFromContext(ctx)
@@ -45,7 +45,7 @@ func JWTCommand() *cobra.Command {
token.Header["kid"] = kp.JWK().KeyID
j, err := token.SignedString(kp.PrivateKey())
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(j)
@@ -22,7 +22,7 @@ func listCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
repos, err := be.Repositories(ctx)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, r := range repos {
if be.AccessLevelByPublicKey(ctx, r.Name(), pk) >= access.ReadOnlyAccess {
@@ -17,7 +17,7 @@ func mirrorCommand() *cobra.Command {
rn := args[0]
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
isMirror := rr.IsMirror()
@@ -23,20 +23,20 @@ func privateCommand() *cobra.Command {
case 1:
isPrivate, err := be.IsPrivate(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(isPrivate)
case 2:
isPrivate, err := strconv.ParseBool(args[1])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := checkIfCollab(cmd, args); err != nil {
return err
}
if err := be.SetPrivate(ctx, rn, isPrivate); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
return nil
@@ -22,7 +22,7 @@ func projectName() *cobra.Command {
case 1:
pn, err := be.ProjectName(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.Println(pn)
@@ -31,7 +31,7 @@ func projectName() *cobra.Command {
return err
}
if err := be.SetProjectName(ctx, rn, strings.Join(args[1:], " ")); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -26,12 +26,12 @@ func PubkeyCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
user, err := be.UserByPublicKey(ctx, pk)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
apk, _, err := sshutils.ParseAuthorizedKey(strings.Join(args, " "))
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return be.AddPublicKey(ctx, user.Username(), apk)
@@ -48,12 +48,12 @@ func PubkeyCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
user, err := be.UserByPublicKey(ctx, pk)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
apk, _, err := sshutils.ParseAuthorizedKey(strings.Join(args, " "))
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return be.RemovePublicKey(ctx, user.Username(), apk)
@@ -71,7 +71,7 @@ func PubkeyCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
user, err := be.UserByPublicKey(ctx, pk)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
pks := user.PublicKeys()
@@ -49,24 +49,24 @@ func RepoCommand() *cobra.Command {
rn := args[0]
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
head, err := r.HEAD()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
var owner proto.User
if rr.UserID() > 0 {
owner, err = be.UserByID(ctx, rr.UserID())
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -18,7 +18,7 @@ func SetUsernameCommand() *cobra.Command {
pk := sshutils.PublicKeyFromContext(ctx)
user, err := be.UserByPublicKey(ctx, pk)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return be.SetUsername(ctx, user.Username(), args[0])
@@ -31,7 +31,7 @@ func SettingsCommand() *cobra.Command {
case 1:
v, _ := strconv.ParseBool(args[0])
if err := be.SetAllowKeyless(ctx, v); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -60,7 +60,7 @@ func SettingsCommand() *cobra.Command {
return fmt.Errorf("invalid access level: %s. Please choose one of the following: %s", args[0], als)
}
if err := be.SetAnonAccess(ctx, al); err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -38,12 +38,12 @@ func tagListCommand() *cobra.Command {
rn := strings.TrimSuffix(args[0], ".git")
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
tags, _ := r.Tags()
@@ -71,13 +71,13 @@ func tagDeleteCommand() *cobra.Command {
rn := strings.TrimSuffix(args[0], ".git")
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
log.Errorf("failed to open repo: %s", err)
- return err
+ return err //nolint:wrapcheck
}
tag := args[1]
@@ -98,18 +98,18 @@ func tagDeleteCommand() *cobra.Command {
tagCommit, err := r.TagCommit(tag)
if err != nil {
log.Errorf("failed to get tag commit: %s", err)
- return err
+ return err //nolint:wrapcheck
}
if err := r.DeleteTag(tag); err != nil {
log.Errorf("failed to delete tag: %s", err)
- return err
+ return err //nolint:wrapcheck
}
wh, err := webhook.NewBranchTagEvent(ctx, proto.UserFromContext(ctx), rr, git.RefsTags+tag, tagCommit.ID.String(), git.ZeroID)
if err != nil {
log.Error("failed to create branch_tag webhook", "err", err)
- return err
+ return err //nolint:wrapcheck
}
return webhook.SendEvent(ctx, wh)
@@ -41,7 +41,7 @@ func TokenCommand() *cobra.Command {
if createExpiresIn != "" {
d, err := duration.Parse(createExpiresIn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
expiresIn = d
@@ -50,7 +50,7 @@ func TokenCommand() *cobra.Command {
token, err := be.CreateAccessToken(ctx, user, name, expiresAt)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
notice := "Access token created"
@@ -83,7 +83,7 @@ func TokenCommand() *cobra.Command {
tokens, err := be.ListAccessTokens(ctx, user)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if len(tokens) == 0 {
@@ -130,11 +130,11 @@ func TokenCommand() *cobra.Command {
id, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if err := be.DeleteAccessToken(ctx, user, id); err != nil {
- return err
+ return err //nolint:wrapcheck
}
cmd.PrintErrln("Access token deleted")
@@ -33,12 +33,12 @@ func treeCommand() *cobra.Command {
}
rr, err := be.Repository(ctx, rn)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
r, err := rr.Open()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if ref == "" {
@@ -47,7 +47,7 @@ func treeCommand() *cobra.Command {
if bs, err := r.Branches(); err != nil && len(bs) == 0 {
return fmt.Errorf("repository is empty")
}
- return err
+ return err //nolint:wrapcheck
}
ref = head.ID
@@ -55,26 +55,26 @@ func treeCommand() *cobra.Command {
tree, err := r.LsTree(ref)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
ents := git.Entries{}
- if path != "" && path != "/" {
+ if path != "" && path != "/" { //nolint:nestif
te, err := tree.TreeEntry(path)
if err == git.ErrRevisionNotExist {
return proto.ErrFileNotFound
}
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
if te.Type() == "tree" {
tree, err = tree.SubTree(path)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
ents, err = tree.Entries()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
} else {
ents = append(ents, te)
@@ -82,7 +82,7 @@ func treeCommand() *cobra.Command {
} else {
ents, err = tree.Entries()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
ents.Sort()
@@ -34,7 +34,7 @@ func UserCommand() *cobra.Command {
if key != "" {
pk, _, err := sshutils.ParseAuthorizedKey(key)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
pubkeys = []ssh.PublicKey{pk}
@@ -46,7 +46,7 @@ func UserCommand() *cobra.Command {
}
_, err := be.CreateUser(ctx, username, opts)
- return err
+ return err //nolint:wrapcheck
},
}
@@ -78,7 +78,7 @@ func UserCommand() *cobra.Command {
be := backend.FromContext(ctx)
users, err := be.Users(ctx)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
sort.Strings(users)
@@ -102,7 +102,7 @@ func UserCommand() *cobra.Command {
pubkey := strings.Join(args[1:], " ")
pk, _, err := sshutils.ParseAuthorizedKey(pubkey)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return be.AddPublicKey(ctx, username, pk)
@@ -121,7 +121,7 @@ func UserCommand() *cobra.Command {
pubkey := strings.Join(args[1:], " ")
pk, _, err := sshutils.ParseAuthorizedKey(pubkey)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
return be.RemovePublicKey(ctx, username, pk)
@@ -154,7 +154,7 @@ func UserCommand() *cobra.Command {
user, err := be.User(ctx, username)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
isAdmin := user.IsAdmin()
@@ -52,12 +52,12 @@ func webhookListCommand() *cobra.Command {
be := backend.FromContext(ctx)
repo, err := be.Repository(ctx, args[0])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
webhooks, err := be.ListWebhooks(ctx, repo)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
table := table.New().Headers("ID", "URL", "Events", "Active", "Created At", "Updated At")
@@ -99,7 +99,7 @@ func webhookCreateCommand() *cobra.Command {
be := backend.FromContext(ctx)
repo, err := be.Repository(ctx, args[0])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
var evs []webhook.Event
@@ -145,7 +145,7 @@ func webhookDeleteCommand() *cobra.Command {
be := backend.FromContext(ctx)
repo, err := be.Repository(ctx, args[0])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
id, err := strconv.ParseInt(args[1], 10, 64)
@@ -176,7 +176,7 @@ func webhookUpdateCommand() *cobra.Command {
be := backend.FromContext(ctx)
repo, err := be.Repository(ctx, args[0])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
id, err := strconv.ParseInt(args[1], 10, 64)
@@ -186,7 +186,7 @@ func webhookUpdateCommand() *cobra.Command {
wh, err := be.Webhook(ctx, repo, id)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
newURL := wh.URL
@@ -283,7 +283,7 @@ func webhookDeliveriesListCommand() *cobra.Command {
dels, err := be.ListWebhookDeliveries(ctx, id)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
table := table.New().Headers("Status", "ID", "Event", "Created At")
@@ -317,7 +317,7 @@ func webhookDeliveriesRedeliverCommand() *cobra.Command {
be := backend.FromContext(ctx)
repo, err := be.Repository(ctx, args[0])
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
id, err := strconv.ParseInt(args[1], 10, 64)
@@ -357,7 +357,7 @@ func webhookDeliveriesGetCommand() *cobra.Command {
del, err := be.WebhookDelivery(ctx, id, delID)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
out := cmd.OutOrStdout()
@@ -1,3 +1,4 @@
+// Package ssh provides SSH server functionality and middleware.
package ssh
import (
@@ -135,7 +136,7 @@ func CommandMiddleware(sh ssh.Handler) ssh.Handler {
rootCmd.SetContext(ctx)
if err := rootCmd.ExecuteContext(ctx); err != nil {
- s.Exit(1) // nolint: errcheck
+ s.Exit(1) //nolint:errcheck,gosec
return
}
}
@@ -41,7 +41,7 @@ var (
)
// SSHServer is a SSH server that implements the git protocol.
-type SSHServer struct { // nolint: revive
+type SSHServer struct { //nolint: revive
srv *ssh.Server
cfg *config.Config
be *backend.Backend
@@ -97,7 +97,7 @@ func NewSSHServer(ctx context.Context) (*SSHServer, error) {
s.srv, err = wish.NewServer(opts...)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
if config.IsDebug() {
@@ -131,22 +131,22 @@ func NewSSHServer(ctx context.Context) (*SSHServer, error) {
// ListenAndServe starts the SSH server.
func (s *SSHServer) ListenAndServe() error {
- return s.srv.ListenAndServe()
+ return s.srv.ListenAndServe() //nolint:wrapcheck
}
// Serve starts the SSH server on the given net.Listener.
func (s *SSHServer) Serve(l net.Listener) error {
- return s.srv.Serve(l)
+ return s.srv.Serve(l) //nolint:wrapcheck
}
// Close closes the SSH server.
func (s *SSHServer) Close() error {
- return s.srv.Close()
+ return s.srv.Close() //nolint:wrapcheck
}
// Shutdown gracefully shuts down the SSH server.
func (s *SSHServer) Shutdown(ctx context.Context) error {
- return s.srv.Shutdown(ctx)
+ return s.srv.Shutdown(ctx) //nolint:wrapcheck
}
func initializePermissions(ctx ssh.Context) {
@@ -157,12 +157,12 @@ func initializePermissions(ctx ssh.Context) {
if perms.Extensions == nil {
perms.Extensions = make(map[string]string)
}
- if perms.Permissions.Extensions == nil {
- perms.Permissions.Extensions = make(map[string]string)
+ if perms.Extensions == nil {
+ perms.Extensions = make(map[string]string)
}
}
-// PublicKeyAuthHandler handles public key authentication.
+// PublicKeyHandler handles public key authentication.
func (s *SSHServer) PublicKeyHandler(ctx ssh.Context, pk ssh.PublicKey) (allowed bool) {
if pk == nil {
return false
@@ -86,7 +86,7 @@ func (ui *UI) getMargins() (wm, hm int) {
// ShortHelp implements help.KeyMap.
func (ui *UI) ShortHelp() []key.Binding {
b := make([]key.Binding, 0)
- switch ui.state {
+ switch ui.state { //nolint:exhaustive
case errorState:
b = append(b, ui.common.KeyMap.Back)
case readyState:
@@ -102,7 +102,7 @@ func (ui *UI) ShortHelp() []key.Binding {
// FullHelp implements help.KeyMap.
func (ui *UI) FullHelp() [][]key.Binding {
b := make([][]key.Binding, 0)
- switch ui.state {
+ switch ui.state { //nolint:exhaustive
case errorState:
b = append(b, []key.Binding{ui.common.KeyMap.Back})
case readyState:
@@ -300,7 +300,7 @@ func (ui *UI) openRepo(rn string) (proto.Repository, error) {
repos, err := be.Repositories(ctx)
if err != nil {
ui.common.Logger.Debugf("ui: failed to list repos: %v", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
for _, r := range repos {
if r.Name() == rn {
@@ -1,3 +1,4 @@
+// Package sshutils provides SSH utility functions.
package sshutils
import (
@@ -11,7 +12,7 @@ import (
// ParseAuthorizedKey parses an authorized key string into a public key.
func ParseAuthorizedKey(ak string) (gossh.PublicKey, string, error) {
pk, c, _, _, err := gossh.ParseAuthorizedKey([]byte(ak))
- return pk, c, err
+ return pk, c, err //nolint:wrapcheck
}
// MarshalAuthorizedKey marshals a public key into an authorized key string.
@@ -1,3 +1,4 @@
+// Package stats provides statistics functionality.
package stats
import (
@@ -37,15 +38,15 @@ func NewStatsServer(ctx context.Context) (*StatsServer, error) {
// ListenAndServe starts the StatsServer.
func (s *StatsServer) ListenAndServe() error {
- return s.server.ListenAndServe()
+ return s.server.ListenAndServe() //nolint:wrapcheck
}
// Shutdown gracefully shuts down the StatsServer.
func (s *StatsServer) Shutdown(ctx context.Context) error {
- return s.server.Shutdown(ctx)
+ return s.server.Shutdown(ctx) //nolint:wrapcheck
}
// Close closes the StatsServer.
func (s *StatsServer) Close() error {
- return s.server.Close()
+ return s.server.Close() //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package storage provides storage functionality.
package storage
import (
@@ -25,34 +26,34 @@ func NewLocalStorage(root string) *LocalStorage {
// Delete implements Storage.
func (l *LocalStorage) Delete(name string) error {
name = l.fixPath(name)
- return os.Remove(name)
+ return os.Remove(name) //nolint:wrapcheck
}
// Open implements Storage.
func (l *LocalStorage) Open(name string) (Object, error) {
name = l.fixPath(name)
- return os.Open(name)
+ return os.Open(name) //nolint:wrapcheck
}
// Stat implements Storage.
func (l *LocalStorage) Stat(name string) (fs.FileInfo, error) {
name = l.fixPath(name)
- return os.Stat(name)
+ return os.Stat(name) //nolint:wrapcheck
}
// Put implements Storage.
func (l *LocalStorage) Put(name string, r io.Reader) (int64, error) {
name = l.fixPath(name)
- if err := os.MkdirAll(filepath.Dir(name), os.ModePerm); err != nil {
- return 0, err
+ if err := os.MkdirAll(filepath.Dir(name), os.ModePerm); err != nil { //nolint:gosec
+ return 0, err //nolint:wrapcheck
}
f, err := os.Create(name)
if err != nil {
- return 0, err
+ return 0, err //nolint:wrapcheck
}
- defer f.Close() // nolint: errcheck
- return io.Copy(f, r)
+ defer f.Close() //nolint:errcheck
+ return io.Copy(f, r) //nolint:wrapcheck
}
// Exists implements Storage.
@@ -65,21 +66,21 @@ func (l *LocalStorage) Exists(name string) (bool, error) {
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
- return false, err
+ return false, err //nolint:wrapcheck
}
// Rename implements Storage.
func (l *LocalStorage) Rename(oldName, newName string) error {
oldName = l.fixPath(oldName)
newName = l.fixPath(newName)
- if err := os.MkdirAll(filepath.Dir(newName), os.ModePerm); err != nil {
- return err
+ if err := os.MkdirAll(filepath.Dir(newName), os.ModePerm); err != nil { //nolint:gosec
+ return err //nolint:wrapcheck
}
- return os.Rename(oldName, newName)
+ return os.Rename(oldName, newName) //nolint:wrapcheck
}
-// Replace all slashes with the OS-specific separator
+// Replace all slashes with the OS-specific separator.
func (l LocalStorage) fixPath(path string) string {
path = strings.ReplaceAll(path, "/", string(os.PathSeparator))
if !filepath.IsAbs(path) {
@@ -1,3 +1,4 @@
+// Package store provides data store functionality.
package store
import (
@@ -1,3 +1,4 @@
+// Package database provides database store implementations.
package database
import (
@@ -29,7 +30,7 @@ func (s *accessTokenStore) CreateAccessToken(ctx context.Context, h db.Handler,
var id int64
if err := h.GetContext(ctx, &id, h.Rebind(query), values...); err != nil {
- return models.AccessToken{}, err
+ return models.AccessToken{}, err //nolint:wrapcheck
}
return s.GetAccessToken(ctx, h, id)
@@ -39,14 +40,14 @@ func (s *accessTokenStore) CreateAccessToken(ctx context.Context, h db.Handler,
func (*accessTokenStore) DeleteAccessToken(ctx context.Context, h db.Handler, id int64) error {
query := h.Rebind(`DELETE FROM access_tokens WHERE id = ?`)
_, err := h.ExecContext(ctx, query, id)
- return err
+ return err //nolint:wrapcheck
}
// DeleteAccessTokenForUser implements store.AccessTokenStore.
func (*accessTokenStore) DeleteAccessTokenForUser(ctx context.Context, h db.Handler, userID int64, id int64) error {
query := h.Rebind(`DELETE FROM access_tokens WHERE user_id = ? AND id = ?`)
_, err := h.ExecContext(ctx, query, userID, id)
- return err
+ return err //nolint:wrapcheck
}
// GetAccessToken implements store.AccessTokenStore.
@@ -54,7 +55,7 @@ func (*accessTokenStore) GetAccessToken(ctx context.Context, h db.Handler, id in
query := h.Rebind(`SELECT * FROM access_tokens WHERE id = ?`)
var m models.AccessToken
err := h.GetContext(ctx, &m, query, id)
- return m, err
+ return m, err //nolint:wrapcheck
}
// GetAccessTokensByUserID implements store.AccessTokenStore.
@@ -62,7 +63,7 @@ func (*accessTokenStore) GetAccessTokensByUserID(ctx context.Context, h db.Handl
query := h.Rebind(`SELECT * FROM access_tokens WHERE user_id = ?`)
var m []models.AccessToken
err := h.SelectContext(ctx, &m, query, userID)
- return m, err
+ return m, err //nolint:wrapcheck
}
// GetAccessTokenByToken implements store.AccessTokenStore.
@@ -70,5 +71,5 @@ func (*accessTokenStore) GetAccessTokenByToken(ctx context.Context, h db.Handler
query := h.Rebind(`SELECT * FROM access_tokens WHERE token = ?`)
var m models.AccessToken
err := h.GetContext(ctx, &m, query, token)
- return m, err
+ return m, err //nolint:wrapcheck
}
@@ -19,7 +19,7 @@ var _ store.CollaboratorStore = (*collabStore)(nil)
func (*collabStore) AddCollabByUsernameAndRepo(ctx context.Context, tx db.Handler, username string, repo string, level access.AccessLevel) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
repo = utils.SanitizeRepo(repo)
@@ -36,7 +36,7 @@ func (*collabStore) AddCollabByUsernameAndRepo(ctx context.Context, tx db.Handle
CURRENT_TIMESTAMP
);`)
_, err := tx.ExecContext(ctx, query, level, username, repo)
- return err
+ return err //nolint:wrapcheck
}
// GetCollabByUsernameAndRepo implements store.CollaboratorStore.
@@ -45,7 +45,7 @@ func (*collabStore) GetCollabByUsernameAndRepo(ctx context.Context, tx db.Handle
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return models.Collab{}, err
+ return models.Collab{}, err //nolint:wrapcheck
}
repo = utils.SanitizeRepo(repo)
@@ -61,7 +61,7 @@ func (*collabStore) GetCollabByUsernameAndRepo(ctx context.Context, tx db.Handle
users.username = ? AND repos.name = ?
`), username, repo)
- return m, err
+ return m, err //nolint:wrapcheck
}
// ListCollabsByRepo implements store.CollaboratorStore.
@@ -80,7 +80,7 @@ func (*collabStore) ListCollabsByRepo(ctx context.Context, tx db.Handler, repo s
`)
err := tx.SelectContext(ctx, &m, query, repo)
- return m, err
+ return m, err //nolint:wrapcheck
}
// ListCollabsByRepoAsUsers implements store.CollaboratorStore.
@@ -100,14 +100,14 @@ func (*collabStore) ListCollabsByRepoAsUsers(ctx context.Context, tx db.Handler,
`)
err := tx.SelectContext(ctx, &m, query, repo)
- return m, err
+ return m, err //nolint:wrapcheck
}
// RemoveCollabByUsernameAndRepo implements store.CollaboratorStore.
func (*collabStore) RemoveCollabByUsernameAndRepo(ctx context.Context, tx db.Handler, username string, repo string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
repo = utils.SanitizeRepo(repo)
@@ -122,5 +122,5 @@ func (*collabStore) RemoveCollabByUsernameAndRepo(ctx context.Context, tx db.Han
)
`)
_, err := tx.ExecContext(ctx, query, username, repo)
- return err
+ return err //nolint:wrapcheck
}
@@ -32,7 +32,7 @@ func (*lfsStore) CreateLFSLockForUser(ctx context.Context, tx db.Handler, repoID
);
`)
_, err := tx.ExecContext(ctx, query, repoID, userID, path, refname)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// GetLFSLocks implements store.LFSStore.
@@ -50,7 +50,7 @@ func (*lfsStore) GetLFSLocks(ctx context.Context, tx db.Handler, repoID int64, p
LIMIT ? OFFSET ?;
`)
err := tx.SelectContext(ctx, &locks, query, repoID, limit, (page-1)*limit)
- return locks, db.WrapError(err)
+ return locks, db.WrapError(err) //nolint:wrapcheck
}
func (s *lfsStore) GetLFSLocksWithCount(ctx context.Context, tx db.Handler, repoID int64, page int, limit int) ([]models.LFSLock, int64, error) {
@@ -67,7 +67,7 @@ func (s *lfsStore) GetLFSLocksWithCount(ctx context.Context, tx db.Handler, repo
`)
err = tx.GetContext(ctx, &count, query, repoID)
if err != nil {
- return nil, 0, db.WrapError(err)
+ return nil, 0, db.WrapError(err) //nolint:wrapcheck
}
return locks, count, nil
@@ -82,7 +82,7 @@ func (*lfsStore) GetLFSLocksForUser(ctx context.Context, tx db.Handler, repoID i
WHERE repo_id = ? AND user_id = ?;
`)
err := tx.SelectContext(ctx, &locks, query, repoID, userID)
- return locks, db.WrapError(err)
+ return locks, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSLocksForPath implements store.LFSStore.
@@ -95,7 +95,7 @@ func (*lfsStore) GetLFSLockForPath(ctx context.Context, tx db.Handler, repoID in
WHERE repo_id = ? AND path = ?;
`)
err := tx.GetContext(ctx, &lock, query, repoID, path)
- return lock, db.WrapError(err)
+ return lock, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSLockForUserPath implements store.LFSStore.
@@ -108,7 +108,7 @@ func (*lfsStore) GetLFSLockForUserPath(ctx context.Context, tx db.Handler, repoI
WHERE repo_id = ? AND user_id = ? AND path = ?;
`)
err := tx.GetContext(ctx, &lock, query, repoID, userID, path)
- return lock, db.WrapError(err)
+ return lock, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSLockByID implements store.LFSStore.
@@ -120,7 +120,7 @@ func (*lfsStore) GetLFSLockByID(ctx context.Context, tx db.Handler, id int64) (m
WHERE lfs_locks.id = ?;
`)
err := tx.GetContext(ctx, &lock, query, id)
- return lock, db.WrapError(err)
+ return lock, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSLockForUserByID implements store.LFSStore.
@@ -132,7 +132,7 @@ func (*lfsStore) GetLFSLockForUserByID(ctx context.Context, tx db.Handler, repoI
WHERE id = ? AND user_id = ? AND repo_id = ?;
`)
err := tx.GetContext(ctx, &lock, query, id, userID, repoID)
- return lock, db.WrapError(err)
+ return lock, db.WrapError(err) //nolint:wrapcheck
}
// DeleteLFSLockForUserByID implements store.LFSStore.
@@ -142,7 +142,7 @@ func (*lfsStore) DeleteLFSLockForUserByID(ctx context.Context, tx db.Handler, re
WHERE repo_id = ? AND user_id = ? AND id = ?;
`)
_, err := tx.ExecContext(ctx, query, repoID, userID, id)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// DeleteLFSLock implements store.LFSStore.
@@ -152,21 +152,21 @@ func (*lfsStore) DeleteLFSLock(ctx context.Context, tx db.Handler, repoID int64,
WHERE repo_id = ? AND id = ?;
`)
_, err := tx.ExecContext(ctx, query, repoID, id)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// CreateLFSObject implements store.LFSStore.
func (*lfsStore) CreateLFSObject(ctx context.Context, tx db.Handler, repoID int64, oid string, size int64) error {
query := tx.Rebind(`INSERT INTO lfs_objects (repo_id, oid, size, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP);`)
_, err := tx.ExecContext(ctx, query, repoID, oid, size)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// DeleteLFSObjectByOid implements store.LFSStore.
func (*lfsStore) DeleteLFSObjectByOid(ctx context.Context, tx db.Handler, repoID int64, oid string) error {
query := tx.Rebind(`DELETE FROM lfs_objects WHERE repo_id = ? AND oid = ?;`)
_, err := tx.ExecContext(ctx, query, repoID, oid)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// GetLFSObjectByOid implements store.LFSStore.
@@ -174,7 +174,7 @@ func (*lfsStore) GetLFSObjectByOid(ctx context.Context, tx db.Handler, repoID in
var obj models.LFSObject
query := tx.Rebind(`SELECT * FROM lfs_objects WHERE repo_id = ? AND oid = ?;`)
err := tx.GetContext(ctx, &obj, query, repoID, oid)
- return obj, db.WrapError(err)
+ return obj, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSObjects implements store.LFSStore.
@@ -182,7 +182,7 @@ func (*lfsStore) GetLFSObjects(ctx context.Context, tx db.Handler, repoID int64)
var objs []models.LFSObject
query := tx.Rebind(`SELECT * FROM lfs_objects WHERE repo_id = ?;`)
err := tx.SelectContext(ctx, &objs, query, repoID)
- return objs, db.WrapError(err)
+ return objs, db.WrapError(err) //nolint:wrapcheck
}
// GetLFSObjectsByName implements store.LFSStore.
@@ -195,5 +195,5 @@ func (*lfsStore) GetLFSObjectsByName(ctx context.Context, tx db.Handler, name st
WHERE repos.name = ?;
`)
err := tx.SelectContext(ctx, &objs, query, name)
- return objs, db.WrapError(err)
+ return objs, db.WrapError(err) //nolint:wrapcheck
}
@@ -29,7 +29,7 @@ func (*repoStore) CreateRepo(ctx context.Context, tx db.Handler, name string, us
query = tx.Rebind(query)
_, err := tx.ExecContext(ctx, query, values...)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// DeleteRepoByName implements store.RepositoryStore.
@@ -37,7 +37,7 @@ func (*repoStore) DeleteRepoByName(ctx context.Context, tx db.Handler, name stri
name = utils.SanitizeRepo(name)
query := tx.Rebind("DELETE FROM repos WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// GetAllRepos implements store.RepositoryStore.
@@ -45,7 +45,7 @@ func (*repoStore) GetAllRepos(ctx context.Context, tx db.Handler) ([]models.Repo
var repos []models.Repo
query := tx.Rebind("SELECT * FROM repos;")
err := tx.SelectContext(ctx, &repos, query)
- return repos, db.WrapError(err)
+ return repos, db.WrapError(err) //nolint:wrapcheck
}
// GetUserRepos implements store.RepositoryStore.
@@ -53,7 +53,7 @@ func (*repoStore) GetUserRepos(ctx context.Context, tx db.Handler, userID int64)
var repos []models.Repo
query := tx.Rebind("SELECT * FROM repos WHERE user_id = ?;")
err := tx.SelectContext(ctx, &repos, query, userID)
- return repos, db.WrapError(err)
+ return repos, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoByName implements store.RepositoryStore.
@@ -62,7 +62,7 @@ func (*repoStore) GetRepoByName(ctx context.Context, tx db.Handler, name string)
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT * FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &repo, query, name)
- return repo, db.WrapError(err)
+ return repo, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoDescriptionByName implements store.RepositoryStore.
@@ -71,7 +71,7 @@ func (*repoStore) GetRepoDescriptionByName(ctx context.Context, tx db.Handler, n
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT description FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &description, query, name)
- return description, db.WrapError(err)
+ return description, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoIsHiddenByName implements store.RepositoryStore.
@@ -80,7 +80,7 @@ func (*repoStore) GetRepoIsHiddenByName(ctx context.Context, tx db.Handler, name
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT hidden FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &isHidden, query, name)
- return isHidden, db.WrapError(err)
+ return isHidden, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoIsMirrorByName implements store.RepositoryStore.
@@ -89,7 +89,7 @@ func (*repoStore) GetRepoIsMirrorByName(ctx context.Context, tx db.Handler, name
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT mirror FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &isMirror, query, name)
- return isMirror, db.WrapError(err)
+ return isMirror, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoIsPrivateByName implements store.RepositoryStore.
@@ -98,7 +98,7 @@ func (*repoStore) GetRepoIsPrivateByName(ctx context.Context, tx db.Handler, nam
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT private FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &isPrivate, query, name)
- return isPrivate, db.WrapError(err)
+ return isPrivate, db.WrapError(err) //nolint:wrapcheck
}
// GetRepoProjectNameByName implements store.RepositoryStore.
@@ -107,7 +107,7 @@ func (*repoStore) GetRepoProjectNameByName(ctx context.Context, tx db.Handler, n
name = utils.SanitizeRepo(name)
query := tx.Rebind("SELECT project_name FROM repos WHERE name = ?;")
err := tx.GetContext(ctx, &pname, query, name)
- return pname, db.WrapError(err)
+ return pname, db.WrapError(err) //nolint:wrapcheck
}
// SetRepoDescriptionByName implements store.RepositoryStore.
@@ -115,7 +115,7 @@ func (*repoStore) SetRepoDescriptionByName(ctx context.Context, tx db.Handler, n
name = utils.SanitizeRepo(name)
query := tx.Rebind("UPDATE repos SET description = ? WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, description, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// SetRepoIsHiddenByName implements store.RepositoryStore.
@@ -123,7 +123,7 @@ func (*repoStore) SetRepoIsHiddenByName(ctx context.Context, tx db.Handler, name
name = utils.SanitizeRepo(name)
query := tx.Rebind("UPDATE repos SET hidden = ? WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, isHidden, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// SetRepoIsPrivateByName implements store.RepositoryStore.
@@ -131,7 +131,7 @@ func (*repoStore) SetRepoIsPrivateByName(ctx context.Context, tx db.Handler, nam
name = utils.SanitizeRepo(name)
query := tx.Rebind("UPDATE repos SET private = ? WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, isPrivate, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// SetRepoNameByName implements store.RepositoryStore.
@@ -140,7 +140,7 @@ func (*repoStore) SetRepoNameByName(ctx context.Context, tx db.Handler, name str
newName = utils.SanitizeRepo(newName)
query := tx.Rebind("UPDATE repos SET name = ? WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, newName, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// SetRepoProjectNameByName implements store.RepositoryStore.
@@ -148,5 +148,5 @@ func (*repoStore) SetRepoProjectNameByName(ctx context.Context, tx db.Handler, n
name = utils.SanitizeRepo(name)
query := tx.Rebind("UPDATE repos SET project_name = ? WHERE name = ?;")
_, err := tx.ExecContext(ctx, query, projectName, name)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
@@ -17,7 +17,7 @@ func (*settingsStore) GetAllowKeylessAccess(ctx context.Context, tx db.Handler)
var allow bool
query := tx.Rebind(`SELECT value FROM settings WHERE "key" = 'allow_keyless'`)
if err := tx.GetContext(ctx, &allow, query); err != nil {
- return false, db.WrapError(err)
+ return false, db.WrapError(err) //nolint:wrapcheck
}
return allow, nil
}
@@ -27,7 +27,7 @@ func (*settingsStore) GetAnonAccess(ctx context.Context, tx db.Handler) (access.
var level string
query := tx.Rebind(`SELECT value FROM settings WHERE "key" = 'anon_access'`)
if err := tx.GetContext(ctx, &level, query); err != nil {
- return access.NoAccess, db.WrapError(err)
+ return access.NoAccess, db.WrapError(err) //nolint:wrapcheck
}
return access.ParseAccessLevel(level), nil
}
@@ -36,12 +36,12 @@ func (*settingsStore) GetAnonAccess(ctx context.Context, tx db.Handler) (access.
func (*settingsStore) SetAllowKeylessAccess(ctx context.Context, tx db.Handler, allow bool) error {
query := tx.Rebind(`UPDATE settings SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE "key" = 'allow_keyless'`)
_, err := tx.ExecContext(ctx, query, allow)
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
// SetAnonAccess implements store.SettingStore.
func (*settingsStore) SetAnonAccess(ctx context.Context, tx db.Handler, level access.AccessLevel) error {
query := tx.Rebind(`UPDATE settings SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE "key" = 'anon_access'`)
_, err := tx.ExecContext(ctx, query, level.String())
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
@@ -20,12 +20,12 @@ var _ store.UserStore = (*userStore)(nil)
func (*userStore) AddPublicKeyByUsername(ctx context.Context, tx db.Handler, username string, pk ssh.PublicKey) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
var userID int64
if err := tx.GetContext(ctx, &userID, tx.Rebind(`SELECT id FROM users WHERE username = ?`), username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`INSERT INTO public_keys (user_id, public_key, updated_at)
@@ -33,14 +33,14 @@ func (*userStore) AddPublicKeyByUsername(ctx context.Context, tx db.Handler, use
ak := sshutils.MarshalAuthorizedKey(pk)
_, err := tx.ExecContext(ctx, query, userID, ak)
- return err
+ return err //nolint:wrapcheck
}
// CreateUser implements store.UserStore.
func (*userStore) CreateUser(ctx context.Context, tx db.Handler, username string, isAdmin bool, pks []ssh.PublicKey) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`INSERT INTO users (username, admin, updated_at)
@@ -48,7 +48,7 @@ func (*userStore) CreateUser(ctx context.Context, tx db.Handler, username string
var userID int64
if err := tx.GetContext(ctx, &userID, query, username, isAdmin); err != nil {
- return err
+ return err //nolint:wrapcheck
}
for _, pk := range pks {
@@ -57,7 +57,7 @@ func (*userStore) CreateUser(ctx context.Context, tx db.Handler, username string
ak := sshutils.MarshalAuthorizedKey(pk)
_, err := tx.ExecContext(ctx, query, userID, ak)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
@@ -68,12 +68,12 @@ func (*userStore) CreateUser(ctx context.Context, tx db.Handler, username string
func (*userStore) DeleteUserByUsername(ctx context.Context, tx db.Handler, username string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`DELETE FROM users WHERE username = ?;`)
_, err := tx.ExecContext(ctx, query, username)
- return err
+ return err //nolint:wrapcheck
}
// GetUserByID implements store.UserStore.
@@ -81,7 +81,7 @@ func (*userStore) GetUserByID(ctx context.Context, tx db.Handler, id int64) (mod
var m models.User
query := tx.Rebind(`SELECT * FROM users WHERE id = ?;`)
err := tx.GetContext(ctx, &m, query, id)
- return m, err
+ return m, err //nolint:wrapcheck
}
// FindUserByPublicKey implements store.UserStore.
@@ -92,20 +92,20 @@ func (*userStore) FindUserByPublicKey(ctx context.Context, tx db.Handler, pk ssh
INNER JOIN public_keys ON users.id = public_keys.user_id
WHERE public_keys.public_key = ?;`)
err := tx.GetContext(ctx, &m, query, sshutils.MarshalAuthorizedKey(pk))
- return m, err
+ return m, err //nolint:wrapcheck
}
// FindUserByUsername implements store.UserStore.
func (*userStore) FindUserByUsername(ctx context.Context, tx db.Handler, username string) (models.User, error) {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return models.User{}, err
+ return models.User{}, err //nolint:wrapcheck
}
var m models.User
query := tx.Rebind(`SELECT * FROM users WHERE username = ?;`)
err := tx.GetContext(ctx, &m, query, username)
- return m, err
+ return m, err //nolint:wrapcheck
}
// FindUserByAccessToken implements store.UserStore.
@@ -116,7 +116,7 @@ func (*userStore) FindUserByAccessToken(ctx context.Context, tx db.Handler, toke
INNER JOIN access_tokens ON users.id = access_tokens.user_id
WHERE access_tokens.token = ?;`)
err := tx.GetContext(ctx, &m, query, token)
- return m, err
+ return m, err //nolint:wrapcheck
}
// GetAllUsers implements store.UserStore.
@@ -124,7 +124,7 @@ func (*userStore) GetAllUsers(ctx context.Context, tx db.Handler) ([]models.User
var ms []models.User
query := tx.Rebind(`SELECT * FROM users;`)
err := tx.SelectContext(ctx, &ms, query)
- return ms, err
+ return ms, err //nolint:wrapcheck
}
// ListPublicKeysByUserID implements store.UserStore..
@@ -135,14 +135,14 @@ func (*userStore) ListPublicKeysByUserID(ctx context.Context, tx db.Handler, id
ORDER BY public_keys.id ASC;`)
err := tx.SelectContext(ctx, &aks, query, id)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
pks := make([]ssh.PublicKey, len(aks))
for i, ak := range aks {
pk, _, err := sshutils.ParseAuthorizedKey(ak)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
pks[i] = pk
}
@@ -154,7 +154,7 @@ func (*userStore) ListPublicKeysByUserID(ctx context.Context, tx db.Handler, id
func (*userStore) ListPublicKeysByUsername(ctx context.Context, tx db.Handler, username string) ([]ssh.PublicKey, error) {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
var aks []string
@@ -164,14 +164,14 @@ func (*userStore) ListPublicKeysByUsername(ctx context.Context, tx db.Handler, u
ORDER BY public_keys.id ASC;`)
err := tx.SelectContext(ctx, &aks, query, username)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
pks := make([]ssh.PublicKey, len(aks))
for i, ak := range aks {
pk, _, err := sshutils.ParseAuthorizedKey(ak)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
pks[i] = pk
}
@@ -183,60 +183,60 @@ func (*userStore) ListPublicKeysByUsername(ctx context.Context, tx db.Handler, u
func (*userStore) RemovePublicKeyByUsername(ctx context.Context, tx db.Handler, username string, pk ssh.PublicKey) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`DELETE FROM public_keys
WHERE user_id = (SELECT id FROM users WHERE username = ?)
AND public_key = ?;`)
_, err := tx.ExecContext(ctx, query, username, sshutils.MarshalAuthorizedKey(pk))
- return err
+ return err //nolint:wrapcheck
}
// SetAdminByUsername implements store.UserStore.
func (*userStore) SetAdminByUsername(ctx context.Context, tx db.Handler, username string, isAdmin bool) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`UPDATE users SET admin = ? WHERE username = ?;`)
_, err := tx.ExecContext(ctx, query, isAdmin, username)
- return err
+ return err //nolint:wrapcheck
}
// SetUsernameByUsername implements store.UserStore.
func (*userStore) SetUsernameByUsername(ctx context.Context, tx db.Handler, username string, newUsername string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
newUsername = strings.ToLower(newUsername)
if err := utils.ValidateUsername(newUsername); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`UPDATE users SET username = ? WHERE username = ?;`)
_, err := tx.ExecContext(ctx, query, newUsername, username)
- return err
+ return err //nolint:wrapcheck
}
// SetUserPassword implements store.UserStore.
func (*userStore) SetUserPassword(ctx context.Context, tx db.Handler, userID int64, password string) error {
query := tx.Rebind(`UPDATE users SET password = ? WHERE id = ?;`)
_, err := tx.ExecContext(ctx, query, password, userID)
- return err
+ return err //nolint:wrapcheck
}
// SetUserPasswordByUsername implements store.UserStore.
func (*userStore) SetUserPasswordByUsername(ctx context.Context, tx db.Handler, username string, password string) error {
username = strings.ToLower(username)
if err := utils.ValidateUsername(username); err != nil {
- return err
+ return err //nolint:wrapcheck
}
query := tx.Rebind(`UPDATE users SET password = ? WHERE username = ?;`)
_, err := tx.ExecContext(ctx, query, password, username)
- return err
+ return err //nolint:wrapcheck
}
@@ -21,7 +21,7 @@ func (*webhookStore) CreateWebhook(ctx context.Context, h db.Handler, repoID int
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP) RETURNING id;`)
err := h.GetContext(ctx, &id, query, repoID, url, secret, contentType, active)
if err != nil {
- return 0, err
+ return 0, err //nolint:wrapcheck
}
return id, nil
@@ -36,7 +36,7 @@ func (*webhookStore) CreateWebhookDelivery(ctx context.Context, h db.Handler, id
reqErr = requestError.Error()
}
_, err := h.ExecContext(ctx, query, id, webhookID, event, url, method, reqErr, requestHeaders, requestBody, responseStatus, responseHeaders, responseBody)
- return err
+ return err //nolint:wrapcheck
}
// CreateWebhookEvents implements store.WebhookStore.
@@ -46,7 +46,7 @@ func (*webhookStore) CreateWebhookEvents(ctx context.Context, h db.Handler, webh
for _, event := range events {
_, err := h.ExecContext(ctx, query, webhookID, event)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
}
return nil
@@ -56,33 +56,33 @@ func (*webhookStore) CreateWebhookEvents(ctx context.Context, h db.Handler, webh
func (*webhookStore) DeleteWebhookByID(ctx context.Context, h db.Handler, id int64) error {
query := h.Rebind(`DELETE FROM webhooks WHERE id = ?;`)
_, err := h.ExecContext(ctx, query, id)
- return err
+ return err //nolint:wrapcheck
}
// DeleteWebhookForRepoByID implements store.WebhookStore.
func (*webhookStore) DeleteWebhookForRepoByID(ctx context.Context, h db.Handler, repoID int64, id int64) error {
query := h.Rebind(`DELETE FROM webhooks WHERE repo_id = ? AND id = ?;`)
_, err := h.ExecContext(ctx, query, repoID, id)
- return err
+ return err //nolint:wrapcheck
}
// DeleteWebhookDeliveryByID implements store.WebhookStore.
func (*webhookStore) DeleteWebhookDeliveryByID(ctx context.Context, h db.Handler, webhookID int64, id uuid.UUID) error {
query := h.Rebind(`DELETE FROM webhook_deliveries WHERE webhook_id = ? AND id = ?;`)
_, err := h.ExecContext(ctx, query, webhookID, id)
- return err
+ return err //nolint:wrapcheck
}
// DeleteWebhookEventsByWebhookID implements store.WebhookStore.
func (*webhookStore) DeleteWebhookEventsByID(ctx context.Context, h db.Handler, ids []int64) error {
query, args, err := sqlx.In(`DELETE FROM webhook_events WHERE id IN (?);`, ids)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
query = h.Rebind(query)
_, err = h.ExecContext(ctx, query, args...)
- return err
+ return err //nolint:wrapcheck
}
// GetWebhookByID implements store.WebhookStore.
@@ -90,7 +90,7 @@ func (*webhookStore) GetWebhookByID(ctx context.Context, h db.Handler, repoID in
query := h.Rebind(`SELECT * FROM webhooks WHERE repo_id = ? AND id = ?;`)
var wh models.Webhook
err := h.GetContext(ctx, &wh, query, repoID, id)
- return wh, err
+ return wh, err //nolint:wrapcheck
}
// GetWebhookDeliveriesByWebhookID implements store.WebhookStore.
@@ -98,7 +98,7 @@ func (*webhookStore) GetWebhookDeliveriesByWebhookID(ctx context.Context, h db.H
query := h.Rebind(`SELECT * FROM webhook_deliveries WHERE webhook_id = ?;`)
var whds []models.WebhookDelivery
err := h.SelectContext(ctx, &whds, query, webhookID)
- return whds, err
+ return whds, err //nolint:wrapcheck
}
// GetWebhookDeliveryByID implements store.WebhookStore.
@@ -106,7 +106,7 @@ func (*webhookStore) GetWebhookDeliveryByID(ctx context.Context, h db.Handler, w
query := h.Rebind(`SELECT * FROM webhook_deliveries WHERE webhook_id = ? AND id = ?;`)
var whd models.WebhookDelivery
err := h.GetContext(ctx, &whd, query, webhookID, id)
- return whd, err
+ return whd, err //nolint:wrapcheck
}
// GetWebhookEventByID implements store.WebhookStore.
@@ -114,7 +114,7 @@ func (*webhookStore) GetWebhookEventByID(ctx context.Context, h db.Handler, id i
query := h.Rebind(`SELECT * FROM webhook_events WHERE id = ?;`)
var whe models.WebhookEvent
err := h.GetContext(ctx, &whe, query, id)
- return whe, err
+ return whe, err //nolint:wrapcheck
}
// GetWebhookEventsByWebhookID implements store.WebhookStore.
@@ -122,7 +122,7 @@ func (*webhookStore) GetWebhookEventsByWebhookID(ctx context.Context, h db.Handl
query := h.Rebind(`SELECT * FROM webhook_events WHERE webhook_id = ?;`)
var whes []models.WebhookEvent
err := h.SelectContext(ctx, &whes, query, webhookID)
- return whes, err
+ return whes, err //nolint:wrapcheck
}
// GetWebhooksByRepoID implements store.WebhookStore.
@@ -130,7 +130,7 @@ func (*webhookStore) GetWebhooksByRepoID(ctx context.Context, h db.Handler, repo
query := h.Rebind(`SELECT * FROM webhooks WHERE repo_id = ?;`)
var whs []models.Webhook
err := h.SelectContext(ctx, &whs, query, repoID)
- return whs, err
+ return whs, err //nolint:wrapcheck
}
// GetWebhooksByRepoIDWhereEvent implements store.WebhookStore.
@@ -140,13 +140,13 @@ func (*webhookStore) GetWebhooksByRepoIDWhereEvent(ctx context.Context, h db.Han
INNER JOIN webhook_events ON webhooks.id = webhook_events.webhook_id
WHERE webhooks.repo_id = ? AND webhook_events.event IN (?);`, repoID, events)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
query = h.Rebind(query)
var whs []models.Webhook
err = h.SelectContext(ctx, &whs, query, args...)
- return whs, err
+ return whs, err //nolint:wrapcheck
}
// ListWebhookDeliveriesByWebhookID implements store.WebhookStore.
@@ -154,12 +154,12 @@ func (*webhookStore) ListWebhookDeliveriesByWebhookID(ctx context.Context, h db.
query := h.Rebind(`SELECT id, response_status, event FROM webhook_deliveries WHERE webhook_id = ?;`)
var whds []models.WebhookDelivery
err := h.SelectContext(ctx, &whds, query, webhookID)
- return whds, err
+ return whds, err //nolint:wrapcheck
}
// UpdateWebhookByID implements store.WebhookStore.
func (*webhookStore) UpdateWebhookByID(ctx context.Context, h db.Handler, repoID int64, id int64, url string, secret string, contentType int, active bool) error {
query := h.Rebind(`UPDATE webhooks SET url = ?, secret = ?, content_type = ?, active = ?, updated_at = CURRENT_TIMESTAMP WHERE repo_id = ? AND id = ?;`)
_, err := h.ExecContext(ctx, query, url, secret, contentType, active, repoID, id)
- return err
+ return err //nolint:wrapcheck
}
@@ -1,3 +1,4 @@
+// Package sync provides synchronization utilities.
package sync
import (
@@ -1,3 +1,4 @@
+// Package task provides task management functionality.
package task
import (
@@ -1,3 +1,4 @@
+// Package test provides testing utilities.
package test
import (
@@ -13,7 +14,7 @@ var (
// RandomPort returns a random port number.
// This is mainly used for testing.
func RandomPort() int {
- addr, _ := net.Listen("tcp", ":0") //nolint:gosec
+ addr, _ := net.Listen("tcp", ":0") //nolint:gosec,noctx
_ = addr.Close()
port := addr.Addr().(*net.TCPAddr).Port
lock.Lock()
@@ -1,3 +1,4 @@
+// Package common provides common UI utilities and components.
package common
import (
@@ -13,8 +13,8 @@ type Component interface {
SetSize(width, height int)
}
-// TabComponenet represents a model that is mounted to a tab.
-// TODO: find a better name
+// TabComponent represents a model that is mounted to a tab.
+// TODO: find a better name.
type TabComponent interface {
Component
@@ -51,7 +51,7 @@ func FormatHighlight(p, c string) (string, error) {
rctx := StyleRendererWithStyles(styles)
err := formatter.Render(&r, rctx)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return r.String(), nil
}
@@ -1,3 +1,4 @@
+// Package code provides code syntax highlighting components.
package code
import (
@@ -83,7 +84,7 @@ func (r *Code) Init() tea.Cmd {
w := r.common.Width - r.common.Styles.App.GetHorizontalFrameSize()
content := r.content
if content == "" {
- r.Viewport.Model.SetContent(r.NoContentStyle.String())
+ r.Model.SetContent(r.NoContentStyle.String())
return nil
}
@@ -113,7 +114,7 @@ func (r *Code) Init() tea.Cmd {
if r.sidenote != "" {
lines := strings.Split(r.sidenote, "\n")
- sideNoteWidth := int(math.Ceil(float64(r.Model.Width()) * r.SideNotePercent))
+ sideNoteWidth := int(math.Ceil(float64(r.Width()) * r.SideNotePercent))
for i, l := range lines {
lines[i] = common.TruncateString(l, sideNoteWidth)
}
@@ -126,7 +127,7 @@ func (r *Code) Init() tea.Cmd {
// TODO: solve this upstream in Glamour/Reflow.
content = lipgloss.NewStyle().Width(w).Render(content)
- r.Viewport.Model.SetContent(content)
+ r.Model.SetContent(content)
return nil
}
@@ -197,11 +198,11 @@ func (r *Code) glamourize(w int, md string) (string, error) {
glamour.WithWordWrap(w),
)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
mdt, err := tr.Render(md)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return mdt, nil
}
@@ -232,7 +233,7 @@ func (r *Code) renderFile(path, content string) (string, error) {
}
err := formatter.Render(&s, rc)
if err != nil {
- return "", err
+ return "", err //nolint:wrapcheck
}
return s.String(), nil
@@ -1,3 +1,4 @@
+// Package footer provides footer UI components.
package footer
import (
@@ -1,3 +1,4 @@
+// Package header provides header UI components.
package header
import (
@@ -1,3 +1,4 @@
+// Package selector provides selector UI components.
package selector
import (
@@ -61,35 +62,35 @@ func New(common common.Common, items []IdentifiableItem, delegate ItemDelegate)
func (s *Selector) PerPage() int {
s.mtx.RLock()
defer s.mtx.RUnlock()
- return s.Model.Paginator.PerPage
+ return s.Paginator.PerPage
}
// SetPage sets the current page.
func (s *Selector) SetPage(page int) {
s.mtx.Lock()
defer s.mtx.Unlock()
- s.Model.Paginator.Page = page
+ s.Paginator.Page = page
}
// Page returns the current page.
func (s *Selector) Page() int {
s.mtx.RLock()
defer s.mtx.RUnlock()
- return s.Model.Paginator.Page
+ return s.Paginator.Page
}
// TotalPages returns the total number of pages.
func (s *Selector) TotalPages() int {
s.mtx.RLock()
defer s.mtx.RUnlock()
- return s.Model.Paginator.TotalPages
+ return s.Paginator.TotalPages
}
// SetTotalPages sets the total number of pages given the number of items.
func (s *Selector) SetTotalPages(items int) int {
s.mtx.Lock()
defer s.mtx.Unlock()
- return s.Model.Paginator.SetTotalPages(items)
+ return s.Paginator.SetTotalPages(items)
}
// SelectedItem returns the currently selected item.
@@ -1,3 +1,4 @@
+// Package statusbar provides status bar UI components.
package statusbar
import (
@@ -1,3 +1,4 @@
+// Package tabs provides tab UI components.
package tabs
import (
@@ -1,3 +1,4 @@
+// Package viewport provides viewport UI components.
package viewport
import (
@@ -28,8 +29,8 @@ func New(c common.Common) *Viewport {
// SetSize implements common.Component.
func (v *Viewport) SetSize(width, height int) {
v.common.SetSize(width, height)
- v.Model.SetWidth(width)
- v.Model.SetHeight(height)
+ v.SetWidth(width)
+ v.SetHeight(height)
}
// Init implements tea.Model.
@@ -75,12 +76,12 @@ func (v *Viewport) GotoBottom() {
// HalfViewDown moves the viewport down by half the viewport height.
func (v *Viewport) HalfViewDown() {
- v.Model.HalfPageDown()
+ v.HalfPageDown()
}
// HalfViewUp moves the viewport up by half the viewport height.
func (v *Viewport) HalfViewUp() {
- v.Model.HalfPageUp()
+ v.HalfPageUp()
}
// ScrollPercent returns the viewport's scroll percentage.
@@ -1,3 +1,4 @@
+// Package keymap provides keyboard mapping definitions.
package keymap
import "github.com/charmbracelet/bubbles/v2/key"
@@ -1,3 +1,4 @@
+// Package repo provides repository UI pages.
package repo
import (
@@ -128,7 +128,7 @@ func (f *Files) SetSize(width, height int) {
// ShortHelp implements help.KeyMap.
func (f *Files) ShortHelp() []key.Binding {
k := f.selector.KeyMap
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
return []key.Binding{
f.common.KeyMap.SelectItem,
@@ -152,7 +152,7 @@ func (f *Files) FullHelp() [][]key.Binding {
b := make([][]key.Binding, 0)
copyKey := f.common.KeyMap.Copy
actionKeys := []key.Binding{}
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
copyKey.SetHelp("c", "copy name")
k := f.selector.KeyMap
@@ -261,12 +261,12 @@ func (f *Files) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
case GoBackMsg:
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles, filesViewContent:
cmds = append(cmds, f.deselectItemCmd())
}
case tea.KeyPressMsg:
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
switch {
case key.Matches(msg, f.common.KeyMap.SelectItem):
@@ -302,7 +302,7 @@ func (f *Files) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
case tea.WindowSizeMsg:
f.SetSize(msg.Width, msg.Height)
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
if f.repo != nil {
cmds = append(cmds, f.updateFilesCmd)
@@ -333,7 +333,7 @@ func (f *Files) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
}
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
m, cmd := f.selector.Update(msg)
f.selector = m.(*selector.Selector)
@@ -380,7 +380,7 @@ func (f *Files) StatusBarValue() string {
// StatusBarInfo returns the status bar info.
func (f *Files) StatusBarInfo() string {
- switch f.activeView {
+ switch f.activeView { //nolint:exhaustive
case filesViewFiles:
return fmt.Sprintf("# %d/%d", f.selector.Index()+1, len(f.selector.VisibleItems()))
case filesViewContent:
@@ -432,7 +432,7 @@ func (f *Files) selectTreeCmd() tea.Msg {
func (f *Files) selectFileCmd() tea.Msg {
i := f.currentItem
- if i != nil && !i.entry.IsTree() {
+ if i != nil && !i.entry.IsTree() { //nolint:nestif
fi := i.entry.File()
if i.Mode().IsDir() || f == nil {
return common.ErrorMsg(errInvalidFile)
@@ -85,7 +85,7 @@ func NewLog(common common.Common) *Log {
// Path implements common.TabComponent.
func (l *Log) Path() string {
- switch l.activeView {
+ switch l.activeView { //nolint:exhaustive
case logViewCommits:
return ""
default:
@@ -107,7 +107,7 @@ func (l *Log) SetSize(width, height int) {
// ShortHelp implements help.KeyMap.
func (l *Log) ShortHelp() []key.Binding {
- switch l.activeView {
+ switch l.activeView { //nolint:exhaustive
case logViewCommits:
copyKey := l.common.KeyMap.Copy
copyKey.SetHelp("c", "copy hash")
@@ -135,7 +135,7 @@ func (l *Log) ShortHelp() []key.Binding {
func (l *Log) FullHelp() [][]key.Binding {
k := l.selector.KeyMap
b := make([][]key.Binding, 0)
- switch l.activeView {
+ switch l.activeView { //nolint:exhaustive
case logViewCommits:
copyKey := l.common.KeyMap.Copy
copyKey.SetHelp("c", "copy hash")
@@ -228,7 +228,7 @@ func (l *Log) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
l.activeCommit = i.(LogItem).Commit
}
case tea.KeyPressMsg, tea.MouseClickMsg:
- switch l.activeView {
+ switch l.activeView { //nolint:exhaustive
case logViewCommits:
switch kmsg := msg.(type) {
case tea.KeyPressMsg:
@@ -335,7 +335,7 @@ func (l *Log) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
l.spinner = s
}
}
- switch l.activeView {
+ switch l.activeView { //nolint:exhaustive
case logViewDiff:
vp, cmd := l.vp.Update(msg)
l.vp = vp.(*viewport.Viewport)
@@ -33,7 +33,7 @@ func (i LogItem) Hash() string {
// Title returns the item title. Implements list.DefaultItem.
func (i LogItem) Title() string {
if i.Commit != nil {
- return strings.Split(i.Commit.Message, "\n")[0]
+ return strings.Split(i.Message, "\n")[0]
}
return ""
}
@@ -64,9 +64,10 @@ func (r *Refs) Path() string {
// TabName returns the name of the tab.
func (r *Refs) TabName() string {
- if r.refPrefix == git.RefsHeads {
+ switch r.refPrefix {
+ case git.RefsHeads:
return "Branches"
- } else if r.refPrefix == git.RefsTags {
+ case git.RefsTags:
return "Tags"
}
return "Refs"
@@ -58,7 +58,7 @@ func (cl RefItems) Swap(i, j int) { cl[i], cl[j] = cl[j], cl[i] }
// Less implements sort.Interface.
func (cl RefItems) Less(i, j int) bool {
if cl[i].Commit != nil && cl[j].Commit != nil {
- return cl[i].Commit.Author.When.After(cl[j].Commit.Author.When)
+ return cl[i].Author.When.After(cl[j].Author.When)
} else if cl[i].Commit != nil && cl[j].Commit == nil {
return true
}
@@ -99,7 +99,7 @@ func (d RefItemDelegate) Render(w io.Writer, m list.Model, index int, listItem l
return
}
- isTag := i.Reference.IsTag()
+ isTag := i.IsTag()
isActive := index == m.Index()
s := d.common.Styles.Ref
st := s.Normal
@@ -130,6 +130,7 @@ func (d RefItemDelegate) Render(w io.Writer, m list.Model, index int, listItem l
ref := i.Short()
var desc string
+ //nolint:nestif // Complex UI logic requires nested conditions
if isTag {
if c != nil {
date := c.Committer.When.Format("Jan 02")
@@ -32,7 +32,7 @@ type EmptyRepoMsg struct{}
type CopyURLMsg struct{}
// RepoMsg is a message that contains a git.Repository.
-type RepoMsg proto.Repository // nolint:revive
+type RepoMsg proto.Repository //nolint:revive
// GoBackMsg is a message to go back to the previous view.
type GoBackMsg struct{}
@@ -226,6 +226,7 @@ func (r *Repo) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// other is used when loading the log.
// Check if the spinner ID matches the spinner model.
case spinner.TickMsg:
+ //nolint:nestif // Complex UI state management requires nested conditions
if r.state == loadingState && r.spinner.ID() == msg.ID {
s, cmd := r.spinner.Update(msg)
r.spinner = s
@@ -120,7 +120,7 @@ func (s *Stash) StatusBarValue() string {
// StatusBarInfo implements common.Component.
func (s *Stash) StatusBarInfo() string {
- switch s.state {
+ switch s.state { //nolint:exhaustive
case stashStateList:
totalPages := s.list.TotalPages()
if totalPages <= 1 {
@@ -166,7 +166,7 @@ func (s *Stash) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
case tea.KeyPressMsg:
- switch s.state {
+ switch s.state { //nolint:exhaustive
case stashStateList:
switch {
case key.Matches(msg, s.common.KeyMap.BackItem):
@@ -217,7 +217,7 @@ func (s *Stash) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
s.state = stashStateList
}
- switch s.state {
+ switch s.state { //nolint:exhaustive
case stashStateList:
l, cmd := s.list.Update(msg)
s.list = l.(*selector.Selector)
@@ -1,3 +1,4 @@
+//nolint:revive
package selection
import (
@@ -135,7 +135,7 @@ func (s *Selection) FullHelp() [][]key.Binding {
s.common.KeyMap.Section,
},
}
- switch s.activePane {
+ switch s.activePane { //nolint:exhaustive
case readmePane:
k := s.readme.KeyMap
b = append(b, []key.Binding{
@@ -266,7 +266,7 @@ func (s *Selection) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case tabs.ActiveTabMsg:
s.activePane = pane(msg)
}
- switch s.activePane {
+ switch s.activePane { //nolint:exhaustive
case readmePane:
r, cmd := s.readme.Update(msg)
s.readme = r.(*code.Code)
@@ -287,7 +287,7 @@ func (s *Selection) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
func (s *Selection) View() string {
var view string
wm, hm := s.getMargins()
- switch s.activePane {
+ switch s.activePane { //nolint:exhaustive
case selectorPane:
ss := lipgloss.NewStyle().
Width(s.common.Width - wm).
@@ -1,3 +1,4 @@
+// Package styles provides UI styling definitions.
package styles
import (
@@ -1,3 +1,4 @@
+//nolint:revive
package utils
import (
@@ -1,3 +1,4 @@
+// Package web provides web server functionality.
package web
import (
@@ -90,7 +91,7 @@ func parseAuthHdr(r *http.Request) (proto.User, error) {
user, err := be.UserByAccessToken(ctx, parts[1])
if err != nil {
logger.Error("failed to get user", "err", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return user, nil
@@ -110,7 +111,7 @@ func parseAuthHdr(r *http.Request) (proto.User, error) {
user, err := be.User(ctx, parts[0])
if err != nil {
logger.Error("failed to get user", "err", err)
- return nil, err
+ return nil, err //nolint:wrapcheck
}
expectedSubject := fmt.Sprintf("%s#%d", user.Username(), user.ID())
@@ -138,7 +139,7 @@ func parseJWT(ctx context.Context, bearer string) (*jwt.RegisteredClaims, error)
logger := log.FromContext(ctx).WithPrefix("http.auth")
kp, err := config.KeyPair(cfg)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
repo := proto.RepositoryFromContext(ctx)
@@ -396,7 +396,7 @@ func serviceRpc(w http.ResponseWriter, r *http.Request) {
Dir: dir,
}
- switch service {
+ switch service { //nolint:exhaustive
case git.UploadPackService, git.ReceivePackService:
cmd.Args = append(cmd.Args, "--stateless-rpc")
}
@@ -434,7 +434,7 @@ func serviceRpc(w http.ResponseWriter, r *http.Request) {
renderInternalServerError(w, r)
return
}
- defer reader.Close() // nolint: errcheck
+ defer reader.Close() //nolint:errcheck
}
cmd.Stdin = reader
@@ -453,13 +453,13 @@ func serviceRpc(w http.ResponseWriter, r *http.Request) {
}
// Handle buffered output
-// Useful when using proxies
+// Useful when using proxies.
type flushResponseWriter struct {
http.ResponseWriter
}
func (f *flushResponseWriter) ReadFrom(r io.Reader) (int64, error) {
- flusher := http.NewResponseController(f.ResponseWriter) // nolint: bodyclose
+ flusher := http.NewResponseController(f.ResponseWriter)
var n int64
p := make([]byte, 1024)
@@ -468,12 +468,12 @@ func (f *flushResponseWriter) ReadFrom(r io.Reader) (int64, error) {
if err == io.EOF {
break
}
- nWrite, err := f.ResponseWriter.Write(p[:nRead])
+ nWrite, err := f.Write(p[:nRead])
if err != nil {
- return n, err
+ return n, err //nolint:wrapcheck
}
if nRead != nWrite {
- return n, err
+ return n, err //nolint:wrapcheck
}
n += int64(nRead)
// ResponseWriter must support http.Flusher to handle buffered output.
@@ -494,7 +494,7 @@ func getInfoRefs(w http.ResponseWriter, r *http.Request) {
gitHttpUploadCounter.WithLabelValues(repoName, file).Inc()
- if service != "" && (service == git.UploadPackService || service == git.ReceivePackService) {
+ if service != "" && (service == git.UploadPackService || service == git.ReceivePackService) { //nolint:nestif
// Smart HTTP
var refs bytes.Buffer
cmd := git.ServiceCommand{
@@ -537,12 +537,12 @@ func getInfoRefs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", service))
w.WriteHeader(http.StatusOK)
if version < 2 {
- git.WritePktline(w, "# service="+service.String()) // nolint: errcheck
+ git.WritePktline(w, "# service="+service.String()) //nolint:errcheck,gosec
}
- w.Write(refs.Bytes()) // nolint: errcheck
+ w.Write(refs.Bytes()) //nolint:errcheck,gosec
} else {
// Dumb HTTP
- updateServerInfo(ctx, dir) // nolint: errcheck
+ updateServerInfo(ctx, dir) //nolint:errcheck,gosec
hdrNocache(w)
sendFile("text/plain; charset=utf-8", w, r)
}
@@ -604,7 +604,7 @@ func isSmart(r *http.Request, service git.Service) bool {
}
func updateServerInfo(ctx context.Context, dir string) error {
- return gitb.UpdateServerInfo(ctx, dir)
+ return gitb.UpdateServerInfo(ctx, dir) //nolint:wrapcheck
}
// HTTP error response handling functions
@@ -29,7 +29,7 @@ import (
// serviceLfsBatch handles a Git LFS batch requests.
// https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
// TODO: support refname
-// POST: /<repo>.git/info/lfs/objects/batch
+// POST: /<repo>.git/info/lfs/objects/batch.
func serviceLfsBatch(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := log.FromContext(ctx).WithPrefix("http.lfs")
@@ -41,7 +41,7 @@ func serviceLfsBatch(w http.ResponseWriter, r *http.Request) {
}
var batchRequest lfs.BatchRequest
- defer r.Body.Close() // nolint: errcheck
+ defer r.Body.Close() //nolint: errcheck
if err := json.NewDecoder(r.Body).Decode(&batchRequest); err != nil {
logger.Errorf("error decoding json: %s", err)
renderJSON(w, http.StatusUnprocessableEntity, lfs.ErrorResponse{
@@ -122,7 +122,7 @@ func serviceLfsBatch(w http.ResponseWriter, r *http.Request) {
return
}
- if !exist {
+ if !exist { //nolint:nestif
objects = append(objects, &lfs.ObjectResponse{
Pointer: o,
Error: &lfs.ObjectError{
@@ -249,7 +249,7 @@ func serviceLfsBasic(w http.ResponseWriter, r *http.Request) {
}
}
-// GET: /<repo>.git/info/lfs/objects/basic/<oid>
+// GET: /<repo>.git/info/lfs/objects/basic/<oid>.
func serviceLfsBasicDownload(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
oid := mux.Vars(r)["oid"]
@@ -282,7 +282,7 @@ func serviceLfsBasicDownload(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.FormatInt(obj.Size, 10))
- defer f.Close() // nolint: errcheck
+ defer f.Close() //nolint: errcheck
if _, err := io.Copy(w, f); err != nil {
logger.Error("error copying object to response", "oid", oid, "err", err)
renderJSON(w, http.StatusInternalServerError, lfs.ErrorResponse{
@@ -292,7 +292,7 @@ func serviceLfsBasicDownload(w http.ResponseWriter, r *http.Request) {
}
}
-// PUT: /<repo>.git/info/lfs/objects/basic/<oid>
+// PUT: /<repo>.git/info/lfs/objects/basic/<oid>.
func serviceLfsBasicUpload(w http.ResponseWriter, r *http.Request) {
if !isBinary(r) {
renderJSON(w, http.StatusUnsupportedMediaType, lfs.ErrorResponse{
@@ -313,7 +313,7 @@ func serviceLfsBasicUpload(w http.ResponseWriter, r *http.Request) {
strg := storage.NewLocalStorage(filepath.Join(cfg.DataPath, "lfs", repoID))
name := mux.Vars(r)["repo"]
- defer r.Body.Close() // nolint: errcheck
+ defer r.Body.Close() //nolint: errcheck
repo, err := be.Repository(ctx, name)
if err != nil {
renderJSON(w, http.StatusNotFound, lfs.ErrorResponse{
@@ -326,7 +326,7 @@ func serviceLfsBasicUpload(w http.ResponseWriter, r *http.Request) {
// partial error, so we need to skip existing objects.
if _, err := datastore.GetLFSObjectByOid(ctx, dbx, repo.ID(), oid); err == nil {
// Object exists, skip request
- io.Copy(io.Discard, r.Body) // nolint: errcheck
+ io.Copy(io.Discard, r.Body) //nolint:errcheck,gosec
renderStatus(http.StatusOK)(w, nil)
return
} else if !errors.Is(err, db.ErrRecordNotFound) {
@@ -366,7 +366,7 @@ func serviceLfsBasicUpload(w http.ResponseWriter, r *http.Request) {
renderStatus(http.StatusOK)(w, nil)
}
-// POST: /<repo>.git/info/lfs/objects/basic/verify
+// POST: /<repo>.git/info/lfs/objects/basic/verify.
func serviceLfsBasicVerify(w http.ResponseWriter, r *http.Request) {
if !isLfs(r) {
renderNotAcceptable(w)
@@ -385,7 +385,7 @@ func serviceLfsBasicVerify(w http.ResponseWriter, r *http.Request) {
return
}
- defer r.Body.Close() // nolint: errcheck
+ defer r.Body.Close() //nolint: errcheck
if err := json.NewDecoder(r.Body).Decode(&pointer); err != nil {
logger.Error("error decoding json", "err", err)
renderJSON(w, http.StatusBadRequest, lfs.ErrorResponse{
@@ -399,7 +399,7 @@ func serviceLfsBasicVerify(w http.ResponseWriter, r *http.Request) {
datastore := store.FromContext(ctx)
repoID := strconv.FormatInt(repo.ID(), 10)
strg := storage.NewLocalStorage(filepath.Join(cfg.DataPath, "lfs", repoID))
- if stat, err := strg.Stat(path.Join("objects", pointer.RelativePath())); err == nil {
+ if stat, err := strg.Stat(path.Join("objects", pointer.RelativePath())); err == nil { //nolint:nestif
// Verify object is in the database.
obj, err := datastore.GetLFSObjectByOid(ctx, dbx, repo.ID(), pointer.Oid)
if err != nil {
@@ -454,7 +454,7 @@ func serviceLfsLocks(w http.ResponseWriter, r *http.Request) {
}
}
-// POST: /<repo>.git/info/lfs/objects/locks
+// POST: /<repo>.git/info/lfs/objects/locks.
func serviceLfsLocksCreate(w http.ResponseWriter, r *http.Request) {
if !isLfs(r) {
renderNotAcceptable(w)
@@ -493,7 +493,7 @@ func serviceLfsLocksCreate(w http.ResponseWriter, r *http.Request) {
dbx := db.FromContext(ctx)
datastore := store.FromContext(ctx)
- if err := datastore.CreateLFSLockForUser(ctx, dbx, repo.ID(), user.ID(), req.Path, req.Ref.Name); err != nil {
+ if err := datastore.CreateLFSLockForUser(ctx, dbx, repo.ID(), user.ID(), req.Path, req.Ref.Name); err != nil { //nolint:nestif
err = db.WrapError(err)
if errors.Is(err, db.ErrDuplicateKey) {
errResp := lfs.LockResponse{
@@ -555,7 +555,7 @@ func serviceLfsLocksCreate(w http.ResponseWriter, r *http.Request) {
})
}
-// GET: /<repo>.git/info/lfs/objects/locks
+// GET: /<repo>.git/info/lfs/objects/locks.
func serviceLfsLocksGet(w http.ResponseWriter, r *http.Request) {
accept := r.Header.Get("Accept")
if !strings.HasPrefix(accept, lfs.MediaType) {
@@ -607,6 +607,7 @@ func serviceLfsLocksGet(w http.ResponseWriter, r *http.Request) {
return
}
+ //nolint:nestif // Complex LFS lock handling requires nested conditions
if id > 0 {
lock, err := datastore.GetLFSLockByID(ctx, dbx, id)
if err != nil {
@@ -730,7 +731,7 @@ func serviceLfsLocksGet(w http.ResponseWriter, r *http.Request) {
renderJSON(w, http.StatusOK, resp)
}
-// POST: /<repo>.git/info/lfs/objects/locks/verify
+// POST: /<repo>.git/info/lfs/objects/locks/verify.
func serviceLfsLocksVerify(w http.ResponseWriter, r *http.Request) {
if !isLfs(r) {
renderNotAcceptable(w)
@@ -827,7 +828,7 @@ func serviceLfsLocksVerify(w http.ResponseWriter, r *http.Request) {
renderJSON(w, http.StatusOK, resp)
}
-// POST: /<repo>.git/info/lfs/objects/locks/:lockID/unlock
+// POST: /<repo>.git/info/lfs/objects/locks/:lockID/unlock.
func serviceLfsLocksDelete(w http.ResponseWriter, r *http.Request) {
if !isLfs(r) {
renderNotAcceptable(w)
@@ -39,18 +39,18 @@ func NewHTTPServer(ctx context.Context) (*HTTPServer, error) {
// Close closes the HTTP server.
func (s *HTTPServer) Close() error {
- return s.Server.Close()
+ return s.Server.Close() //nolint:wrapcheck
}
// ListenAndServe starts the HTTP server.
func (s *HTTPServer) ListenAndServe() error {
if s.cfg.HTTP.TLSKeyPath != "" && s.cfg.HTTP.TLSCertPath != "" {
- return s.Server.ListenAndServeTLS(s.cfg.HTTP.TLSCertPath, s.cfg.HTTP.TLSKeyPath)
+ return s.Server.ListenAndServeTLS(s.cfg.HTTP.TLSCertPath, s.cfg.HTTP.TLSKeyPath) //nolint:wrapcheck
}
- return s.Server.ListenAndServe()
+ return s.Server.ListenAndServe() //nolint:wrapcheck
}
// Shutdown gracefully shuts down the HTTP server.
func (s *HTTPServer) Shutdown(ctx context.Context) error {
- return s.Server.Shutdown(ctx)
+ return s.Server.Shutdown(ctx) //nolint:wrapcheck
}
@@ -24,13 +24,13 @@ var _ http.Flusher = (*logWriter)(nil)
var _ http.Hijacker = (*logWriter)(nil)
-var _ http.CloseNotifier = (*logWriter)(nil) // nolint: staticcheck
+var _ http.CloseNotifier = (*logWriter)(nil) //nolint: staticcheck
// Write implements http.ResponseWriter.
func (r *logWriter) Write(p []byte) (int, error) {
written, err := r.ResponseWriter.Write(p)
r.bytes += written
- return written, err
+ return written, err //nolint:wrapcheck
}
// Note this is generally only called when sending an HTTP error, so it's
@@ -54,7 +54,7 @@ func (r *logWriter) Flush() {
// CloseNotify implements http.CloseNotifier.
func (r *logWriter) CloseNotify() <-chan bool {
- if cn, ok := r.ResponseWriter.(http.CloseNotifier); ok { // nolint: staticcheck
+ if cn, ok := r.ResponseWriter.(http.CloseNotifier); ok { //nolint: staticcheck
return cn.CloseNotify()
}
return nil
@@ -63,7 +63,7 @@ func (r *logWriter) CloseNotify() <-chan bool {
// Hijack implements http.Hijacker.
func (r *logWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := r.ResponseWriter.(http.Hijacker); ok {
- return h.Hijack()
+ return h.Hijack() //nolint:wrapcheck
}
return nil, nil, fmt.Errorf("http.Hijacker not implemented")
}
@@ -9,6 +9,6 @@ import (
func renderStatus(code int) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(code)
- io.WriteString(w, fmt.Sprintf("%d %s", code, http.StatusText(code))) // nolint: errcheck
+ io.WriteString(w, fmt.Sprintf("%d %s", code, http.StatusText(code))) //nolint:errcheck,gosec
}
}
@@ -1,3 +1,4 @@
+// Package webhook provides webhook functionality.
package webhook
import (
@@ -72,7 +73,7 @@ func NewBranchTagEvent(ctx context.Context, user proto.User, repo proto.Reposito
datastore := store.FromContext(ctx)
owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
if err != nil {
- return BranchTagEvent{}, db.WrapError(err)
+ return BranchTagEvent{}, db.WrapError(err) //nolint:wrapcheck
}
payload.Repository.Owner.ID = owner.ID
@@ -60,7 +60,7 @@ func NewCollaboratorEvent(ctx context.Context, user proto.User, repo proto.Repos
datastore := store.FromContext(ctx)
owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
if err != nil {
- return CollaboratorEvent{}, db.WrapError(err)
+ return CollaboratorEvent{}, db.WrapError(err) //nolint:wrapcheck
}
payload.Repository.Owner.ID = owner.ID
@@ -69,7 +69,7 @@ func NewCollaboratorEvent(ctx context.Context, user proto.User, repo proto.Repos
collab, err := datastore.GetCollabByUsernameAndRepo(ctx, dbx, collabUsername, repo.Name())
if err != nil {
- return CollaboratorEvent{}, err
+ return CollaboratorEvent{}, err //nolint:wrapcheck
}
payload.AccessLevel = collab.AccessLevel
@@ -62,7 +62,7 @@ func NewPushEvent(ctx context.Context, user proto.User, repo proto.Repository, r
datastore := store.FromContext(ctx)
owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
if err != nil {
- return PushEvent{}, db.WrapError(err)
+ return PushEvent{}, db.WrapError(err) //nolint:wrapcheck
}
payload.Repository.Owner.ID = owner.ID
@@ -71,7 +71,7 @@ func NewPushEvent(ctx context.Context, user proto.User, repo proto.Repository, r
// Find commits.
r, err := repo.Open()
if err != nil {
- return PushEvent{}, err
+ return PushEvent{}, err //nolint:wrapcheck
}
payload.Repository.DefaultBranch, _ = getDefaultBranch(repo)
@@ -87,7 +87,7 @@ func NewPushEvent(ctx context.Context, user proto.User, repo proto.Repository, r
MaxCount: 20,
})
if err != nil {
- return PushEvent{}, err
+ return PushEvent{}, err //nolint:wrapcheck
}
payload.Commits = make([]Commit, len(commits))
@@ -34,7 +34,7 @@ const (
// NewRepositoryEvent sends a repository event.
func NewRepositoryEvent(ctx context.Context, user proto.User, repo proto.Repository, action RepositoryEventAction) (RepositoryEvent, error) {
var event Event
- switch action {
+ switch action { //nolint:exhaustive
case RepositoryEventActionVisibilityChange:
event = EventRepositoryVisibilityChange
default:
@@ -71,7 +71,7 @@ func NewRepositoryEvent(ctx context.Context, user proto.User, repo proto.Reposit
datastore := store.FromContext(ctx)
owner, err := datastore.GetUserByID(ctx, dbx, repo.UserID())
if err != nil {
- return RepositoryEvent{}, db.WrapError(err)
+ return RepositoryEvent{}, db.WrapError(err) //nolint:wrapcheck
}
payload.Repository.Owner.ID = owner.ID
@@ -41,13 +41,13 @@ type Delivery struct {
func do(ctx context.Context, url string, method string, headers http.Header, body io.Reader) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
req.Header = headers
res, err := http.DefaultClient.Do(req)
if err != nil {
- return nil, err
+ return nil, err //nolint:wrapcheck
}
return res, nil
@@ -63,14 +63,14 @@ func SendWebhook(ctx context.Context, w models.Webhook, event Event, payload int
switch contentType {
case ContentTypeJSON:
if err := json.NewEncoder(&buf).Encode(payload); err != nil {
- return err
+ return err //nolint:wrapcheck
}
case ContentTypeForm:
v, err := query.Values(payload)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
- buf.WriteString(v.Encode()) // nolint: errcheck
+ buf.WriteString(v.Encode())
default:
return ErrInvalidContentType
}
@@ -82,7 +82,7 @@ func SendWebhook(ctx context.Context, w models.Webhook, event Event, payload int
id, err := uuid.NewUUID()
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
headers.Add("X-SoftServe-Delivery", id.String())
@@ -90,7 +90,7 @@ func SendWebhook(ctx context.Context, w models.Webhook, event Event, payload int
reqBody := buf.String()
if w.Secret != "" {
sig := hmac.New(sha256.New, []byte(w.Secret))
- sig.Write([]byte(reqBody)) // nolint: errcheck
+ sig.Write([]byte(reqBody))
headers.Add("X-SoftServe-Signature", "sha256="+hex.EncodeToString(sig.Sum(nil)))
}
@@ -111,17 +111,17 @@ func SendWebhook(ctx context.Context, w models.Webhook, event Event, payload int
}
if res.Body != nil {
- defer res.Body.Close() // nolint: errcheck
+ defer res.Body.Close() //nolint:errcheck
b, err := io.ReadAll(res.Body)
if err != nil {
- return err
+ return err //nolint:wrapcheck
}
resBody = string(b)
}
}
- return db.WrapError(datastore.CreateWebhookDelivery(ctx, dbx, id, w.ID, int(event), w.URL, http.MethodPost, reqErr, reqHeaders, reqBody, resStatus, resHeaders, resBody))
+ return db.WrapError(datastore.CreateWebhookDelivery(ctx, dbx, id, w.ID, int(event), w.URL, http.MethodPost, reqErr, reqHeaders, reqBody, resStatus, resHeaders, resBody)) //nolint:wrapcheck
}
// SendEvent sends a webhook event.
@@ -130,7 +130,7 @@ func SendEvent(ctx context.Context, payload EventPayload) error {
datastore := store.FromContext(ctx)
webhooks, err := datastore.GetWebhooksByRepoIDWhereEvent(ctx, dbx, payload.RepositoryID(), []int{int(payload.Event())})
if err != nil {
- return db.WrapError(err)
+ return db.WrapError(err) //nolint:wrapcheck
}
for _, w := range webhooks {
@@ -153,7 +153,7 @@ func getDefaultBranch(repo proto.Repository) (string, error) {
// This means that the repo doesn't have a default branch yet and this is
// the first push to it.
if err != nil && !errors.Is(err, git.ErrReferenceNotExist) {
- return "", err
+ return "", err //nolint:wrapcheck
}
return branch, nil
@@ -167,7 +167,7 @@ func TestScript(t *testing.T) {
// Override the database data source if we're using postgres
// so we can create a temporary database for the tests.
if cfg.DB.Driver == "postgres" {
- err, cleanup := setupPostgres(e.T(), cfg)
+ cleanup, err := setupPostgres(e.T(), cfg)
if err != nil {
return err
}
@@ -310,7 +310,7 @@ func cmdGit(key string) func(ts *testscript.TestScript, neg bool, args []string)
return func(ts *testscript.TestScript, neg bool, args []string) {
ts.Check(os.WriteFile(
ts.Getenv("SSH_KNOWN_CONFIG_FILE"),
- []byte(fmt.Sprintf(sshConfig, ts.Getenv("SSH_KNOWN_HOSTS_FILE"))),
+ fmt.Appendf(nil, sshConfig, ts.Getenv("SSH_KNOWN_HOSTS_FILE")),
0o600,
))
sshArgs := []string{
@@ -519,17 +519,14 @@ func cmdEnsureServerNotRunning(ts *testscript.TestScript, neg bool, args []strin
// verify that the server is not up
addr := net.JoinHostPort("localhost", port)
- for {
- conn, _ := net.DialTimeout(
- "tcp",
- addr,
- time.Second,
- )
- if conn != nil {
- ts.Fatalf("server is running on port %s while it should not be running", port)
- conn.Close()
- }
- break
+ conn, _ := net.DialTimeout(
+ "tcp",
+ addr,
+ time.Second,
+ )
+ if conn != nil {
+ ts.Fatalf("server is running on port %s while it should not be running", port)
+ conn.Close()
}
}
@@ -541,7 +538,7 @@ func cmdStopserver(ts *testscript.TestScript, neg bool, args []string) {
time.Sleep(time.Second * 2) // Allow some time for the server to stop
}
-func setupPostgres(t testscript.T, cfg *config.Config) (error, func()) {
+func setupPostgres(t testscript.T, cfg *config.Config) (func(), error) {
// Indicates postgres
// Create a disposable database
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
@@ -551,26 +548,26 @@ func setupPostgres(t testscript.T, cfg *config.Config) (error, func()) {
cfg.DB.DataSource = "postgres://postgres@localhost:5432/postgres?sslmode=disable"
}
- dbUrl, err := url.Parse(cfg.DB.DataSource)
+ dbURL, err := url.Parse(cfg.DB.DataSource)
if err != nil {
- return err, nil
+ return nil, err
}
- scheme := dbUrl.Scheme
+ scheme := dbURL.Scheme
if scheme == "" {
scheme = "postgres"
}
- host := dbUrl.Hostname()
+ host := dbURL.Hostname()
if host == "" {
host = "localhost"
}
connInfo := fmt.Sprintf("host=%s sslmode=disable", host)
- username := dbUrl.User.Username()
+ username := dbURL.User.Username()
if username != "" {
connInfo += fmt.Sprintf(" user=%s", username)
- password, ok := dbUrl.User.Password()
+ password, ok := dbURL.User.Password()
if ok {
username = fmt.Sprintf("%s:%s", username, password)
connInfo += fmt.Sprintf(" password=%s", password)
@@ -581,7 +578,7 @@ func setupPostgres(t testscript.T, cfg *config.Config) (error, func()) {
username = "postgres@"
}
- port := dbUrl.Port()
+ port := dbURL.Port()
if port != "" {
connInfo += fmt.Sprintf(" port=%s", port)
port = fmt.Sprintf(":%s", port)
@@ -598,14 +595,14 @@ func setupPostgres(t testscript.T, cfg *config.Config) (error, func()) {
// Create the database
dbx, err := db.Open(context.TODO(), cfg.DB.Driver, connInfo)
if err != nil {
- return err, nil
+ return nil, err
}
if _, err := dbx.Exec("CREATE DATABASE " + dbName); err != nil {
- return err, nil
+ return nil, err
}
- return nil, func() {
+ return func() {
dbx, err := db.Open(context.TODO(), cfg.DB.Driver, connInfo)
if err != nil {
t.Fatal("failed to open database", dbName, err)
@@ -614,5 +611,5 @@ func setupPostgres(t testscript.T, cfg *config.Config) (error, func()) {
if _, err := dbx.Exec("DROP DATABASE " + dbName); err != nil {
t.Fatal("failed to drop database", dbName, err)
}
- }
+ }, nil
}