chore(gonf): removed opinionated static checkers

This commit is contained in:
Julien Dessaux 2024-06-02 01:17:36 +02:00
parent efbfb291ae
commit 4a254746de
Signed by: adyxax
GPG key ID: F92E51B86E07177E
10 changed files with 56 additions and 86 deletions

View file

@ -19,12 +19,12 @@ func cmdBuild(ctx context.Context,
where FLAG can be one or more of`, flag.ContinueOnError) where FLAG can be one or more of`, flag.ContinueOnError)
hostFlag := addHostFlag(f) hostFlag := addHostFlag(f)
f.SetOutput(stderr) f.SetOutput(stderr)
_ = f.Parse(args) f.Parse(args)
if helpMode { if helpMode {
f.SetOutput(stdout) f.SetOutput(stdout)
f.Usage() f.Usage()
} }
hostDir, err := hostFlagToHostDir(f, hostFlag) hostDir, err := hostFlagToHostDir(hostFlag)
if err != nil { if err != nil {
f.Usage() f.Usage()
return err return err
@ -32,16 +32,12 @@ where FLAG can be one or more of`, flag.ContinueOnError)
return runBuild(ctx, stderr, hostDir) return runBuild(ctx, stderr, hostDir)
} }
func runBuild(ctx context.Context, stderr io.Writer, hostDir string) (err error) { func runBuild(ctx context.Context, stderr io.Writer, hostDir string) error {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
return err return err
} }
defer func() { defer os.Chdir(wd)
if e := os.Chdir(wd); err == nil {
err = e
}
}()
if err = os.Chdir(hostDir); err != nil { if err = os.Chdir(hostDir); err != nil {
return err return err
} }

View file

@ -18,17 +18,16 @@ func cmdDeploy(ctx context.Context,
where FLAG can be one or more of`, flag.ContinueOnError) where FLAG can be one or more of`, flag.ContinueOnError)
hostFlag := addHostFlag(f) hostFlag := addHostFlag(f)
f.SetOutput(stderr) f.SetOutput(stderr)
_ = f.Parse(args) f.Parse(args)
if helpMode { if helpMode {
f.SetOutput(stdout) f.SetOutput(stdout)
f.Usage() f.Usage()
} }
hostDir, err := hostFlagToHostDir(f, hostFlag) hostDir, err := hostFlagToHostDir(hostFlag)
if err != nil { if err != nil {
f.Usage() f.Usage()
return err return err
} }
_ = hostDir
return runDeploy(ctx, getenv, stdout, stderr, *hostFlag, hostDir) return runDeploy(ctx, getenv, stdout, stderr, *hostFlag, hostDir)
} }

View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"errors"
"flag" "flag"
"fmt" "fmt"
"os" "os"
@ -12,13 +11,13 @@ func addHostFlag(f *flag.FlagSet) *string {
return f.String("host", "", "(REQUIRED) a valid $GONF_CONFIG/hosts/ subdirectory") return f.String("host", "", "(REQUIRED) a valid $GONF_CONFIG/hosts/ subdirectory")
} }
func hostFlagToHostDir(f *flag.FlagSet, hostFlag *string) (string, error) { func hostFlagToHostDir(hostFlag *string) (string, error) {
return "", errors.New("required -host FLAG is missing")
if *hostFlag == "" { if *hostFlag == "" {
return "", fmt.Errorf("required -host FLAG is missing")
} }
hostDir := filepath.Join(configDir, "hosts", *hostFlag) hostDir := filepath.Join(configDir, "hosts", *hostFlag)
if info, err := os.Stat(hostDir); err != nil { if info, err := os.Stat(hostDir); err != nil {
return "", fmt.Errorf("invalid host name %s: %+v", *hostFlag, err) return "", fmt.Errorf("invalid host name %s: %w", *hostFlag, err)
} else if !info.IsDir() { } else if !info.IsDir() {
return "", fmt.Errorf("invalid host name %s: %s is not a directory", *hostFlag, hostDir) return "", fmt.Errorf("invalid host name %s: %s is not a directory", *hostFlag, hostDir)
} }

View file

@ -2,7 +2,6 @@ package main
import ( import (
"context" "context"
"errors"
"flag" "flag"
"fmt" "fmt"
"io" "io"
@ -25,7 +24,7 @@ func main() {
os.Stdout, os.Stdout,
os.Stderr, os.Stderr,
); err != nil { ); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err) fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1) os.Exit(1)
} }
} }
@ -41,7 +40,8 @@ func run(ctx context.Context,
defer cancel() defer cancel()
f := flag.NewFlagSet(`gonf COMMAND [-FLAG] f := flag.NewFlagSet(`gonf COMMAND [-FLAG]
where COMMAND is one of: where COMMAND is one of:
* build: build configurations for one or more hosts * build: build configuration for a host
* deploy: deploy configuration for a host
* help: show contextual help * help: show contextual help
* version: show build version and time * version: show build version and time
where FLAG can be one or more of`, flag.ContinueOnError) where FLAG can be one or more of`, flag.ContinueOnError)
@ -49,13 +49,11 @@ where FLAG can be one or more of`, flag.ContinueOnError)
f.BoolVar(&helpMode, "help", false, "show contextual help") f.BoolVar(&helpMode, "help", false, "show contextual help")
f.StringVar(&configDir, "config", "", "(REQUIRED for most commands) path to a gonf configurations repository (overrides the GONF_CONFIG environment variable)") f.StringVar(&configDir, "config", "", "(REQUIRED for most commands) path to a gonf configurations repository (overrides the GONF_CONFIG environment variable)")
f.SetOutput(stderr) f.SetOutput(stderr)
if err := f.Parse(args[1:]); err != nil { f.Parse(args[1:])
return err
}
if f.NArg() < 1 { if f.NArg() < 1 {
f.Usage() f.Usage()
return errors.New("no command given") return fmt.Errorf("no command given")
} }
cmd := f.Arg(0) cmd := f.Arg(0)
argsTail := f.Args()[1:] argsTail := f.Args()[1:]
@ -70,7 +68,7 @@ where FLAG can be one or more of`, flag.ContinueOnError)
configDir = getenv("GONF_CONFIG") configDir = getenv("GONF_CONFIG")
if configDir == "" { if configDir == "" {
f.Usage() f.Usage()
return errors.New("the GONF_CONFIG environment variable is unset and the -config FLAG is missing. Please use one or the other") return fmt.Errorf("the GONF_CONFIG environment variable is unset and the -config FLAG is missing. Please use one or the other")
} }
} }
switch cmd { switch cmd {

View file

@ -29,13 +29,13 @@ func newSSHClient(context context.Context,
socket := getenv("SSH_AUTH_SOCK") socket := getenv("SSH_AUTH_SOCK")
if sshc.agentConn, err = net.Dial("unix", socket); err != nil { if sshc.agentConn, err = net.Dial("unix", socket); err != nil {
return nil, fmt.Errorf("failed to open SSH_AUTH_SOCK: %+v", err) return nil, fmt.Errorf("failed to open SSH_AUTH_SOCK: %w", err)
} }
agentClient := agent.NewClient(sshc.agentConn) agentClient := agent.NewClient(sshc.agentConn)
hostKeyCallback, err := knownhosts.New(filepath.Join(getenv("HOME"), ".ssh/known_hosts")) hostKeyCallback, err := knownhosts.New(filepath.Join(getenv("HOME"), ".ssh/known_hosts"))
if err != nil { if err != nil {
return nil, fmt.Errorf("could not create hostkeycallback function: %+v", err) return nil, fmt.Errorf("failed to create hostkeycallback function: %w", err)
} }
config := &ssh.ClientConfig{ config := &ssh.ClientConfig{
@ -47,7 +47,7 @@ func newSSHClient(context context.Context,
} }
sshc.client, err = ssh.Dial("tcp", destination, config) sshc.client, err = ssh.Dial("tcp", destination, config)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to dial: %+v", err) return nil, fmt.Errorf("failed to dial: %w", err)
} }
return &sshc, nil return &sshc, nil
} }
@ -62,38 +62,31 @@ func (sshc *sshClient) Close() error {
return nil return nil
} }
func (sshc *sshClient) SendFile(ctx context.Context, func (sshc *sshClient) SendFile(
ctx context.Context,
stdout, stderr io.Writer, stdout, stderr io.Writer,
filename string, filename string,
) (err error) { ) error {
session, err := sshc.client.NewSession() session, err := sshc.client.NewSession()
if err != nil { if err != nil {
return fmt.Errorf("sshClient failed to create session: %+v", err) return fmt.Errorf("failed to create ssh client session: %w", err)
} }
defer func() { defer session.Close()
if e := session.Close(); err == nil && e != io.EOF {
err = e
}
}()
file, err := os.Open(filename) file, err := os.Open(filename)
if err != nil { if err != nil {
return fmt.Errorf("sshClient failed to open file: %+v", err) return fmt.Errorf("failed to open file: %w", err)
} }
defer func() { defer file.Close()
if e := file.Close(); err == nil {
err = e
}
}()
fi, err := file.Stat() fi, err := file.Stat()
if err != nil { if err != nil {
return fmt.Errorf("sshClient failed to stat file: %+v", err) return fmt.Errorf("failed to stat file: %w", err)
} }
w, err := session.StdinPipe() w, err := session.StdinPipe()
if err != nil { if err != nil {
return fmt.Errorf("sshClient failed to open session stdin pipe: %+v", err) return fmt.Errorf("sshClient failed to open session stdin pipe: %w", err)
} }
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
@ -102,8 +95,8 @@ func (sshc *sshClient) SendFile(ctx context.Context,
session.Stdout = stdout session.Stdout = stdout
session.Stderr = stderr session.Stderr = stderr
if err = session.Start("scp -t /usr/local/bin/gonf-run"); err != nil { if err := session.Start("scp -t /usr/local/bin/gonf-run"); err != nil {
return fmt.Errorf("sshClient failed to run scp: %+v", err) return fmt.Errorf("failed to run scp: %w", err)
} }
go func() { go func() {
defer wg.Done() defer wg.Done()
@ -114,11 +107,7 @@ func (sshc *sshClient) SendFile(ctx context.Context,
go func() { go func() {
defer wg.Done() defer wg.Done()
defer func() { defer w.Close()
if e := w.Close(); e != nil {
errCh <- e
}
}()
// Write "C{mode} {size} {filename}\n" // Write "C{mode} {size} {filename}\n"
if _, e := fmt.Fprintf(w, "C%#o %d %s\n", 0700, fi.Size(), "gonf-run"); e != nil { if _, e := fmt.Fprintf(w, "C%#o %d %s\n", 0700, fi.Size(), "gonf-run"); e != nil {
errCh <- e errCh <- e
@ -135,8 +124,7 @@ func (sshc *sshClient) SendFile(ctx context.Context,
} }
}() }()
var cancel context.CancelFunc ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
defer cancel() defer cancel()
// wait for all waitgroup.Done() or the timeout // wait for all waitgroup.Done() or the timeout
@ -157,6 +145,5 @@ func (sshc *sshClient) SendFile(ctx context.Context,
return err return err
} }
} }
return nil return nil
} }

View file

@ -139,16 +139,12 @@ func resolveFiles() (status Status) {
return return
} }
func sha256sumOfFile(filename string) (hash []byte, err error) { func sha256sumOfFile(filename string) ([]byte, error) {
f, err := os.Open(filename) f, err := os.Open(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer func() { defer f.Close()
if e := f.Close(); err == nil {
err = e
}
}()
h := sha256.New() h := sha256.New()
if _, err := io.Copy(h, f); err != nil { if _, err := io.Copy(h, f); err != nil {
return nil, err return nil, err
@ -156,16 +152,12 @@ func sha256sumOfFile(filename string) (hash []byte, err error) {
return h.Sum(nil), nil return h.Sum(nil), nil
} }
func writeFile(filename string, contents []byte) (err error) { func writeFile(filename string, contents []byte) error {
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
return err return err
} }
defer func() { defer f.Close()
if e := f.Close(); err == nil {
err = e
}
}()
_, err = f.Write(contents) _, err = f.Write(contents)
return err return err
} }

View file

@ -1,7 +1,7 @@
package gonf package gonf
import ( import (
"errors" "fmt"
"io/fs" "io/fs"
"os" "os"
"os/user" "os/user"
@ -29,10 +29,10 @@ func (p *Permissions) resolve(filename string) (Status, error) {
if group, err := user.LookupGroup(p.group.String()); err != nil { if group, err := user.LookupGroup(p.group.String()); err != nil {
return BROKEN, err return BROKEN, err
} else { } else {
if groupID, err := strconv.Atoi(group.Gid); err != nil { if groupId, err := strconv.Atoi(group.Gid); err != nil {
return BROKEN, err return BROKEN, err
} else { } else {
g = &IntValue{groupID} g = &IntValue{groupId}
p.group = g p.group = g
} }
} }
@ -46,10 +46,10 @@ func (p *Permissions) resolve(filename string) (Status, error) {
if user, err := user.Lookup(p.user.String()); err != nil { if user, err := user.Lookup(p.user.String()); err != nil {
return BROKEN, err return BROKEN, err
} else { } else {
if userID, err := strconv.Atoi(user.Uid); err != nil { if userId, err := strconv.Atoi(user.Uid); err != nil {
return BROKEN, err return BROKEN, err
} else { } else {
u = &IntValue{userID} u = &IntValue{userId}
p.group = u p.group = u
} }
} }
@ -75,7 +75,7 @@ func (p *Permissions) resolve(filename string) (Status, error) {
status = REPAIRED status = REPAIRED
} }
} else { } else {
return BROKEN, errors.New("unsupported operating system") return BROKEN, fmt.Errorf("unsupported operating system")
} }
} }
return status, nil return status, nil

View file

@ -28,17 +28,17 @@ func FilterSlice[T any](slice *[]T, predicate func(T) bool) {
func makeDirectoriesHierarchy(dir string, perms *Permissions) (Status, error) { func makeDirectoriesHierarchy(dir string, perms *Permissions) (Status, error) {
if _, err := os.Lstat(dir); err != nil { if _, err := os.Lstat(dir); err != nil {
if errors.Is(err, fs.ErrNotExist) { if errors.Is(err, fs.ErrNotExist) {
if _, err = makeDirectoriesHierarchy(filepath.Dir(dir), perms); err != nil { if _, err := makeDirectoriesHierarchy(filepath.Dir(dir), perms); err != nil {
return BROKEN, err return BROKEN, err
} }
var m int m, err := perms.mode.Int()
if m, err = perms.mode.Int(); err != nil { if err != nil {
return BROKEN, err return BROKEN, err
} }
if err = os.Mkdir(dir, fs.FileMode(m)); err != nil { if err := os.Mkdir(dir, fs.FileMode(m)); err != nil {
return BROKEN, err return BROKEN, err
} }
if _, err = perms.resolve(dir); err != nil { if _, err := perms.resolve(dir); err != nil {
return BROKEN, err return BROKEN, err
} }
return REPAIRED, nil return REPAIRED, nil

View file

@ -14,20 +14,19 @@ type Value interface {
} }
func interfaceToValue(v any) Value { func interfaceToValue(v any) Value {
if vv, ok := v.([]byte); ok { switch vv := v.(type) {
case []byte:
return &BytesValue{vv} return &BytesValue{vv}
} case int:
if vv, ok := v.(int); ok {
return &IntValue{vv} return &IntValue{vv}
} case string:
if vv, ok := v.(string); ok {
return &StringValue{vv} return &StringValue{vv}
} case *VariablePromise:
if vv, ok := v.(*VariablePromise); ok {
return vv return vv
default:
slog.Error("interfaceToValue", "value", v, "error", "Not Implemented")
panic(fmt.Sprintf("interfaceToValue cannot take type %T as argument. Value was %#v.", v, v))
} }
slog.Error("interfaceToValue", "value", v, "error", "Not Implemented")
panic(fmt.Sprintf("interfaceToValue cannot take type %T as argument. Value was %#v.", v, v))
} }
func interfaceToTemplateValue(v any) Value { func interfaceToTemplateValue(v any) Value {

View file

@ -1,7 +1,7 @@
package systemd package systemd
import ( import (
"errors" "fmt"
"os/exec" "os/exec"
gonf "git.adyxax.org/adyxax/gonf/v2/pkg" gonf "git.adyxax.org/adyxax/gonf/v2/pkg"
@ -64,6 +64,6 @@ func systemdService(name, state string) (gonf.Status, error) {
return gonf.KEPT, nil return gonf.KEPT, nil
} }
default: default:
return gonf.BROKEN, errors.New("unsupported systemctl operation " + state) return gonf.BROKEN, fmt.Errorf("unsupported systemctl operation " + state)
} }
} }