Compare commits
4 Commits
feat/home-
...
cicd/fix-n
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dbc845bb21 | ||
|
|
49948de0ed | ||
|
|
933da8bad2 | ||
|
|
9b09ee7c6c |
8
.github/workflows/ci.yaml
vendored
8
.github/workflows/ci.yaml
vendored
@@ -32,9 +32,9 @@ jobs:
|
||||
go-version: "1.25.0"
|
||||
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v8
|
||||
uses: golangci/golangci-lint-action@v6
|
||||
with:
|
||||
version: v2.5.0
|
||||
version: latest
|
||||
|
||||
nix-build:
|
||||
strategy:
|
||||
@@ -44,7 +44,9 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: DeterminateSystems/nix-installer-action@v17
|
||||
- uses: cachix/install-nix-action@v30
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: nix-community/cache-nix-action@v6
|
||||
with:
|
||||
|
||||
72
README.md
72
README.md
@@ -6,29 +6,13 @@ a friendlier `ss` / `netstat` for humans. inspect network connections with a cle
|
||||
|
||||
## install
|
||||
|
||||
### homebrew
|
||||
|
||||
```bash
|
||||
brew install snitch
|
||||
```
|
||||
|
||||
> thanks to [@bevanjkay](https://github.com/bevanjkay) for adding snitch to homebrew-core
|
||||
|
||||
### go
|
||||
|
||||
```bash
|
||||
go install github.com/karol-broda/snitch@latest
|
||||
```
|
||||
|
||||
### nixpkgs
|
||||
|
||||
```bash
|
||||
nix-env -iA nixpkgs.snitch
|
||||
```
|
||||
|
||||
> thanks to [@DieracDelta](https://github.com/DieracDelta) for adding snitch to nixpkgs
|
||||
|
||||
### nixos / nix (flake)
|
||||
### nixos / nix
|
||||
|
||||
```bash
|
||||
# try it
|
||||
@@ -44,45 +28,6 @@ nix profile install github:karol-broda/snitch
|
||||
# then use: inputs.snitch.packages.${system}.default
|
||||
```
|
||||
|
||||
### home-manager (flake)
|
||||
|
||||
add snitch to your flake inputs and import the home-manager module:
|
||||
|
||||
```nix
|
||||
{
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
home-manager.url = "github:nix-community/home-manager";
|
||||
snitch.url = "github:karol-broda/snitch";
|
||||
};
|
||||
|
||||
outputs = { nixpkgs, home-manager, snitch, ... }: {
|
||||
homeConfigurations."user" = home-manager.lib.homeManagerConfiguration {
|
||||
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||
modules = [
|
||||
snitch.homeManagerModules.default
|
||||
{
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
# optional: use the flake's package instead of nixpkgs
|
||||
# package = snitch.packages.x86_64-linux.default;
|
||||
settings = {
|
||||
defaults = {
|
||||
theme = "catppuccin-mocha";
|
||||
interval = "2s";
|
||||
resolve = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
available themes: `ansi`, `catppuccin-mocha`, `catppuccin-macchiato`, `catppuccin-frappe`, `catppuccin-latte`, `gruvbox-dark`, `gruvbox-light`, `dracula`, `nord`, `tokyo-night`, `tokyo-night-storm`, `tokyo-night-light`, `solarized-dark`, `solarized-light`, `one-dark`, `mono`
|
||||
|
||||
### arch linux (aur)
|
||||
|
||||
```bash
|
||||
@@ -277,23 +222,8 @@ optional config file at `~/.config/snitch/snitch.toml`:
|
||||
numeric = false # disable name resolution
|
||||
dns_cache = true # cache dns lookups (set to false to disable)
|
||||
theme = "auto" # color theme: auto, dark, light, mono
|
||||
|
||||
[tui]
|
||||
remember_state = false # remember view options between sessions
|
||||
```
|
||||
|
||||
### remembering view options
|
||||
|
||||
when `remember_state = true`, the tui will save and restore:
|
||||
|
||||
- filter toggles (tcp/udp, listen/established/other)
|
||||
- sort field and direction
|
||||
- address and port resolution settings
|
||||
|
||||
state is saved to `$XDG_STATE_HOME/snitch/tui.json` (defaults to `~/.local/state/snitch/tui.json`).
|
||||
|
||||
cli flags always take priority over saved state.
|
||||
|
||||
### environment variables
|
||||
|
||||
```bash
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
"github.com/karol-broda/snitch/internal/testutil"
|
||||
)
|
||||
|
||||
@@ -408,16 +407,16 @@ func TestEnvironmentVariables(t *testing.T) {
|
||||
oldEnvVars := make(map[string]string)
|
||||
for key, value := range tt.envVars {
|
||||
oldEnvVars[key] = os.Getenv(key)
|
||||
errutil.Setenv(key, value)
|
||||
os.Setenv(key, value)
|
||||
}
|
||||
|
||||
// Clean up environment variables
|
||||
defer func() {
|
||||
for key, oldValue := range oldEnvVars {
|
||||
if oldValue == "" {
|
||||
errutil.Unsetenv(key)
|
||||
os.Unsetenv(key)
|
||||
} else {
|
||||
errutil.Setenv(key, oldValue)
|
||||
os.Setenv(key, oldValue)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
16
cmd/ls.go
16
cmd/ls.go
@@ -8,18 +8,16 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/color"
|
||||
"github.com/karol-broda/snitch/internal/config"
|
||||
"github.com/karol-broda/snitch/internal/resolver"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/color"
|
||||
"github.com/karol-broda/snitch/internal/config"
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
"github.com/karol-broda/snitch/internal/resolver"
|
||||
"github.com/tidwall/pretty"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
@@ -187,7 +185,7 @@ func printCSV(conns []collector.Connection, headers bool, timestamp bool, select
|
||||
|
||||
func printPlainTable(conns []collector.Connection, headers bool, timestamp bool, selectedFields []string) {
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||
defer errutil.Flush(w)
|
||||
defer w.Flush()
|
||||
|
||||
if len(selectedFields) == 0 {
|
||||
selectedFields = []string{"pid", "process", "user", "proto", "state", "laddr", "lport", "raddr", "rport"}
|
||||
@@ -201,7 +199,7 @@ func printPlainTable(conns []collector.Connection, headers bool, timestamp bool,
|
||||
for _, field := range selectedFields {
|
||||
headerRow = append(headerRow, strings.ToUpper(field))
|
||||
}
|
||||
errutil.Ignore(fmt.Fprintln(w, strings.Join(headerRow, "\t")))
|
||||
fmt.Fprintln(w, strings.Join(headerRow, "\t"))
|
||||
}
|
||||
|
||||
for _, conn := range conns {
|
||||
@@ -210,7 +208,7 @@ func printPlainTable(conns []collector.Connection, headers bool, timestamp bool,
|
||||
for _, field := range selectedFields {
|
||||
row = append(row, fieldMap[field])
|
||||
}
|
||||
errutil.Ignore(fmt.Fprintln(w, strings.Join(row, "\t")))
|
||||
fmt.Fprintln(w, strings.Join(row, "\t"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
34
cmd/stats.go
34
cmd/stats.go
@@ -8,6 +8,7 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -16,9 +17,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
)
|
||||
|
||||
type StatsData struct {
|
||||
@@ -229,19 +227,19 @@ func printStatsCSV(stats *StatsData, headers bool) {
|
||||
|
||||
func printStatsTable(stats *StatsData, headers bool) {
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||
defer errutil.Flush(w)
|
||||
defer w.Flush()
|
||||
|
||||
if headers {
|
||||
errutil.Ignore(fmt.Fprintf(w, "TIMESTAMP\t%s\n", stats.Timestamp.Format(time.RFC3339)))
|
||||
errutil.Ignore(fmt.Fprintf(w, "TOTAL CONNECTIONS\t%d\n", stats.Total))
|
||||
errutil.Ignore(fmt.Fprintln(w))
|
||||
fmt.Fprintf(w, "TIMESTAMP\t%s\n", stats.Timestamp.Format(time.RFC3339))
|
||||
fmt.Fprintf(w, "TOTAL CONNECTIONS\t%d\n", stats.Total)
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
|
||||
// Protocol breakdown
|
||||
if len(stats.ByProto) > 0 {
|
||||
if headers {
|
||||
errutil.Ignore(fmt.Fprintln(w, "BY PROTOCOL:"))
|
||||
errutil.Ignore(fmt.Fprintln(w, "PROTO\tCOUNT"))
|
||||
fmt.Fprintln(w, "BY PROTOCOL:")
|
||||
fmt.Fprintln(w, "PROTO\tCOUNT")
|
||||
}
|
||||
protocols := make([]string, 0, len(stats.ByProto))
|
||||
for proto := range stats.ByProto {
|
||||
@@ -249,16 +247,16 @@ func printStatsTable(stats *StatsData, headers bool) {
|
||||
}
|
||||
sort.Strings(protocols)
|
||||
for _, proto := range protocols {
|
||||
errutil.Ignore(fmt.Fprintf(w, "%s\t%d\n", strings.ToUpper(proto), stats.ByProto[proto]))
|
||||
fmt.Fprintf(w, "%s\t%d\n", strings.ToUpper(proto), stats.ByProto[proto])
|
||||
}
|
||||
errutil.Ignore(fmt.Fprintln(w))
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
|
||||
// State breakdown
|
||||
if len(stats.ByState) > 0 {
|
||||
if headers {
|
||||
errutil.Ignore(fmt.Fprintln(w, "BY STATE:"))
|
||||
errutil.Ignore(fmt.Fprintln(w, "STATE\tCOUNT"))
|
||||
fmt.Fprintln(w, "BY STATE:")
|
||||
fmt.Fprintln(w, "STATE\tCOUNT")
|
||||
}
|
||||
states := make([]string, 0, len(stats.ByState))
|
||||
for state := range stats.ByState {
|
||||
@@ -266,16 +264,16 @@ func printStatsTable(stats *StatsData, headers bool) {
|
||||
}
|
||||
sort.Strings(states)
|
||||
for _, state := range states {
|
||||
errutil.Ignore(fmt.Fprintf(w, "%s\t%d\n", state, stats.ByState[state]))
|
||||
fmt.Fprintf(w, "%s\t%d\n", state, stats.ByState[state])
|
||||
}
|
||||
errutil.Ignore(fmt.Fprintln(w))
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
|
||||
// Process breakdown (top 10)
|
||||
if len(stats.ByProc) > 0 {
|
||||
if headers {
|
||||
errutil.Ignore(fmt.Fprintln(w, "BY PROCESS (TOP 10):"))
|
||||
errutil.Ignore(fmt.Fprintln(w, "PID\tPROCESS\tCOUNT"))
|
||||
fmt.Fprintln(w, "BY PROCESS (TOP 10):")
|
||||
fmt.Fprintln(w, "PID\tPROCESS\tCOUNT")
|
||||
}
|
||||
limit := 10
|
||||
if len(stats.ByProc) < limit {
|
||||
@@ -283,7 +281,7 @@ func printStatsTable(stats *StatsData, headers bool) {
|
||||
}
|
||||
for i := 0; i < limit; i++ {
|
||||
proc := stats.ByProc[i]
|
||||
errutil.Ignore(fmt.Fprintf(w, "%d\t%s\t%d\n", proc.PID, proc.Process, proc.Count))
|
||||
fmt.Fprintf(w, "%d\t%s\t%d\n", proc.PID, proc.Process, proc.Count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11
cmd/top.go
11
cmd/top.go
@@ -33,12 +33,11 @@ var topCmd = &cobra.Command{
|
||||
resolver.SetNoCache(effectiveNoCache)
|
||||
|
||||
opts := tui.Options{
|
||||
Theme: theme,
|
||||
Interval: topInterval,
|
||||
ResolveAddrs: resolveAddrs,
|
||||
ResolvePorts: resolvePorts,
|
||||
NoCache: effectiveNoCache,
|
||||
RememberState: cfg.TUI.RememberState,
|
||||
Theme: theme,
|
||||
Interval: topInterval,
|
||||
ResolveAddrs: resolveAddrs,
|
||||
ResolvePorts: resolvePorts,
|
||||
NoCache: effectiveNoCache,
|
||||
}
|
||||
|
||||
// if any filter flag is set, use exclusive mode
|
||||
|
||||
195
cmd/upgrade.go
195
cmd/upgrade.go
@@ -18,7 +18,6 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
"github.com/karol-broda/snitch/internal/tui"
|
||||
)
|
||||
|
||||
@@ -94,13 +93,13 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
|
||||
|
||||
if currentClean == latestClean {
|
||||
green := color.New(color.FgGreen)
|
||||
errutil.Println(green, tui.SymbolSuccess+" you are running the latest version")
|
||||
green.Println(tui.SymbolSuccess + " you are running the latest version")
|
||||
return nil
|
||||
}
|
||||
|
||||
if current == "dev" {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" you are running a development build")
|
||||
yellow.Println(tui.SymbolWarning + " you are running a development build")
|
||||
fmt.Println()
|
||||
fmt.Println("use one of the methods below to install a release version:")
|
||||
fmt.Println()
|
||||
@@ -109,7 +108,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
green := color.New(color.FgGreen, color.Bold)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" update available: %s "+tui.SymbolArrowRight+" %s\n", current, latest)
|
||||
green.Printf(tui.SymbolSuccess+" update available: %s "+tui.SymbolArrowRight+" %s\n", current, latest)
|
||||
fmt.Println()
|
||||
|
||||
if !upgradeYes {
|
||||
@@ -117,8 +116,8 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
|
||||
fmt.Println()
|
||||
faint := color.New(color.Faint)
|
||||
cmdStyle := color.New(color.FgCyan)
|
||||
errutil.Print(faint, " in-place ")
|
||||
errutil.Println(cmdStyle, "snitch upgrade --yes")
|
||||
faint.Print(" in-place ")
|
||||
cmdStyle.Println("snitch upgrade --yes")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -135,17 +134,17 @@ func handleSpecificVersion(current, target string) error {
|
||||
|
||||
if isVersionLower(targetClean, firstUpgradeVersion) {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Printf(yellow, tui.SymbolWarning+" warning: the upgrade command was introduced in v%s\n", firstUpgradeVersion)
|
||||
yellow.Printf(tui.SymbolWarning+" warning: the upgrade command was introduced in v%s\n", firstUpgradeVersion)
|
||||
faint := color.New(color.Faint)
|
||||
errutil.Printf(faint, " version %s does not include this command\n", target)
|
||||
errutil.Println(faint, " you will need to use other methods to upgrade from that version")
|
||||
faint.Printf(" version %s does not include this command\n", target)
|
||||
faint.Println(" you will need to use other methods to upgrade from that version")
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
currentClean := strings.TrimPrefix(current, "v")
|
||||
if currentClean == targetClean {
|
||||
green := color.New(color.FgGreen)
|
||||
errutil.Println(green, tui.SymbolSuccess+" you are already running this version")
|
||||
green.Println(tui.SymbolSuccess + " you are already running this version")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -154,15 +153,15 @@ func handleSpecificVersion(current, target string) error {
|
||||
cmdStyle := color.New(color.FgCyan)
|
||||
if isVersionLower(targetClean, currentClean) {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Printf(yellow, tui.SymbolArrowDown+" this will downgrade from %s to %s\n", current, target)
|
||||
yellow.Printf(tui.SymbolArrowDown+" this will downgrade from %s to %s\n", current, target)
|
||||
} else {
|
||||
green := color.New(color.FgGreen)
|
||||
errutil.Printf(green, tui.SymbolArrowUp+" this will upgrade from %s to %s\n", current, target)
|
||||
green.Printf(tui.SymbolArrowUp+" this will upgrade from %s to %s\n", current, target)
|
||||
}
|
||||
fmt.Println()
|
||||
errutil.Print(faint, "run ")
|
||||
errutil.Printf(cmdStyle, "snitch upgrade --version %s --yes", target)
|
||||
errutil.Println(faint, " to proceed")
|
||||
faint.Print("run ")
|
||||
cmdStyle.Printf("snitch upgrade --version %s --yes", target)
|
||||
faint.Println(" to proceed")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -176,20 +175,20 @@ func handleNixUpgrade(current, latest string) error {
|
||||
currentCommit := extractCommitFromVersion(current)
|
||||
dirty := isNixDirty(current)
|
||||
|
||||
errutil.Print(faint, "current ")
|
||||
errutil.Print(version, current)
|
||||
faint.Print("current ")
|
||||
version.Print(current)
|
||||
if currentCommit != "" {
|
||||
errutil.Printf(faint, " (commit %s)", currentCommit)
|
||||
faint.Printf(" (commit %s)", currentCommit)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
errutil.Print(faint, "latest ")
|
||||
errutil.Println(version, latest)
|
||||
faint.Print("latest ")
|
||||
version.Println(latest)
|
||||
fmt.Println()
|
||||
|
||||
if dirty {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" you are running a dirty nix build (uncommitted changes)")
|
||||
yellow.Println(tui.SymbolWarning + " you are running a dirty nix build (uncommitted changes)")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
@@ -197,8 +196,8 @@ func handleNixUpgrade(current, latest string) error {
|
||||
|
||||
if currentCommit == "" {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" this is a nix installation")
|
||||
errutil.Println(faint, " nix store is immutable; use nix commands to upgrade")
|
||||
yellow.Println(tui.SymbolWarning + " this is a nix installation")
|
||||
faint.Println(" nix store is immutable; use nix commands to upgrade")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
@@ -206,11 +205,11 @@ func handleNixUpgrade(current, latest string) error {
|
||||
|
||||
releaseCommit, err := fetchCommitForTag(latest)
|
||||
if err != nil {
|
||||
errutil.Printf(faint, " (could not fetch release commit: %v)\n", err)
|
||||
faint.Printf(" (could not fetch release commit: %v)\n", err)
|
||||
fmt.Println()
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" this is a nix installation")
|
||||
errutil.Println(faint, " nix store is immutable; use nix commands to upgrade")
|
||||
yellow.Println(tui.SymbolWarning + " this is a nix installation")
|
||||
faint.Println(" nix store is immutable; use nix commands to upgrade")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
@@ -223,20 +222,20 @@ func handleNixUpgrade(current, latest string) error {
|
||||
|
||||
if strings.HasPrefix(releaseCommit, currentCommit) || strings.HasPrefix(currentCommit, releaseShort) {
|
||||
green := color.New(color.FgGreen)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" you are running %s (commit %s)\n", latest, releaseShort)
|
||||
green.Printf(tui.SymbolSuccess+" you are running %s (commit %s)\n", latest, releaseShort)
|
||||
return nil
|
||||
}
|
||||
|
||||
comparison, err := compareCommits(latest, currentCommit)
|
||||
if err != nil {
|
||||
green := color.New(color.FgGreen, color.Bold)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" update available: %s "+tui.SymbolArrowRight+" %s\n", currentCommit, latest)
|
||||
errutil.Printf(faint, " your commit: %s\n", currentCommit)
|
||||
errutil.Printf(faint, " release: %s (%s)\n", releaseShort, latest)
|
||||
green.Printf(tui.SymbolSuccess+" update available: %s "+tui.SymbolArrowRight+" %s\n", currentCommit, latest)
|
||||
faint.Printf(" your commit: %s\n", currentCommit)
|
||||
faint.Printf(" release: %s (%s)\n", releaseShort, latest)
|
||||
fmt.Println()
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" this is a nix installation")
|
||||
errutil.Println(faint, " nix store is immutable; use nix commands to upgrade")
|
||||
yellow.Println(tui.SymbolWarning + " this is a nix installation")
|
||||
faint.Println(" nix store is immutable; use nix commands to upgrade")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
@@ -244,30 +243,30 @@ func handleNixUpgrade(current, latest string) error {
|
||||
|
||||
if comparison.AheadBy > 0 {
|
||||
cyan := color.New(color.FgCyan)
|
||||
errutil.Printf(cyan, tui.SymbolArrowUp+" you are %d commit(s) ahead of %s\n", comparison.AheadBy, latest)
|
||||
errutil.Printf(faint, " your commit: %s\n", currentCommit)
|
||||
errutil.Printf(faint, " release: %s (%s)\n", releaseShort, latest)
|
||||
cyan.Printf(tui.SymbolArrowUp+" you are %d commit(s) ahead of %s\n", comparison.AheadBy, latest)
|
||||
faint.Printf(" your commit: %s\n", currentCommit)
|
||||
faint.Printf(" release: %s (%s)\n", releaseShort, latest)
|
||||
fmt.Println()
|
||||
errutil.Println(faint, "you are running a newer build than the latest release")
|
||||
faint.Println("you are running a newer build than the latest release")
|
||||
return nil
|
||||
}
|
||||
|
||||
if comparison.BehindBy > 0 {
|
||||
green := color.New(color.FgGreen, color.Bold)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" update available: %d commit(s) behind %s\n", comparison.BehindBy, latest)
|
||||
errutil.Printf(faint, " your commit: %s\n", currentCommit)
|
||||
errutil.Printf(faint, " release: %s (%s)\n", releaseShort, latest)
|
||||
green.Printf(tui.SymbolSuccess+" update available: %d commit(s) behind %s\n", comparison.BehindBy, latest)
|
||||
faint.Printf(" your commit: %s\n", currentCommit)
|
||||
faint.Printf(" release: %s (%s)\n", releaseShort, latest)
|
||||
fmt.Println()
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" this is a nix installation")
|
||||
errutil.Println(faint, " nix store is immutable; use nix commands to upgrade")
|
||||
yellow.Println(tui.SymbolWarning + " this is a nix installation")
|
||||
faint.Println(" nix store is immutable; use nix commands to upgrade")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
}
|
||||
|
||||
green := color.New(color.FgGreen)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" you are running %s (commit %s)\n", latest, releaseShort)
|
||||
green.Printf(tui.SymbolSuccess+" you are running %s (commit %s)\n", latest, releaseShort)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -279,22 +278,22 @@ func handleNixSpecificVersion(current, target string) error {
|
||||
printVersionComparisonTarget(current, target)
|
||||
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" this is a nix installation")
|
||||
yellow.Println(tui.SymbolWarning + " this is a nix installation")
|
||||
faint := color.New(color.Faint)
|
||||
errutil.Println(faint, " nix store is immutable; in-place upgrades are not supported")
|
||||
faint.Println(" nix store is immutable; in-place upgrades are not supported")
|
||||
fmt.Println()
|
||||
|
||||
bold := color.New(color.Bold)
|
||||
cmd := color.New(color.FgCyan)
|
||||
|
||||
errutil.Println(bold, "to install a specific version with nix:")
|
||||
bold.Println("to install a specific version with nix:")
|
||||
fmt.Println()
|
||||
|
||||
errutil.Print(faint, " specific ref ")
|
||||
errutil.Printf(cmd, "nix profile install github:%s/%s/%s\n", repoOwner, repoName, target)
|
||||
faint.Print(" specific ref ")
|
||||
cmd.Printf("nix profile install github:%s/%s/%s\n", repoOwner, repoName, target)
|
||||
|
||||
errutil.Print(faint, " latest ")
|
||||
errutil.Printf(cmd, "nix profile install github:%s/%s\n", repoOwner, repoName)
|
||||
faint.Print(" latest ")
|
||||
cmd.Printf("nix profile install github:%s/%s\n", repoOwner, repoName)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -334,7 +333,7 @@ func fetchLatestVersion() (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer errutil.Close(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("github api returned status %d", resp.StatusCode)
|
||||
@@ -356,10 +355,10 @@ func printVersionComparison(current, latest string) {
|
||||
faint := color.New(color.Faint)
|
||||
version := color.New(color.FgCyan)
|
||||
|
||||
errutil.Print(faint, "current ")
|
||||
errutil.Println(version, current)
|
||||
errutil.Print(faint, "latest ")
|
||||
errutil.Println(version, latest)
|
||||
faint.Print("current ")
|
||||
version.Println(current)
|
||||
faint.Print("latest ")
|
||||
version.Println(latest)
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
@@ -367,10 +366,10 @@ func printVersionComparisonTarget(current, target string) {
|
||||
faint := color.New(color.Faint)
|
||||
version := color.New(color.FgCyan)
|
||||
|
||||
errutil.Print(faint, "current ")
|
||||
errutil.Println(version, current)
|
||||
errutil.Print(faint, "target ")
|
||||
errutil.Println(version, target)
|
||||
faint.Print("current ")
|
||||
version.Println(current)
|
||||
faint.Print("target ")
|
||||
version.Println(target)
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
@@ -379,20 +378,20 @@ func printUpgradeInstructions() {
|
||||
faint := color.New(color.Faint)
|
||||
cmd := color.New(color.FgCyan)
|
||||
|
||||
errutil.Println(bold, "upgrade options:")
|
||||
bold.Println("upgrade options:")
|
||||
fmt.Println()
|
||||
|
||||
errutil.Print(faint, " go install ")
|
||||
errutil.Printf(cmd, "go install github.com/%s/%s@latest\n", repoOwner, repoName)
|
||||
faint.Print(" go install ")
|
||||
cmd.Printf("go install github.com/%s/%s@latest\n", repoOwner, repoName)
|
||||
|
||||
errutil.Print(faint, " shell script ")
|
||||
errutil.Printf(cmd, "curl -sSL https://raw.githubusercontent.com/%s/%s/master/install.sh | sh\n", repoOwner, repoName)
|
||||
faint.Print(" shell script ")
|
||||
cmd.Printf("curl -sSL https://raw.githubusercontent.com/%s/%s/master/install.sh | sh\n", repoOwner, repoName)
|
||||
|
||||
errutil.Print(faint, " arch (aur) ")
|
||||
errutil.Println(cmd, "yay -S snitch-bin")
|
||||
faint.Print(" arch (aur) ")
|
||||
cmd.Println("yay -S snitch-bin")
|
||||
|
||||
errutil.Print(faint, " nix ")
|
||||
errutil.Printf(cmd, "nix profile upgrade --inputs-from github:%s/%s\n", repoOwner, repoName)
|
||||
faint.Print(" nix ")
|
||||
cmd.Printf("nix profile upgrade --inputs-from github:%s/%s\n", repoOwner, repoName)
|
||||
}
|
||||
|
||||
func performUpgrade(version string) error {
|
||||
@@ -408,7 +407,7 @@ func performUpgrade(version string) error {
|
||||
|
||||
if strings.HasPrefix(execPath, "/nix/store/") {
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Println(yellow, tui.SymbolWarning+" cannot perform in-place upgrade for nix installation")
|
||||
yellow.Println(tui.SymbolWarning + " cannot perform in-place upgrade for nix installation")
|
||||
fmt.Println()
|
||||
printNixUpgradeInstructions()
|
||||
return nil
|
||||
@@ -424,15 +423,15 @@ func performUpgrade(version string) error {
|
||||
|
||||
faint := color.New(color.Faint)
|
||||
cyan := color.New(color.FgCyan)
|
||||
errutil.Print(faint, tui.SymbolDownload+" downloading ")
|
||||
errutil.Printf(cyan, "%s", archiveName)
|
||||
errutil.Println(faint, "...")
|
||||
faint.Print(tui.SymbolDownload + " downloading ")
|
||||
cyan.Printf("%s", archiveName)
|
||||
faint.Println("...")
|
||||
|
||||
resp, err := http.Get(downloadURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download: %w", err)
|
||||
}
|
||||
defer errutil.Close(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download failed with status %d", resp.StatusCode)
|
||||
@@ -442,7 +441,7 @@ func performUpgrade(version string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp directory: %w", err)
|
||||
}
|
||||
defer errutil.RemoveAll(tmpDir)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
binaryPath, err := extractBinaryFromTarGz(resp.Body, tmpDir)
|
||||
if err != nil {
|
||||
@@ -459,14 +458,14 @@ func performUpgrade(version string) error {
|
||||
yellow := color.New(color.FgYellow)
|
||||
cmdStyle := color.New(color.FgCyan)
|
||||
|
||||
errutil.Printf(yellow, tui.SymbolWarning+" elevated permissions required to install to %s\n", targetDir)
|
||||
yellow.Printf(tui.SymbolWarning+" elevated permissions required to install to %s\n", targetDir)
|
||||
fmt.Println()
|
||||
errutil.Println(faint, "run with sudo or install to a user-writable location:")
|
||||
faint.Println("run with sudo or install to a user-writable location:")
|
||||
fmt.Println()
|
||||
errutil.Print(faint, " sudo ")
|
||||
errutil.Println(cmdStyle, "sudo snitch upgrade --yes")
|
||||
errutil.Print(faint, " custom dir ")
|
||||
errutil.Printf(cmdStyle, "curl -sSL https://raw.githubusercontent.com/%s/%s/master/install.sh | INSTALL_DIR=~/.local/bin sh\n",
|
||||
faint.Print(" sudo ")
|
||||
cmdStyle.Println("sudo snitch upgrade --yes")
|
||||
faint.Print(" custom dir ")
|
||||
cmdStyle.Printf("curl -sSL https://raw.githubusercontent.com/%s/%s/master/install.sh | INSTALL_DIR=~/.local/bin sh\n",
|
||||
repoOwner, repoName)
|
||||
return nil
|
||||
}
|
||||
@@ -492,11 +491,11 @@ func performUpgrade(version string) error {
|
||||
if err := os.Remove(backupPath); err != nil {
|
||||
// non-fatal, just warn
|
||||
yellow := color.New(color.FgYellow)
|
||||
errutil.Fprintf(yellow, os.Stderr, tui.SymbolWarning+" warning: failed to remove backup file %s: %v\n", backupPath, err)
|
||||
yellow.Fprintf(os.Stderr, tui.SymbolWarning + " warning: failed to remove backup file %s: %v\n", backupPath, err)
|
||||
}
|
||||
|
||||
green := color.New(color.FgGreen, color.Bold)
|
||||
errutil.Printf(green, tui.SymbolSuccess+" successfully upgraded to %s\n", version)
|
||||
green.Printf(tui.SymbolSuccess + " successfully upgraded to %s\n", version)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -505,7 +504,7 @@ func extractBinaryFromTarGz(r io.Reader, destDir string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer errutil.Close(gzr)
|
||||
defer gzr.Close()
|
||||
|
||||
tr := tar.NewReader(gzr)
|
||||
|
||||
@@ -535,10 +534,10 @@ func extractBinaryFromTarGz(r io.Reader, destDir string) (string, error) {
|
||||
}
|
||||
|
||||
if _, err := io.Copy(outFile, tr); err != nil {
|
||||
errutil.Close(outFile)
|
||||
outFile.Close()
|
||||
return "", err
|
||||
}
|
||||
errutil.Close(outFile)
|
||||
outFile.Close()
|
||||
|
||||
return destPath, nil
|
||||
}
|
||||
@@ -552,8 +551,8 @@ func isWritable(path string) bool {
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
errutil.Close(f)
|
||||
errutil.Remove(testFile)
|
||||
f.Close()
|
||||
os.Remove(testFile)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -562,13 +561,13 @@ func copyFile(src, dst string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer errutil.Close(srcFile)
|
||||
defer srcFile.Close()
|
||||
|
||||
dstFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer errutil.Close(dstFile)
|
||||
defer dstFile.Close()
|
||||
|
||||
if _, err := io.Copy(dstFile, srcFile); err != nil {
|
||||
return err
|
||||
@@ -581,7 +580,7 @@ func removeQuarantine(path string) {
|
||||
cmd := exec.Command("xattr", "-d", "com.apple.quarantine", path)
|
||||
if err := cmd.Run(); err == nil {
|
||||
faint := color.New(color.Faint)
|
||||
errutil.Println(faint, " removed macOS quarantine attribute")
|
||||
faint.Println(" removed macOS quarantine attribute")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -634,7 +633,7 @@ func fetchCommitForTag(tag string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer errutil.Close(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("github api returned status %d", resp.StatusCode)
|
||||
@@ -655,7 +654,7 @@ func compareCommits(base, head string) (*githubCompare, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer errutil.Close(resp.Body)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("github api returned status %d", resp.StatusCode)
|
||||
@@ -674,16 +673,16 @@ func printNixUpgradeInstructions() {
|
||||
faint := color.New(color.Faint)
|
||||
cmd := color.New(color.FgCyan)
|
||||
|
||||
errutil.Println(bold, "nix upgrade options:")
|
||||
bold.Println("nix upgrade options:")
|
||||
fmt.Println()
|
||||
|
||||
errutil.Print(faint, " flake profile ")
|
||||
errutil.Printf(cmd, "nix profile install github:%s/%s\n", repoOwner, repoName)
|
||||
faint.Print(" flake profile ")
|
||||
cmd.Printf("nix profile install github:%s/%s\n", repoOwner, repoName)
|
||||
|
||||
errutil.Print(faint, " flake update ")
|
||||
errutil.Println(cmd, "nix flake update snitch (in your system/home-manager config)")
|
||||
faint.Print(" flake update ")
|
||||
cmd.Println("nix flake update snitch (in your system/home-manager config)")
|
||||
|
||||
errutil.Print(faint, " rebuild ")
|
||||
errutil.Println(cmd, "nixos-rebuild switch or home-manager switch")
|
||||
faint.Print(" rebuild ")
|
||||
cmd.Println("nixos-rebuild switch or home-manager switch")
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -24,20 +22,20 @@ var versionCmd = &cobra.Command{
|
||||
cyan := color.New(color.FgCyan)
|
||||
faint := color.New(color.Faint)
|
||||
|
||||
errutil.Print(bold, "snitch ")
|
||||
errutil.Println(cyan, Version)
|
||||
bold.Print("snitch ")
|
||||
cyan.Println(Version)
|
||||
fmt.Println()
|
||||
|
||||
errutil.Print(faint, " commit ")
|
||||
faint.Print(" commit ")
|
||||
fmt.Println(Commit)
|
||||
|
||||
errutil.Print(faint, " built ")
|
||||
faint.Print(" built ")
|
||||
fmt.Println(Date)
|
||||
|
||||
errutil.Print(faint, " go ")
|
||||
faint.Print(" go ")
|
||||
fmt.Println(runtime.Version())
|
||||
|
||||
errutil.Print(faint, " os ")
|
||||
faint.Print(" os ")
|
||||
fmt.Printf("%s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||
},
|
||||
}
|
||||
|
||||
27
flake.nix
27
flake.nix
@@ -106,32 +106,5 @@
|
||||
overlays.default = final: _prev: {
|
||||
snitch = mkSnitch final;
|
||||
};
|
||||
|
||||
homeManagerModules.default = import ./nix/hm-module.nix;
|
||||
homeManagerModules.snitch = self.homeManagerModules.default;
|
||||
|
||||
# alias for flake-parts compatibility
|
||||
homeModules.default = self.homeManagerModules.default;
|
||||
homeModules.snitch = self.homeManagerModules.default;
|
||||
|
||||
checks = eachSystem (system:
|
||||
let
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
overlays = [ self.overlays.default ];
|
||||
};
|
||||
in
|
||||
{
|
||||
# home manager module tests
|
||||
hm-module = import ./nix/tests/hm-module-test.nix {
|
||||
inherit pkgs;
|
||||
lib = pkgs.lib;
|
||||
hmModule = self.homeManagerModules.default;
|
||||
};
|
||||
|
||||
# package builds correctly
|
||||
package = self.packages.${system}.default;
|
||||
}
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,8 +14,6 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
)
|
||||
|
||||
// set SNITCH_DEBUG_TIMING=1 to enable timing diagnostics
|
||||
@@ -140,7 +138,7 @@ func buildInodeToProcessMap() (map[int64]*processInfo, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer errutil.Close(procDir)
|
||||
defer procDir.Close()
|
||||
|
||||
entries, err := procDir.Readdir(-1)
|
||||
if err != nil {
|
||||
@@ -280,7 +278,7 @@ func getProcessInfo(pid int) (*processInfo, error) {
|
||||
if err != nil {
|
||||
return info, nil
|
||||
}
|
||||
defer errutil.Close(statusFile)
|
||||
defer statusFile.Close()
|
||||
|
||||
scanner := bufio.NewScanner(statusFile)
|
||||
for scanner.Scan() {
|
||||
@@ -306,7 +304,7 @@ func parseProcNet(path, proto string, ipVersion int, inodeMap map[int64]*process
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer errutil.Close(file)
|
||||
defer file.Close()
|
||||
|
||||
var connections []Connection
|
||||
scanner := bufio.NewScanner(file)
|
||||
@@ -475,7 +473,7 @@ func GetUnixSockets() ([]Connection, error) {
|
||||
if err != nil {
|
||||
return connections, nil
|
||||
}
|
||||
defer errutil.Close(file)
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Scan()
|
||||
|
||||
@@ -5,8 +5,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/fatih/color"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
)
|
||||
|
||||
func TestInit(t *testing.T) {
|
||||
@@ -31,8 +29,8 @@ func TestInit(t *testing.T) {
|
||||
origTerm := os.Getenv("TERM")
|
||||
|
||||
// Set test env vars
|
||||
errutil.Setenv("NO_COLOR", tc.noColor)
|
||||
errutil.Setenv("TERM", tc.term)
|
||||
os.Setenv("NO_COLOR", tc.noColor)
|
||||
os.Setenv("TERM", tc.term)
|
||||
|
||||
Init(tc.mode)
|
||||
|
||||
@@ -41,8 +39,8 @@ func TestInit(t *testing.T) {
|
||||
}
|
||||
|
||||
// Restore original env vars
|
||||
errutil.Setenv("NO_COLOR", origNoColor)
|
||||
errutil.Setenv("TERM", origTerm)
|
||||
os.Setenv("NO_COLOR", origNoColor)
|
||||
os.Setenv("TERM", origTerm)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,12 +14,6 @@ import (
|
||||
// Config represents the application configuration
|
||||
type Config struct {
|
||||
Defaults DefaultConfig `mapstructure:"defaults"`
|
||||
TUI TUIConfig `mapstructure:"tui"`
|
||||
}
|
||||
|
||||
// TUIConfig contains TUI-specific configuration
|
||||
type TUIConfig struct {
|
||||
RememberState bool `mapstructure:"remember_state"`
|
||||
}
|
||||
|
||||
// DefaultConfig contains default values for CLI options
|
||||
@@ -111,9 +105,6 @@ func setDefaults(v *viper.Viper) {
|
||||
v.SetDefault("defaults.no_headers", false)
|
||||
v.SetDefault("defaults.output_format", "table")
|
||||
v.SetDefault("defaults.sort_by", "")
|
||||
|
||||
// tui settings
|
||||
v.SetDefault("tui.remember_state", false)
|
||||
}
|
||||
|
||||
func handleSpecialEnvVars(v *viper.Viper) {
|
||||
@@ -155,9 +146,6 @@ func Get() *Config {
|
||||
OutputFormat: "table",
|
||||
SortBy: "",
|
||||
},
|
||||
TUI: TUIConfig{
|
||||
RememberState: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
return config
|
||||
@@ -211,11 +199,6 @@ ipv6 = false
|
||||
no_headers = false
|
||||
output_format = "table"
|
||||
sort_by = ""
|
||||
|
||||
[tui]
|
||||
# remember view options (filters, sort, resolution) between sessions
|
||||
# state is saved to $XDG_STATE_HOME/snitch/tui.json
|
||||
remember_state = false
|
||||
`, themeList, theme.DefaultTheme)
|
||||
|
||||
// Ensure directory exists
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package errutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
func Ignore[T any](val T, _ error) T {
|
||||
return val
|
||||
}
|
||||
|
||||
func IgnoreErr(_ error) {}
|
||||
|
||||
func Close(c io.Closer) {
|
||||
if c != nil {
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// color.Color wrappers - these discard the (int, error) return values
|
||||
|
||||
func Print(c *color.Color, a ...any) {
|
||||
_, _ = c.Print(a...)
|
||||
}
|
||||
|
||||
func Println(c *color.Color, a ...any) {
|
||||
_, _ = c.Println(a...)
|
||||
}
|
||||
|
||||
func Printf(c *color.Color, format string, a ...any) {
|
||||
_, _ = c.Printf(format, a...)
|
||||
}
|
||||
|
||||
func Fprintf(c *color.Color, w io.Writer, format string, a ...any) {
|
||||
_, _ = c.Fprintf(w, format, a...)
|
||||
}
|
||||
|
||||
// os function wrappers for test cleanup where errors are non-critical
|
||||
|
||||
func Setenv(key, value string) {
|
||||
_ = os.Setenv(key, value)
|
||||
}
|
||||
|
||||
func Unsetenv(key string) {
|
||||
_ = os.Unsetenv(key)
|
||||
}
|
||||
|
||||
func Remove(name string) {
|
||||
_ = os.Remove(name)
|
||||
}
|
||||
|
||||
func RemoveAll(path string) {
|
||||
_ = os.RemoveAll(path)
|
||||
}
|
||||
|
||||
// Flush calls Flush on a tabwriter and discards the error
|
||||
type Flusher interface {
|
||||
Flush() error
|
||||
}
|
||||
|
||||
func Flush(f Flusher) {
|
||||
_ = f.Flush()
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
)
|
||||
|
||||
// TUIState holds view options that can be persisted between sessions
|
||||
type TUIState struct {
|
||||
ShowTCP bool `json:"show_tcp"`
|
||||
ShowUDP bool `json:"show_udp"`
|
||||
ShowListening bool `json:"show_listening"`
|
||||
ShowEstablished bool `json:"show_established"`
|
||||
ShowOther bool `json:"show_other"`
|
||||
SortField collector.SortField `json:"sort_field"`
|
||||
SortReverse bool `json:"sort_reverse"`
|
||||
ResolveAddrs bool `json:"resolve_addrs"`
|
||||
ResolvePorts bool `json:"resolve_ports"`
|
||||
}
|
||||
|
||||
var (
|
||||
saveMu sync.Mutex
|
||||
saveChan chan TUIState
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// Path returns the XDG-compliant state file path
|
||||
func Path() string {
|
||||
stateDir := os.Getenv("XDG_STATE_HOME")
|
||||
if stateDir == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
stateDir = filepath.Join(home, ".local", "state")
|
||||
}
|
||||
return filepath.Join(stateDir, "snitch", "tui.json")
|
||||
}
|
||||
|
||||
// Load reads the TUI state from disk.
|
||||
// returns nil if state file doesn't exist or can't be read.
|
||||
func Load() *TUIState {
|
||||
path := Path()
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var state TUIState
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &state
|
||||
}
|
||||
|
||||
// Save writes the TUI state to disk synchronously.
|
||||
// creates parent directories if needed.
|
||||
func Save(state TUIState) error {
|
||||
path := Path()
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
saveMu.Lock()
|
||||
defer saveMu.Unlock()
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(state, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, data, 0644)
|
||||
}
|
||||
|
||||
// SaveAsync queues a state save to happen in the background.
|
||||
// only the most recent state is saved if multiple saves are queued.
|
||||
func SaveAsync(state TUIState) {
|
||||
once.Do(func() {
|
||||
saveChan = make(chan TUIState, 1)
|
||||
go saveWorker()
|
||||
})
|
||||
|
||||
// non-blocking send, replace pending save with newer state
|
||||
select {
|
||||
case saveChan <- state:
|
||||
default:
|
||||
// channel full, drain and replace
|
||||
select {
|
||||
case <-saveChan:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case saveChan <- state:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func saveWorker() {
|
||||
for state := range saveChan {
|
||||
_ = Save(state)
|
||||
}
|
||||
}
|
||||
|
||||
// Default returns a TUIState with default values
|
||||
func Default() TUIState {
|
||||
return TUIState{
|
||||
ShowTCP: true,
|
||||
ShowUDP: true,
|
||||
ShowListening: true,
|
||||
ShowEstablished: true,
|
||||
ShowOther: true,
|
||||
SortField: collector.SortByLport,
|
||||
SortReverse: false,
|
||||
ResolveAddrs: false,
|
||||
ResolvePorts: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
)
|
||||
|
||||
func TestPath_XDGStateHome(t *testing.T) {
|
||||
t.Setenv("XDG_STATE_HOME", "/custom/state")
|
||||
path := Path()
|
||||
|
||||
expected := "/custom/state/snitch/tui.json"
|
||||
if path != expected {
|
||||
t.Errorf("Path() = %q, want %q", path, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPath_DefaultFallback(t *testing.T) {
|
||||
t.Setenv("XDG_STATE_HOME", "")
|
||||
path := Path()
|
||||
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
t.Skip("cannot determine home directory")
|
||||
}
|
||||
|
||||
expected := filepath.Join(home, ".local", "state", "snitch", "tui.json")
|
||||
if path != expected {
|
||||
t.Errorf("Path() = %q, want %q", path, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefault(t *testing.T) {
|
||||
d := Default()
|
||||
|
||||
if d.ShowTCP != true {
|
||||
t.Error("expected ShowTCP to be true")
|
||||
}
|
||||
if d.ShowUDP != true {
|
||||
t.Error("expected ShowUDP to be true")
|
||||
}
|
||||
if d.ShowListening != true {
|
||||
t.Error("expected ShowListening to be true")
|
||||
}
|
||||
if d.ShowEstablished != true {
|
||||
t.Error("expected ShowEstablished to be true")
|
||||
}
|
||||
if d.ShowOther != true {
|
||||
t.Error("expected ShowOther to be true")
|
||||
}
|
||||
if d.SortField != collector.SortByLport {
|
||||
t.Errorf("expected SortField to be %q, got %q", collector.SortByLport, d.SortField)
|
||||
}
|
||||
if d.SortReverse != false {
|
||||
t.Error("expected SortReverse to be false")
|
||||
}
|
||||
if d.ResolveAddrs != false {
|
||||
t.Error("expected ResolveAddrs to be false")
|
||||
}
|
||||
if d.ResolvePorts != false {
|
||||
t.Error("expected ResolvePorts to be false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAndLoad(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
state := TUIState{
|
||||
ShowTCP: false,
|
||||
ShowUDP: true,
|
||||
ShowListening: true,
|
||||
ShowEstablished: false,
|
||||
ShowOther: true,
|
||||
SortField: collector.SortByProcess,
|
||||
SortReverse: true,
|
||||
ResolveAddrs: true,
|
||||
ResolvePorts: false,
|
||||
}
|
||||
|
||||
err := Save(state)
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
|
||||
// verify file was created
|
||||
path := Path()
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
t.Fatal("expected state file to exist after Save()")
|
||||
}
|
||||
|
||||
loaded := Load()
|
||||
if loaded == nil {
|
||||
t.Fatal("Load() returned nil")
|
||||
}
|
||||
|
||||
if loaded.ShowTCP != state.ShowTCP {
|
||||
t.Errorf("ShowTCP = %v, want %v", loaded.ShowTCP, state.ShowTCP)
|
||||
}
|
||||
if loaded.ShowUDP != state.ShowUDP {
|
||||
t.Errorf("ShowUDP = %v, want %v", loaded.ShowUDP, state.ShowUDP)
|
||||
}
|
||||
if loaded.ShowListening != state.ShowListening {
|
||||
t.Errorf("ShowListening = %v, want %v", loaded.ShowListening, state.ShowListening)
|
||||
}
|
||||
if loaded.ShowEstablished != state.ShowEstablished {
|
||||
t.Errorf("ShowEstablished = %v, want %v", loaded.ShowEstablished, state.ShowEstablished)
|
||||
}
|
||||
if loaded.ShowOther != state.ShowOther {
|
||||
t.Errorf("ShowOther = %v, want %v", loaded.ShowOther, state.ShowOther)
|
||||
}
|
||||
if loaded.SortField != state.SortField {
|
||||
t.Errorf("SortField = %v, want %v", loaded.SortField, state.SortField)
|
||||
}
|
||||
if loaded.SortReverse != state.SortReverse {
|
||||
t.Errorf("SortReverse = %v, want %v", loaded.SortReverse, state.SortReverse)
|
||||
}
|
||||
if loaded.ResolveAddrs != state.ResolveAddrs {
|
||||
t.Errorf("ResolveAddrs = %v, want %v", loaded.ResolveAddrs, state.ResolveAddrs)
|
||||
}
|
||||
if loaded.ResolvePorts != state.ResolvePorts {
|
||||
t.Errorf("ResolvePorts = %v, want %v", loaded.ResolvePorts, state.ResolvePorts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_NonExistent(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
loaded := Load()
|
||||
if loaded != nil {
|
||||
t.Error("expected Load() to return nil for non-existent file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_InvalidJSON(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
// create directory and invalid json file
|
||||
stateDir := filepath.Join(tmpDir, "snitch")
|
||||
if err := os.MkdirAll(stateDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stateFile := filepath.Join(stateDir, "tui.json")
|
||||
if err := os.WriteFile(stateFile, []byte("not valid json"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
loaded := Load()
|
||||
if loaded != nil {
|
||||
t.Error("expected Load() to return nil for invalid JSON")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSave_CreatesDirectories(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
// snitch directory should not exist yet
|
||||
snitchDir := filepath.Join(tmpDir, "snitch")
|
||||
if _, err := os.Stat(snitchDir); err == nil {
|
||||
t.Fatal("expected snitch directory to not exist initially")
|
||||
}
|
||||
|
||||
err := Save(Default())
|
||||
if err != nil {
|
||||
t.Fatalf("Save() error = %v", err)
|
||||
}
|
||||
|
||||
// directory should now exist
|
||||
if _, err := os.Stat(snitchDir); os.IsNotExist(err) {
|
||||
t.Error("expected Save() to create parent directories")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAsync(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
state := TUIState{
|
||||
ShowTCP: false,
|
||||
SortField: collector.SortByPID,
|
||||
}
|
||||
|
||||
SaveAsync(state)
|
||||
|
||||
// wait for background save with timeout
|
||||
deadline := time.Now().Add(100 * time.Millisecond)
|
||||
for time.Now().Before(deadline) {
|
||||
if loaded := Load(); loaded != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
t.Log("SaveAsync may not have completed in time (non-fatal in CI)")
|
||||
}
|
||||
|
||||
func TestTUIState_JSONRoundtrip(t *testing.T) {
|
||||
// verify all sort fields serialize correctly
|
||||
sortFields := []collector.SortField{
|
||||
collector.SortByLport,
|
||||
collector.SortByProcess,
|
||||
collector.SortByPID,
|
||||
collector.SortByState,
|
||||
collector.SortByProto,
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
t.Setenv("XDG_STATE_HOME", tmpDir)
|
||||
|
||||
for _, sf := range sortFields {
|
||||
state := TUIState{
|
||||
ShowTCP: true,
|
||||
SortField: sf,
|
||||
}
|
||||
|
||||
if err := Save(state); err != nil {
|
||||
t.Fatalf("Save() error for %q: %v", sf, err)
|
||||
}
|
||||
|
||||
loaded := Load()
|
||||
if loaded == nil {
|
||||
t.Fatalf("Load() returned nil for %q", sf)
|
||||
}
|
||||
|
||||
if loaded.SortField != sf {
|
||||
t.Errorf("SortField roundtrip failed: got %q, want %q", loaded.SortField, sf)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/errutil"
|
||||
)
|
||||
|
||||
// TestCollector wraps MockCollector for use in tests
|
||||
@@ -48,13 +47,13 @@ func SetupTestEnvironment(t *testing.T) (string, func()) {
|
||||
oldConfig := os.Getenv("SNITCH_CONFIG")
|
||||
oldNoColor := os.Getenv("SNITCH_NO_COLOR")
|
||||
|
||||
errutil.Setenv("SNITCH_NO_COLOR", "1")
|
||||
os.Setenv("SNITCH_NO_COLOR", "1") // Disable colors in tests
|
||||
|
||||
// Cleanup function
|
||||
cleanup := func() {
|
||||
errutil.RemoveAll(tempDir)
|
||||
errutil.Setenv("SNITCH_CONFIG", oldConfig)
|
||||
errutil.Setenv("SNITCH_NO_COLOR", oldNoColor)
|
||||
os.RemoveAll(tempDir)
|
||||
os.Setenv("SNITCH_CONFIG", oldConfig)
|
||||
os.Setenv("SNITCH_NO_COLOR", oldNoColor)
|
||||
}
|
||||
|
||||
return tempDir, cleanup
|
||||
@@ -193,8 +192,8 @@ func (oc *OutputCapture) Stop() (string, string, error) {
|
||||
os.Stderr = oc.oldStderr
|
||||
|
||||
// Close files
|
||||
errutil.Close(oc.stdout)
|
||||
errutil.Close(oc.stderr)
|
||||
oc.stdout.Close()
|
||||
oc.stderr.Close()
|
||||
|
||||
// Read captured content
|
||||
stdoutContent, err := os.ReadFile(oc.stdoutFile)
|
||||
@@ -208,9 +207,9 @@ func (oc *OutputCapture) Stop() (string, string, error) {
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
errutil.Remove(oc.stdoutFile)
|
||||
errutil.Remove(oc.stderrFile)
|
||||
errutil.Remove(filepath.Dir(oc.stdoutFile))
|
||||
os.Remove(oc.stdoutFile)
|
||||
os.Remove(oc.stderrFile)
|
||||
os.Remove(filepath.Dir(oc.stdoutFile))
|
||||
|
||||
return string(stdoutContent), string(stderrContent), nil
|
||||
}
|
||||
@@ -118,39 +118,31 @@ func (m model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
case "t":
|
||||
m.showTCP = !m.showTCP
|
||||
m.clampCursor()
|
||||
m.saveState()
|
||||
case "u":
|
||||
m.showUDP = !m.showUDP
|
||||
m.clampCursor()
|
||||
m.saveState()
|
||||
case "l":
|
||||
m.showListening = !m.showListening
|
||||
m.clampCursor()
|
||||
m.saveState()
|
||||
case "e":
|
||||
m.showEstablished = !m.showEstablished
|
||||
m.clampCursor()
|
||||
m.saveState()
|
||||
case "o":
|
||||
m.showOther = !m.showOther
|
||||
m.clampCursor()
|
||||
m.saveState()
|
||||
case "a":
|
||||
m.showTCP = true
|
||||
m.showUDP = true
|
||||
m.showListening = true
|
||||
m.showEstablished = true
|
||||
m.showOther = true
|
||||
m.saveState()
|
||||
|
||||
// sorting
|
||||
case "s":
|
||||
m.cycleSort()
|
||||
m.saveState()
|
||||
case "S":
|
||||
m.sortReverse = !m.sortReverse
|
||||
m.applySorting()
|
||||
m.saveState()
|
||||
|
||||
// search
|
||||
case "/":
|
||||
@@ -228,7 +220,6 @@ func (m model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
m.statusMessage = "address resolution: off"
|
||||
}
|
||||
m.statusExpiry = time.Now().Add(2 * time.Second)
|
||||
m.saveState()
|
||||
return m, clearStatusAfter(2 * time.Second)
|
||||
|
||||
// toggle port resolution
|
||||
@@ -240,7 +231,6 @@ func (m model) handleNormalKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
m.statusMessage = "port resolution: off"
|
||||
}
|
||||
m.statusExpiry = time.Now().Add(2 * time.Second)
|
||||
m.saveState()
|
||||
return m, clearStatusAfter(2 * time.Second)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,13 +2,11 @@ package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/theme"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"github.com/karol-broda/snitch/internal/collector"
|
||||
"github.com/karol-broda/snitch/internal/state"
|
||||
"github.com/karol-broda/snitch/internal/theme"
|
||||
)
|
||||
|
||||
type model struct {
|
||||
@@ -53,24 +51,20 @@ type model struct {
|
||||
// status message (temporary feedback)
|
||||
statusMessage string
|
||||
statusExpiry time.Time
|
||||
|
||||
// state persistence
|
||||
rememberState bool
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Theme string
|
||||
Interval time.Duration
|
||||
TCP bool
|
||||
UDP bool
|
||||
Listening bool
|
||||
Established bool
|
||||
Other bool
|
||||
FilterSet bool // true if user specified any filter flags
|
||||
ResolveAddrs bool // when true, resolve IP addresses to hostnames
|
||||
ResolvePorts bool // when true, resolve port numbers to service names
|
||||
NoCache bool // when true, disable DNS caching
|
||||
RememberState bool // when true, persist view options between sessions
|
||||
Theme string
|
||||
Interval time.Duration
|
||||
TCP bool
|
||||
UDP bool
|
||||
Listening bool
|
||||
Established bool
|
||||
Other bool
|
||||
FilterSet bool // true if user specified any filter flags
|
||||
ResolveAddrs bool // when true, resolve IP addresses to hostnames
|
||||
ResolvePorts bool // when true, resolve port numbers to service names
|
||||
NoCache bool // when true, disable DNS caching
|
||||
}
|
||||
|
||||
func New(opts Options) model {
|
||||
@@ -85,27 +79,8 @@ func New(opts Options) model {
|
||||
showListening := true
|
||||
showEstablished := true
|
||||
showOther := true
|
||||
sortField := collector.SortByLport
|
||||
sortReverse := false
|
||||
resolveAddrs := opts.ResolveAddrs
|
||||
resolvePorts := opts.ResolvePorts
|
||||
|
||||
// load saved state if enabled and no CLI filter flags were specified
|
||||
if opts.RememberState && !opts.FilterSet {
|
||||
if saved := state.Load(); saved != nil {
|
||||
showTCP = saved.ShowTCP
|
||||
showUDP = saved.ShowUDP
|
||||
showListening = saved.ShowListening
|
||||
showEstablished = saved.ShowEstablished
|
||||
showOther = saved.ShowOther
|
||||
sortField = saved.SortField
|
||||
sortReverse = saved.SortReverse
|
||||
resolveAddrs = saved.ResolveAddrs
|
||||
resolvePorts = saved.ResolvePorts
|
||||
}
|
||||
}
|
||||
|
||||
// if user specified filters, use those instead (CLI flags take precedence)
|
||||
// if user specified filters, use those instead
|
||||
if opts.FilterSet {
|
||||
showTCP = opts.TCP
|
||||
showUDP = opts.UDP
|
||||
@@ -133,15 +108,13 @@ func New(opts Options) model {
|
||||
showListening: showListening,
|
||||
showEstablished: showEstablished,
|
||||
showOther: showOther,
|
||||
sortField: sortField,
|
||||
sortReverse: sortReverse,
|
||||
resolveAddrs: resolveAddrs,
|
||||
resolvePorts: resolvePorts,
|
||||
sortField: collector.SortByLport,
|
||||
resolveAddrs: opts.ResolveAddrs,
|
||||
resolvePorts: opts.ResolvePorts,
|
||||
theme: theme.GetTheme(opts.Theme),
|
||||
interval: interval,
|
||||
lastRefresh: time.Now(),
|
||||
watchedPIDs: make(map[int]bool),
|
||||
rememberState: opts.RememberState,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,25 +291,3 @@ func (m *model) toggleWatch(pid int) {
|
||||
func (m model) watchedCount() int {
|
||||
return len(m.watchedPIDs)
|
||||
}
|
||||
|
||||
// currentState returns the current view options as a TUIState for persistence
|
||||
func (m model) currentState() state.TUIState {
|
||||
return state.TUIState{
|
||||
ShowTCP: m.showTCP,
|
||||
ShowUDP: m.showUDP,
|
||||
ShowListening: m.showListening,
|
||||
ShowEstablished: m.showEstablished,
|
||||
ShowOther: m.showOther,
|
||||
SortField: m.sortField,
|
||||
SortReverse: m.sortReverse,
|
||||
ResolveAddrs: m.resolveAddrs,
|
||||
ResolvePorts: m.resolvePorts,
|
||||
}
|
||||
}
|
||||
|
||||
// saveState persists current view options in the background
|
||||
func (m model) saveState() {
|
||||
if m.rememberState {
|
||||
state.SaveAsync(m.currentState())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.programs.snitch;
|
||||
|
||||
themes = [
|
||||
"ansi"
|
||||
"catppuccin-mocha"
|
||||
"catppuccin-macchiato"
|
||||
"catppuccin-frappe"
|
||||
"catppuccin-latte"
|
||||
"gruvbox-dark"
|
||||
"gruvbox-light"
|
||||
"dracula"
|
||||
"nord"
|
||||
"tokyo-night"
|
||||
"tokyo-night-storm"
|
||||
"tokyo-night-light"
|
||||
"solarized-dark"
|
||||
"solarized-light"
|
||||
"one-dark"
|
||||
"mono"
|
||||
"auto"
|
||||
];
|
||||
|
||||
defaultFields = [
|
||||
"pid"
|
||||
"process"
|
||||
"user"
|
||||
"proto"
|
||||
"state"
|
||||
"laddr"
|
||||
"lport"
|
||||
"raddr"
|
||||
"rport"
|
||||
];
|
||||
|
||||
tomlFormat = pkgs.formats.toml { };
|
||||
|
||||
settingsType = lib.types.submodule {
|
||||
freeformType = tomlFormat.type;
|
||||
|
||||
options = {
|
||||
defaults = lib.mkOption {
|
||||
type = lib.types.submodule {
|
||||
freeformType = tomlFormat.type;
|
||||
|
||||
options = {
|
||||
interval = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "1s";
|
||||
example = "2s";
|
||||
description = "Default refresh interval for watch/stats/trace commands.";
|
||||
};
|
||||
|
||||
numeric = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = "Disable name/service resolution by default.";
|
||||
};
|
||||
|
||||
fields = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = defaultFields;
|
||||
example = [ "pid" "process" "proto" "state" "laddr" "lport" ];
|
||||
description = "Default fields to display.";
|
||||
};
|
||||
|
||||
theme = lib.mkOption {
|
||||
type = lib.types.enum themes;
|
||||
default = "ansi";
|
||||
description = ''
|
||||
Color theme for the TUI. "ansi" inherits terminal colors.
|
||||
'';
|
||||
};
|
||||
|
||||
units = lib.mkOption {
|
||||
type = lib.types.enum [ "auto" "si" "iec" ];
|
||||
default = "auto";
|
||||
description = "Default units for byte display.";
|
||||
};
|
||||
|
||||
color = lib.mkOption {
|
||||
type = lib.types.enum [ "auto" "always" "never" ];
|
||||
default = "auto";
|
||||
description = "Default color mode.";
|
||||
};
|
||||
|
||||
resolve = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = "Enable name resolution by default.";
|
||||
};
|
||||
|
||||
dns_cache = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = "Enable DNS caching.";
|
||||
};
|
||||
|
||||
ipv4 = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = "Filter to IPv4 only by default.";
|
||||
};
|
||||
|
||||
ipv6 = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = "Filter to IPv6 only by default.";
|
||||
};
|
||||
|
||||
no_headers = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = "Omit headers in output by default.";
|
||||
};
|
||||
|
||||
output_format = lib.mkOption {
|
||||
type = lib.types.enum [ "table" "json" "csv" ];
|
||||
default = "table";
|
||||
description = "Default output format.";
|
||||
};
|
||||
|
||||
sort_by = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "";
|
||||
example = "pid";
|
||||
description = "Default sort field.";
|
||||
};
|
||||
};
|
||||
};
|
||||
default = { };
|
||||
description = "Default settings for snitch commands.";
|
||||
};
|
||||
};
|
||||
};
|
||||
in
|
||||
{
|
||||
options.programs.snitch = {
|
||||
enable = lib.mkEnableOption "snitch, a friendlier ss/netstat for humans";
|
||||
|
||||
package = lib.mkPackageOption pkgs "snitch" { };
|
||||
|
||||
settings = lib.mkOption {
|
||||
type = settingsType;
|
||||
default = { };
|
||||
example = lib.literalExpression ''
|
||||
{
|
||||
defaults = {
|
||||
theme = "catppuccin-mocha";
|
||||
interval = "2s";
|
||||
resolve = true;
|
||||
};
|
||||
}
|
||||
'';
|
||||
description = ''
|
||||
Configuration written to {file}`$XDG_CONFIG_HOME/snitch/snitch.toml`.
|
||||
|
||||
See <https://github.com/karol-broda/snitch> for available options.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
home.packages = [ cfg.package ];
|
||||
|
||||
xdg.configFile."snitch/snitch.toml" = lib.mkIf (cfg.settings != { }) {
|
||||
source = tomlFormat.generate "snitch.toml" cfg.settings;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,429 +0,0 @@
|
||||
# home manager module tests
|
||||
#
|
||||
# run with: nix build .#checks.x86_64-linux.hm-module
|
||||
#
|
||||
# tests cover:
|
||||
# - module evaluation with various configurations
|
||||
# - type validation for all options
|
||||
# - generated TOML content verification
|
||||
# - edge cases (disabled, empty settings, full settings)
|
||||
{ pkgs, lib, hmModule }:
|
||||
|
||||
let
|
||||
# minimal home-manager stub for standalone module testing
|
||||
hmLib = {
|
||||
hm.types.dagOf = lib.types.attrsOf;
|
||||
dag.entryAnywhere = x: x;
|
||||
};
|
||||
|
||||
# evaluate the hm module with a given config
|
||||
evalModule = testConfig:
|
||||
lib.evalModules {
|
||||
modules = [
|
||||
hmModule
|
||||
# stub home-manager's expected structure
|
||||
{
|
||||
options = {
|
||||
home.packages = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.package;
|
||||
default = [ ];
|
||||
};
|
||||
xdg.configFile = lib.mkOption {
|
||||
type = lib.types.attrsOf (lib.types.submodule {
|
||||
options = {
|
||||
source = lib.mkOption { type = lib.types.path; };
|
||||
text = lib.mkOption { type = lib.types.str; default = ""; };
|
||||
};
|
||||
});
|
||||
default = { };
|
||||
};
|
||||
};
|
||||
}
|
||||
testConfig
|
||||
];
|
||||
specialArgs = { inherit pkgs lib; };
|
||||
};
|
||||
|
||||
# read generated TOML file content
|
||||
readGeneratedToml = evalResult:
|
||||
let
|
||||
configFile = evalResult.config.xdg.configFile."snitch/snitch.toml" or null;
|
||||
in
|
||||
if configFile != null && configFile ? source
|
||||
then builtins.readFile configFile.source
|
||||
else null;
|
||||
|
||||
# test cases
|
||||
tests = {
|
||||
# test 1: module evaluates when disabled
|
||||
moduleDisabled = {
|
||||
name = "module-disabled";
|
||||
config = {
|
||||
programs.snitch.enable = false;
|
||||
};
|
||||
assertions = evalResult: [
|
||||
{
|
||||
assertion = evalResult.config.home.packages == [ ];
|
||||
message = "packages should be empty when disabled";
|
||||
}
|
||||
{
|
||||
assertion = !(evalResult.config.xdg.configFile ? "snitch/snitch.toml");
|
||||
message = "config file should not exist when disabled";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 2: module evaluates with enable only (defaults)
|
||||
moduleEnabledDefaults = {
|
||||
name = "module-enabled-defaults";
|
||||
config = {
|
||||
programs.snitch.enable = true;
|
||||
};
|
||||
assertions = evalResult: [
|
||||
{
|
||||
assertion = builtins.length evalResult.config.home.packages == 1;
|
||||
message = "package should be installed when enabled";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 3: all theme values are valid
|
||||
themeValidation = {
|
||||
name = "theme-validation";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.theme = "catppuccin-mocha";
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = toml != null;
|
||||
message = "TOML config should be generated";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "catppuccin-mocha" toml;
|
||||
message = "theme should be set in TOML";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 4: full configuration with all options
|
||||
fullConfiguration = {
|
||||
name = "full-configuration";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults = {
|
||||
interval = "2s";
|
||||
numeric = true;
|
||||
fields = [ "pid" "process" "proto" ];
|
||||
theme = "nord";
|
||||
units = "si";
|
||||
color = "always";
|
||||
resolve = false;
|
||||
dns_cache = false;
|
||||
ipv4 = true;
|
||||
ipv6 = false;
|
||||
no_headers = true;
|
||||
output_format = "json";
|
||||
sort_by = "pid";
|
||||
};
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = toml != null;
|
||||
message = "TOML config should be generated";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "interval = \"2s\"" toml;
|
||||
message = "interval should be 2s";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "numeric = true" toml;
|
||||
message = "numeric should be true";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "theme = \"nord\"" toml;
|
||||
message = "theme should be nord";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "units = \"si\"" toml;
|
||||
message = "units should be si";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "color = \"always\"" toml;
|
||||
message = "color should be always";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "resolve = false" toml;
|
||||
message = "resolve should be false";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "output_format = \"json\"" toml;
|
||||
message = "output_format should be json";
|
||||
}
|
||||
{
|
||||
assertion = lib.hasInfix "sort_by = \"pid\"" toml;
|
||||
message = "sort_by should be pid";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 5: output format enum validation
|
||||
outputFormatCsv = {
|
||||
name = "output-format-csv";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.output_format = "csv";
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lib.hasInfix "output_format = \"csv\"" toml;
|
||||
message = "output_format should accept csv";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 6: units enum validation
|
||||
unitsIec = {
|
||||
name = "units-iec";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.units = "iec";
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lib.hasInfix "units = \"iec\"" toml;
|
||||
message = "units should accept iec";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 7: color never value
|
||||
colorNever = {
|
||||
name = "color-never";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.color = "never";
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lib.hasInfix "color = \"never\"" toml;
|
||||
message = "color should accept never";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 8: freeform type allows custom keys
|
||||
freeformCustomKeys = {
|
||||
name = "freeform-custom-keys";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings = {
|
||||
defaults.theme = "dracula";
|
||||
custom_section = {
|
||||
custom_key = "custom_value";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lib.hasInfix "custom_key" toml;
|
||||
message = "freeform type should allow custom keys";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 9: all themes evaluate correctly
|
||||
allThemes =
|
||||
let
|
||||
themes = [
|
||||
"ansi"
|
||||
"catppuccin-mocha"
|
||||
"catppuccin-macchiato"
|
||||
"catppuccin-frappe"
|
||||
"catppuccin-latte"
|
||||
"gruvbox-dark"
|
||||
"gruvbox-light"
|
||||
"dracula"
|
||||
"nord"
|
||||
"tokyo-night"
|
||||
"tokyo-night-storm"
|
||||
"tokyo-night-light"
|
||||
"solarized-dark"
|
||||
"solarized-light"
|
||||
"one-dark"
|
||||
"mono"
|
||||
"auto"
|
||||
];
|
||||
in
|
||||
{
|
||||
name = "all-themes";
|
||||
# use the last theme as the test config
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.theme = "auto";
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
# verify all themes can be set by evaluating them
|
||||
themeResults = map
|
||||
(theme:
|
||||
let
|
||||
result = evalModule {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.theme = theme;
|
||||
};
|
||||
};
|
||||
toml = readGeneratedToml result;
|
||||
in
|
||||
{
|
||||
inherit theme;
|
||||
success = toml != null && lib.hasInfix theme toml;
|
||||
}
|
||||
)
|
||||
themes;
|
||||
allSucceeded = lib.all (r: r.success) themeResults;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = allSucceeded;
|
||||
message = "all themes should evaluate correctly: ${
|
||||
lib.concatMapStringsSep ", "
|
||||
(r: "${r.theme}=${if r.success then "ok" else "fail"}")
|
||||
themeResults
|
||||
}";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# test 10: fields list serialization
|
||||
fieldsListSerialization = {
|
||||
name = "fields-list-serialization";
|
||||
config = {
|
||||
programs.snitch = {
|
||||
enable = true;
|
||||
settings.defaults.fields = [ "pid" "process" "proto" "state" ];
|
||||
};
|
||||
};
|
||||
assertions = evalResult:
|
||||
let
|
||||
toml = readGeneratedToml evalResult;
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lib.hasInfix "pid" toml && lib.hasInfix "process" toml;
|
||||
message = "fields list should be serialized correctly";
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# run all tests and collect results
|
||||
runTests =
|
||||
let
|
||||
testResults = lib.mapAttrsToList
|
||||
(name: test:
|
||||
let
|
||||
evalResult = evalModule test.config;
|
||||
assertions = test.assertions evalResult;
|
||||
failures = lib.filter (a: !a.assertion) assertions;
|
||||
in
|
||||
{
|
||||
inherit name;
|
||||
testName = test.name;
|
||||
passed = failures == [ ];
|
||||
failures = map (f: f.message) failures;
|
||||
}
|
||||
)
|
||||
tests;
|
||||
|
||||
allPassed = lib.all (r: r.passed) testResults;
|
||||
failedTests = lib.filter (r: !r.passed) testResults;
|
||||
|
||||
summary = ''
|
||||
========================================
|
||||
home manager module test results
|
||||
========================================
|
||||
total tests: ${toString (builtins.length testResults)}
|
||||
passed: ${toString (builtins.length (lib.filter (r: r.passed) testResults))}
|
||||
failed: ${toString (builtins.length failedTests)}
|
||||
========================================
|
||||
${lib.concatMapStringsSep "\n" (r:
|
||||
if r.passed
|
||||
then "[yes] ${r.testName}"
|
||||
else "[no] ${r.testName}\n ${lib.concatStringsSep "\n " r.failures}"
|
||||
) testResults}
|
||||
========================================
|
||||
'';
|
||||
in
|
||||
{
|
||||
inherit testResults allPassed failedTests summary;
|
||||
};
|
||||
|
||||
results = runTests;
|
||||
|
||||
in
|
||||
pkgs.runCommand "hm-module-test"
|
||||
{
|
||||
passthru = {
|
||||
inherit results;
|
||||
# expose for debugging
|
||||
inherit evalModule tests;
|
||||
};
|
||||
}
|
||||
(
|
||||
if results.allPassed
|
||||
then ''
|
||||
echo "${results.summary}"
|
||||
echo "all tests passed"
|
||||
touch $out
|
||||
''
|
||||
else ''
|
||||
echo "${results.summary}"
|
||||
echo ""
|
||||
echo "failed tests:"
|
||||
${lib.concatMapStringsSep "\n" (t: ''
|
||||
echo " - ${t.testName}: ${lib.concatStringsSep ", " t.failures}"
|
||||
'') results.failedTests}
|
||||
exit 1
|
||||
''
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user