Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use slog in place of waterlog #14

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-Present Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
2 changes: 1 addition & 1 deletion cli/graph.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-Present Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
6 changes: 3 additions & 3 deletions cli/list.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-Present Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,8 +16,8 @@ package cli

import (
"fmt"
"log/slog"

log "github.com/DataDrake/waterlog"
"github.com/getsolus/usysconf/config"
)

Expand All @@ -28,7 +28,7 @@ func (l list) Run(flags GlobalFlags) error {
if err != nil {
return fmt.Errorf("failed to load triggers: %w", err)
}
log.Info("Available triggers:\n\n")
slog.Info("Available triggers:")
tm.Print(flags.Chroot, flags.Live)
return nil
}
6 changes: 1 addition & 5 deletions cli/run.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-Present Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -19,7 +19,6 @@ import (
"fmt"
"os"

log "github.com/DataDrake/waterlog"
"github.com/getsolus/usysconf/config"
"github.com/getsolus/usysconf/triggers"
"github.com/getsolus/usysconf/util"
Expand All @@ -33,9 +32,6 @@ type run struct {
}

func (r run) Run(flags GlobalFlags) error {
log.Debugln("Started usysconf")
defer log.Debugln("Exiting usysconf")

if os.Geteuid() != 0 {
return errors.New("you must have root privileges to run triggers")
}
Expand Down
113 changes: 44 additions & 69 deletions config/load.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-2020 Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,32 +16,29 @@ package config

import (
"fmt"
log "github.com/DataDrake/waterlog"
"github.com/getsolus/usysconf/triggers"
"io/ioutil"
"log/slog"
"os"
"os/user"
"path/filepath"
"strings"

"github.com/getsolus/usysconf/triggers"
)

// Load reads in all of the trigger files in a directory
func Load(path string) (tm triggers.Map, err error) {
tm = make(triggers.Map)
entries, err := ioutil.ReadDir(path)
// Load reads in all of the trigger files in a directory.
func Load(path string) (triggers.Map, error) {
logger := slog.With("path", path)

entries, err := os.ReadDir(path)
if err != nil {
log.Debugf("Skipped directory '%s':\n", path)
if os.IsNotExist(err) {
log.Debugf(" Not found.\n")
err = nil
return
logger.Debug("Directory not found")
return nil, nil
}
log.Debugf(" Failed to read triggers, reason: %s\n", err)
err = nil
return
return nil, fmt.Errorf("failed to read triggers: %w", err)
}
log.Debugf("Scanning directory '%s':\n", path)
found := false
tm := make(triggers.Map, len(entries))
logger.Debug("Scanning directory")
for _, entry := range entries {
if entry.IsDir() {
continue
Expand All @@ -54,73 +51,51 @@ func Load(path string) (tm triggers.Map, err error) {
Name: strings.TrimSuffix(name, ".toml"),
Path: filepath.Clean(filepath.Join(path, name)),
}
// found trigger
log.Debugf(" Found '%s'\n", t.Name)
found = true
if err = t.Load(t.Path); err == nil {
// Check the config for problems
err = t.Validate()
logger.Debug("Trigger found", "name", t.Name)
err = t.Load(t.Path)
if err != nil {
return nil, err
}
err = t.Validate()
if err != nil {
err = fmt.Errorf("failed to read '%s' from '%s' reason: %s", name, path, err.Error())
return
return nil, fmt.Errorf("failed to read %s from %s: %w", name, path, err)
}
// save trigger
tm[t.Name] = t
}
if !found {
log.Debugln(" No triggers found.")
if len(tm) == 0 {
logger.Debug("No triggers found")
}
return
return tm, nil
}

// LoadAll will check the system, user, and home directories, in that order, for a
// configuration file that has the passed name parameter, without the extension
// and will create a config with the specified valus.
func LoadAll() (tm triggers.Map, err error) {
// Read from System directory
tm, err = Load(SysDir)
if err != nil {
return
}
// Read from User Directory
tm2, err := Load(UsrDir)
if err != nil {
return
func LoadAll() (triggers.Map, error) {
paths := []string{SysDir, UsrDir}
if p, err := os.UserHomeDir(); err != nil {
paths = append(paths, p)
}
tm.Merge(tm2)
// Read from Home directory
home, err := os.UserHomeDir()
if err != nil {
return
}
// replace the root directory with the user home directory executing usysconf
if os.Getuid() == 0 {
username := os.Getenv("SUDO_USER")
if username == "" || username == "root" {
// if user is not found or it is actually being run by root without sudo return
log.Warnln("Home Triggers not loaded")
goto CHECK
uname := os.Getenv("SUDO_USER")
if uname != "" && uname != "root" {
u, err := user.Lookup(uname)
if err != nil {
slog.Warn("Failed to lookup underlying user", "name", uname, "reason", err)
} else {
paths = append(paths, filepath.Join(u.HomeDir, ".config", "usysconf.d"))
}
}
// Lookup sudo user's home directory
u, err := user.Lookup(username)
}

tm := make(triggers.Map)
for _, path := range paths {
trig, err := Load(path)
if err != nil {
log.Warnf("Failed to lookup user '%s', reason: %s\n", username, err)
} else {
home = u.HomeDir
return nil, err
}
tm.Merge(trig)
}
// Load configs from the user's Home directory
tm2, err = Load(filepath.Join(home, ".config", "usysconf.d"))
if err != nil {
return
}
tm.Merge(tm2)
CHECK:
// check for lack of triggers
if len(tm) == 0 {
log.Fatalln("No triggers available")
}
log.Goodf("Found '%d' triggers\n", len(tm))
return
slog.Info("Total triggers", "count", len(tm))
return tm, nil
}
17 changes: 10 additions & 7 deletions deps/graph.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-2020 Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -15,7 +15,8 @@
package deps

import (
log "github.com/DataDrake/waterlog"
"fmt"
"log/slog"
"sort"
"strings"
)
Expand Down Expand Up @@ -46,7 +47,7 @@ func (g Graph) CheckMissing(triggers []string) {
}
}
if !found {
log.Warnf("Dependency '%s' of trigger '%s' does not exist\n", dep, name)
slog.Warn("Dependency does not exist", "parent", name, "child", dep)
}
}
}
Expand All @@ -64,7 +65,9 @@ func (g Graph) CheckCircular() {
}
found = found[1:]
}
log.Fatalf("Circular dependency: %s\n", strings.Join(found, " -> "))
// TODO: Return an error instead of panicking.
slog.Error("Circular dependency", "chain", strings.Join(found, " -> "))
panic("Circular dependency")
}
}
}
Expand Down Expand Up @@ -168,13 +171,13 @@ func (g Graph) Print() {
names = append(names, name)
}
sort.Strings(names)
log.Println("digraph {")
fmt.Println("digraph {")
for _, name := range names {
deps := g[name]
sort.Strings(deps)
for _, dep := range deps {
log.Printf("\t\"%s\" -> \"%s\";\n", name, dep)
fmt.Printf("\t\"%s\" -> \"%s\";\n", name, dep)
}
}
log.Println("}")
fmt.Println("}")
}
8 changes: 2 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
module github.com/getsolus/usysconf

go 1.20
go 1.21

require (
github.com/BurntSushi/toml v1.3.2
github.com/DataDrake/waterlog v1.2.0
github.com/alecthomas/kong v0.8.0
github.com/fxamacker/cbor/v2 v2.5.0
)

require (
github.com/DataDrake/flair v0.5.1 // indirect
github.com/x448/float16 v0.8.4 // indirect
)
require github.com/x448/float16 v0.8.4 // indirect
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/DataDrake/flair v0.5.1 h1:JHWOoBRiQGWg+k2bV2Mje2YmDtRjhMj51yDxQkzidWI=
github.com/DataDrake/flair v0.5.1/go.mod h1:3KgdmkL8eJDbg/HdMwlHkeYH/mpSy/hsQvxYQFp9A/Y=
github.com/DataDrake/waterlog v1.2.0 h1:T3Hs0D6YOQfz6GtViw+fYSIGpGimU41FubcxQQzaeHM=
github.com/DataDrake/waterlog v1.2.0/go.mod h1:xSKEWChL8698jwSJSyjKPIpFpj/K5n+Eif2ztYXDjJI=
github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0=
github.com/alecthomas/kong v0.8.0 h1:ryDCzutfIqJPnNn0omnrgHLbAggDQM2VWHikE1xqK7s=
github.com/alecthomas/kong v0.8.0/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
Expand Down
17 changes: 8 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-2020 Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -15,25 +15,24 @@
package main

import (
log2 "log"
"log/slog"
"os"

log "github.com/DataDrake/waterlog"
"github.com/DataDrake/waterlog/format"
"github.com/DataDrake/waterlog/level"
"github.com/getsolus/usysconf/cli"
)

func main() {
ctx, flags := cli.Parse()

logOpt := &slog.HandlerOptions{}
if flags.Debug {
log.SetLevel(level.Debug)
logOpt.Level = slog.LevelDebug
}
log.SetFormat(format.Min)
log.SetFlags(log2.Ltime | log2.Ldate | log2.LUTC)
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, logOpt)))

err := ctx.Run(flags)
if err != nil {
log.Fatal(err)
slog.Error(err.Error())
os.Exit(1)
}
}
10 changes: 5 additions & 5 deletions state/map.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2019-2020 Solus Project
// Copyright © Solus Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -16,14 +16,14 @@ package state

import (
"fmt"
"log/slog"
"os"
"path/filepath"
"regexp"
"strings"
"time"

log "github.com/DataDrake/waterlog"
cbor "github.com/fxamacker/cbor/v2"
"github.com/fxamacker/cbor/v2"
)

// Path is the location of the serialized system state directory
Expand Down Expand Up @@ -110,7 +110,7 @@ func (m Map) Search(paths []string) Map {
search = "^" + strings.ReplaceAll(search, string(filepath.Separator), "\\"+string(filepath.Separator))
regex, err := regexp.Compile(search)
if err != nil {
log.Warnf("Could not convert path to regex: %s\n", path)
slog.Warn("Could not convert to regex", "path", path)
continue
}
for k, v := range m {
Expand All @@ -133,7 +133,7 @@ func (m Map) Exclude(patterns []string) Map {
exclude := strings.ReplaceAll(pattern, "*", ".*")
regex, err := regexp.Compile(exclude)
if err != nil {
log.Warnf("Could not convert pattern to regex: %s\n", pattern)
slog.Warn("Could not convert to regex", "pattern", pattern)
continue
}
regexes = append(regexes, regex)
Expand Down
Loading