2 Commits

Author SHA1 Message Date
8301b337cc refactor: use unused constants instead of removing them
- Export unitTypes as UnitTypes and add HasValidUnitSuffix helper
- Use killed const (exit code 130) in execute() to detect SIGINT
- Update go.mod to go 1.26
2026-02-23 04:58:07 +00:00
c967fcb09e refactor: clean up unused code, fix typos, improve docs
- Remove unused 'killed' const and 'unitTypes' var (staticcheck U1000)
- Replace regexp with strings.TrimSuffix+switch in isFailed for consistency
- Fix typo: 'programatically' -> 'programmatically'
- Fix typo: 'an an int' -> 'as an int' in README and helpers.go
- Add missing godoc comments on exported helper functions
- Bump minimum Go version from 1.18 to 1.21
2026-02-18 08:23:50 +00:00
10 changed files with 198 additions and 386 deletions

View File

@@ -1,55 +0,0 @@
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]
permissions:
contents: read
jobs:
test:
name: Test (Go ${{ matrix.go-version }})
runs-on: ubuntu-latest
strategy:
matrix:
go-version: ["1.26"]
steps:
- uses: actions/checkout@v4
- name: Set up Go ${{ matrix.go-version }}
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go-version }}
cache: true
- name: Run tests with race detection and coverage
run: go test -race -coverprofile=coverage.out -covermode=atomic ./...
- name: Upload coverage to Codecov
if: matrix.go-version == '1.26'
uses: codecov/codecov-action@v5
with:
files: coverage.out
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: false
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.26"
cache: true
- name: Run staticcheck
uses: dominikh/staticcheck-action@v1
with:
version: latest
install-go: false

View File

@@ -13,10 +13,10 @@ import (
func TestErrorFuncs(t *testing.T) { func TestErrorFuncs(t *testing.T) {
errFuncs := []func(ctx context.Context, unit string, opts Options) error{ errFuncs := []func(ctx context.Context, unit string, opts Options) error{
func(ctx context.Context, unit string, opts Options) error { return Enable(ctx, unit, opts) }, Enable,
func(ctx context.Context, unit string, opts Options) error { return Disable(ctx, unit, opts) }, Disable,
func(ctx context.Context, unit string, opts Options) error { return Restart(ctx, unit, opts) }, Restart,
func(ctx context.Context, unit string, opts Options) error { return Start(ctx, unit, opts) }, Start,
} }
errCases := []struct { errCases := []struct {
unit string unit string

View File

@@ -1,119 +0,0 @@
package systemctl
import (
"errors"
"testing"
)
func TestFilterErr(t *testing.T) {
tests := []struct {
name string
stderr string
want error
}{
{
name: "empty stderr",
stderr: "",
want: nil,
},
{
name: "unit does not exist",
stderr: "Unit foo.service does not exist, proceeding anyway.",
want: ErrDoesNotExist,
},
{
name: "unit not found",
stderr: "Unit foo.service not found.",
want: ErrDoesNotExist,
},
{
name: "unit not loaded",
stderr: "Unit foo.service not loaded.",
want: ErrUnitNotLoaded,
},
{
name: "no such file or directory",
stderr: "No such file or directory",
want: ErrDoesNotExist,
},
{
name: "interactive authentication required",
stderr: "Interactive authentication required.",
want: ErrInsufficientPermissions,
},
{
name: "access denied",
stderr: "Access denied",
want: ErrInsufficientPermissions,
},
{
name: "dbus session bus address",
stderr: "Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS not set",
want: ErrBusFailure,
},
{
name: "unit is masked",
stderr: "Unit foo.service is masked.",
want: ErrMasked,
},
{
name: "generic failed",
stderr: "Failed to do something unknown",
want: ErrUnspecified,
},
{
name: "unrecognized warning",
stderr: "Warning: something benign happened",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := filterErr(tt.stderr)
if tt.want == nil {
if got != nil {
t.Errorf("filterErr(%q) = %v, want nil", tt.stderr, got)
}
return
}
if !errors.Is(got, tt.want) {
t.Errorf("filterErr(%q) = %v, want error wrapping %v", tt.stderr, got, tt.want)
}
})
}
}
func TestHasValidUnitSuffix(t *testing.T) {
tests := []struct {
unit string
want bool
}{
{"nginx.service", true},
{"sshd.socket", true},
{"backup.timer", true},
{"dev-sda1.device", true},
{"home.mount", true},
{"dev-sda1.swap", true},
{"user.slice", true},
{"multi-user.target", true},
{"session-1.scope", true},
{"foo.automount", true},
{"backup.path", true},
{"foo.snapshot", true},
{"nginx", false},
{"", false},
{"foo.bar", false},
{"foo.services", false},
{".service", true},
}
for _, tt := range tests {
t.Run(tt.unit, func(t *testing.T) {
got := HasValidUnitSuffix(tt.unit)
if got != tt.want {
t.Errorf("HasValidUnitSuffix(%q) = %v, want %v", tt.unit, got, tt.want)
}
})
}
}

View File

@@ -32,23 +32,7 @@ func GetNumRestarts(ctx context.Context, unit string, opts Options) (int, error)
if err != nil { if err != nil {
return -1, err return -1, err
} }
if value == "[not set]" { return strconv.Atoi(value)
return -1, ErrValueNotSet
}
restarts, err := strconv.Atoi(value)
if err != nil {
return -1, err
}
// systemd returns NRestarts=0 for both genuinely zero-restart units and
// nonexistent/unloaded units. Disambiguate by checking LoadState: if the
// unit isn't loaded, the value is meaningless.
if restarts == 0 {
loadState, loadErr := Show(ctx, unit, properties.LoadState, opts)
if loadErr == nil && loadState == "not-found" {
return -1, ErrValueNotSet
}
}
return restarts, nil
} }
// Get current memory in bytes (`systemctl show [unit] --property MemoryCurrent`) as an int // Get current memory in bytes (`systemctl show [unit] --property MemoryCurrent`) as an int

View File

@@ -105,8 +105,8 @@ func TestGetNumRestarts(t *testing.T) {
// try nonexistant unit in user mode as user // try nonexistant unit in user mode as user
{"nonexistant", ErrValueNotSet, Options{UserMode: false}, true}, {"nonexistant", ErrValueNotSet, Options{UserMode: false}, true},
// try existing unit in user mode as user (loaded, so NRestarts=0 is valid) // try existing unit in user mode as user
{"syncthing", nil, Options{UserMode: true}, true}, {"syncthing", ErrValueNotSet, Options{UserMode: true}, true},
// try existing unit in system mode as user // try existing unit in system mode as user
{"nginx", nil, Options{UserMode: false}, true}, {"nginx", nil, Options{UserMode: false}, true},

View File

@@ -12,10 +12,8 @@ import (
// files, and recreate the entire dependency tree. While the daemon is being // files, and recreate the entire dependency tree. While the daemon is being
// reloaded, all sockets systemd listens on behalf of user configuration will // reloaded, all sockets systemd listens on behalf of user configuration will
// stay accessible. // stay accessible.
// func DaemonReload(ctx context.Context, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return daemonReload(ctx, opts)
func DaemonReload(ctx context.Context, opts Options, args ...string) error {
return daemonReload(ctx, opts, args...)
} }
// Reenables one or more units. // Reenables one or more units.
@@ -23,10 +21,8 @@ func DaemonReload(ctx context.Context, opts Options, args ...string) error {
// This removes all symlinks to the unit files backing the specified units from // This removes all symlinks to the unit files backing the specified units from
// the unit configuration directory, then recreates the symlink to the unit again, // the unit configuration directory, then recreates the symlink to the unit again,
// atomically. Can be used to change the symlink target. // atomically. Can be used to change the symlink target.
// func Reenable(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return reenable(ctx, unit, opts)
func Reenable(ctx context.Context, unit string, opts Options, args ...string) error {
return reenable(ctx, unit, opts, args...)
} }
// Disables one or more units. // Disables one or more units.
@@ -34,10 +30,8 @@ func Reenable(ctx context.Context, unit string, opts Options, args ...string) er
// This removes all symlinks to the unit files backing the specified units from // This removes all symlinks to the unit files backing the specified units from
// the unit configuration directory, and hence undoes any changes made by // the unit configuration directory, and hence undoes any changes made by
// enable or link. // enable or link.
// func Disable(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return disable(ctx, unit, opts)
func Disable(ctx context.Context, unit string, opts Options, args ...string) error {
return disable(ctx, unit, opts, args...)
} }
// Enable one or more units or unit instances. // Enable one or more units or unit instances.
@@ -46,20 +40,17 @@ func Disable(ctx context.Context, unit string, opts Options, args ...string) err
// the indicated unit files. After the symlinks have been created, the system // the indicated unit files. After the symlinks have been created, the system
// manager configuration is reloaded (in a way equivalent to daemon-reload), // manager configuration is reloaded (in a way equivalent to daemon-reload),
// in order to ensure the changes are taken into account immediately. // in order to ensure the changes are taken into account immediately.
// func Enable(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return enable(ctx, unit, opts)
func Enable(ctx context.Context, unit string, opts Options, args ...string) error {
return enable(ctx, unit, opts, args...)
} }
// Check whether any of the specified units are active (i.e. running). // Check whether any of the specified units are active (i.e. running).
// //
// Returns true if the unit is active, false if inactive or failed. // Returns true if the unit is active, false if inactive or failed.
// Also returns false in an error case. // Also returns false in an error case.
// func IsActive(ctx context.Context, unit string, opts Options) (bool, error) {
// Any additional arguments are passed directly to the systemctl command. result, err := isActive(ctx, unit, opts)
func IsActive(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { return result, err
return isActive(ctx, unit, opts, args...)
} }
// Checks whether any of the specified unit files are enabled (as with enable). // Checks whether any of the specified unit files are enabled (as with enable).
@@ -71,17 +62,15 @@ func IsActive(ctx context.Context, unit string, opts Options, args ...string) (b
// //
// See https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6 // See https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6
// for more information // for more information
// func IsEnabled(ctx context.Context, unit string, opts Options) (bool, error) {
// Any additional arguments are passed directly to the systemctl command. result, err := isEnabled(ctx, unit, opts)
func IsEnabled(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { return result, err
return isEnabled(ctx, unit, opts, args...)
} }
// Check whether any of the specified units are in a "failed" state. // Check whether any of the specified units are in a "failed" state.
// func IsFailed(ctx context.Context, unit string, opts Options) (bool, error) {
// Any additional arguments are passed directly to the systemctl command. result, err := isFailed(ctx, unit, opts)
func IsFailed(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { return result, err
return isFailed(ctx, unit, opts, args...)
} }
// Mask one or more units, as specified on the command line. This will link // Mask one or more units, as specified on the command line. This will link
@@ -90,33 +79,26 @@ func IsFailed(ctx context.Context, unit string, opts Options, args ...string) (b
// Notably, Mask may return ErrDoesNotExist if a unit doesn't exist, but it will // Notably, Mask may return ErrDoesNotExist if a unit doesn't exist, but it will
// continue masking anyway. Calling Mask on a non-existing masked unit does not // continue masking anyway. Calling Mask on a non-existing masked unit does not
// return an error. Similarly, see Unmask. // return an error. Similarly, see Unmask.
// func Mask(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return mask(ctx, unit, opts)
func Mask(ctx context.Context, unit string, opts Options, args ...string) error {
return mask(ctx, unit, opts, args...)
} }
// Stop and then start one or more units specified on the command line. // Stop and then start one or more units specified on the command line.
// If the units are not running yet, they will be started. // If the units are not running yet, they will be started.
// func Restart(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return restart(ctx, unit, opts)
func Restart(ctx context.Context, unit string, opts Options, args ...string) error {
return restart(ctx, unit, opts, args...)
} }
// Show a selected property of a unit. Accepted properties are predefined in the // Show a selected property of a unit. Accepted properties are predefined in the
// properties subpackage to guarantee properties are valid and assist code-completion. // properties subpackage to guarantee properties are valid and assist code-completion.
// func Show(ctx context.Context, unit string, property properties.Property, opts Options) (string, error) {
// Any additional arguments are passed directly to the systemctl command. str, err := show(ctx, unit, property, opts)
func Show(ctx context.Context, unit string, property properties.Property, opts Options, args ...string) (string, error) { return str, err
return show(ctx, unit, property, opts, args...)
} }
// Start (activate) a given unit // Start (activate) a given unit
// func Start(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return start(ctx, unit, opts)
func Start(ctx context.Context, unit string, opts Options, args ...string) error {
return start(ctx, unit, opts, args...)
} }
// Get back the status string which would be returned by running // Get back the status string which would be returned by running
@@ -124,17 +106,14 @@ func Start(ctx context.Context, unit string, opts Options, args ...string) error
// //
// Generally, it makes more sense to programmatically retrieve the properties // Generally, it makes more sense to programmatically retrieve the properties
// using Show, but this command is provided for the sake of completeness // using Show, but this command is provided for the sake of completeness
// func Status(ctx context.Context, unit string, opts Options) (string, error) {
// Any additional arguments are passed directly to the systemctl command. stat, err := status(ctx, unit, opts)
func Status(ctx context.Context, unit string, opts Options, args ...string) (string, error) { return stat, err
return status(ctx, unit, opts, args...)
} }
// Stop (deactivate) a given unit // Stop (deactivate) a given unit
// func Stop(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return stop(ctx, unit, opts)
func Stop(ctx context.Context, unit string, opts Options, args ...string) error {
return stop(ctx, unit, opts, args...)
} }
// Unmask one or more unit files, as specified on the command line. // Unmask one or more unit files, as specified on the command line.
@@ -144,8 +123,6 @@ func Stop(ctx context.Context, unit string, opts Options, args ...string) error
// doesn't exist, but only if it's not already masked. // doesn't exist, but only if it's not already masked.
// If the unit doesn't exist but it's masked anyway, no error will be // If the unit doesn't exist but it's masked anyway, no error will be
// returned. Gross, I know. Take it up with Poettering. // returned. Gross, I know. Take it up with Poettering.
// func Unmask(ctx context.Context, unit string, opts Options) error {
// Any additional arguments are passed directly to the systemctl command. return unmask(ctx, unit, opts)
func Unmask(ctx context.Context, unit string, opts Options, args ...string) error {
return unmask(ctx, unit, opts, args...)
} }

View File

@@ -8,58 +8,58 @@ import (
"github.com/taigrr/systemctl/properties" "github.com/taigrr/systemctl/properties"
) )
func daemonReload(_ context.Context, _ Options, _ ...string) error { func daemonReload(ctx context.Context, opts Options) error {
return nil return nil
} }
func reenable(_ context.Context, _ string, _ Options, _ ...string) error { func reenable(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func disable(_ context.Context, _ string, _ Options, _ ...string) error { func disable(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func enable(_ context.Context, _ string, _ Options, _ ...string) error { func enable(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func isActive(_ context.Context, _ string, _ Options, _ ...string) (bool, error) { func isActive(ctx context.Context, unit string, opts Options) (bool, error) {
return false, nil return false, nil
} }
func isEnabled(_ context.Context, _ string, _ Options, _ ...string) (bool, error) { func isEnabled(ctx context.Context, unit string, opts Options) (bool, error) {
return false, nil return false, nil
} }
func isFailed(_ context.Context, _ string, _ Options, _ ...string) (bool, error) { func isFailed(ctx context.Context, unit string, opts Options) (bool, error) {
return false, nil return false, nil
} }
func mask(_ context.Context, _ string, _ Options, _ ...string) error { func mask(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func restart(_ context.Context, _ string, _ Options, _ ...string) error { func restart(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func show(_ context.Context, _ string, _ properties.Property, _ Options, _ ...string) (string, error) { func show(ctx context.Context, unit string, property properties.Property, opts Options) (string, error) {
return "", nil return "", nil
} }
func start(_ context.Context, _ string, _ Options, _ ...string) error { func start(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func status(_ context.Context, _ string, _ Options, _ ...string) (string, error) { func status(ctx context.Context, unit string, opts Options) (string, error) {
return "", nil return "", nil
} }
func stop(_ context.Context, _ string, _ Options, _ ...string) error { func stop(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }
func unmask(_ context.Context, _ string, _ Options, _ ...string) error { func unmask(ctx context.Context, unit string, opts Options) error {
return nil return nil
} }

View File

@@ -9,33 +9,74 @@ import (
"github.com/taigrr/systemctl/properties" "github.com/taigrr/systemctl/properties"
) )
func daemonReload(ctx context.Context, opts Options, args ...string) error { // Reload systemd manager configuration.
a := prepareArgs("daemon-reload", opts, args...) //
_, _, _, err := execute(ctx, a) // This will rerun all generators (see systemd. generator(7)), reload all unit
// files, and recreate the entire dependency tree. While the daemon is being
// reloaded, all sockets systemd listens on behalf of user configuration will
// stay accessible.
func daemonReload(ctx context.Context, opts Options) error {
args := []string{"daemon-reload", "--system"}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func reenable(ctx context.Context, unit string, opts Options, args ...string) error { // Reenables one or more units.
a := prepareArgs("reenable", opts, append([]string{unit}, args...)...) //
_, _, _, err := execute(ctx, a) // This removes all symlinks to the unit files backing the specified units from
// the unit configuration directory, then recreates the symlink to the unit again,
// atomically. Can be used to change the symlink target.
func reenable(ctx context.Context, unit string, opts Options) error {
args := []string{"reenable", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func disable(ctx context.Context, unit string, opts Options, args ...string) error { // Disables one or more units.
a := prepareArgs("disable", opts, append([]string{unit}, args...)...) //
_, _, _, err := execute(ctx, a) // This removes all symlinks to the unit files backing the specified units from
// the unit configuration directory, and hence undoes any changes made by
// enable or link.
func disable(ctx context.Context, unit string, opts Options) error {
args := []string{"disable", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func enable(ctx context.Context, unit string, opts Options, args ...string) error { // Enable one or more units or unit instances.
a := prepareArgs("enable", opts, append([]string{unit}, args...)...) //
_, _, _, err := execute(ctx, a) // This will create a set of symlinks, as encoded in the [Install] sections of
// the indicated unit files. After the symlinks have been created, the system
// manager configuration is reloaded (in a way equivalent to daemon-reload),
// in order to ensure the changes are taken into account immediately.
func enable(ctx context.Context, unit string, opts Options) error {
args := []string{"enable", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func isActive(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { // Check whether any of the specified units are active (i.e. running).
a := prepareArgs("is-active", opts, append([]string{unit}, args...)...) //
stdout, _, _, err := execute(ctx, a) // Returns true if the unit is active, false if inactive or failed.
// Also returns false in an error case.
func isActive(ctx context.Context, unit string, opts Options) (bool, error) {
args := []string{"is-active", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
stdout, _, _, err := execute(ctx, args)
stdout = strings.TrimSuffix(stdout, "\n") stdout = strings.TrimSuffix(stdout, "\n")
switch stdout { switch stdout {
case "inactive": case "inactive":
@@ -51,9 +92,21 @@ func isActive(ctx context.Context, unit string, opts Options, args ...string) (b
} }
} }
func isEnabled(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { // Checks whether any of the specified unit files are enabled (as with enable).
a := prepareArgs("is-enabled", opts, append([]string{unit}, args...)...) //
stdout, _, _, err := execute(ctx, a) // Returns true if the unit is enabled, aliased, static, indirect, generated
// or transient.
//
// Returns false if disabled. Also returns an error if linked, masked, or bad.
//
// See https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6
// for more information
func isEnabled(ctx context.Context, unit string, opts Options) (bool, error) {
args := []string{"is-enabled", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
stdout, _, _, err := execute(ctx, args)
stdout = strings.TrimSuffix(stdout, "\n") stdout = strings.TrimSuffix(stdout, "\n")
switch stdout { switch stdout {
case "enabled": case "enabled":
@@ -87,9 +140,13 @@ func isEnabled(ctx context.Context, unit string, opts Options, args ...string) (
return false, ErrUnspecified return false, ErrUnspecified
} }
func isFailed(ctx context.Context, unit string, opts Options, args ...string) (bool, error) { // Check whether any of the specified units are in a "failed" state.
a := prepareArgs("is-failed", opts, append([]string{unit}, args...)...) func isFailed(ctx context.Context, unit string, opts Options) (bool, error) {
stdout, _, _, err := execute(ctx, a) args := []string{"is-failed", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
stdout, _, _, err := execute(ctx, args)
stdout = strings.TrimSuffix(stdout, "\n") stdout = strings.TrimSuffix(stdout, "\n")
switch stdout { switch stdout {
case "inactive": case "inactive":
@@ -103,47 +160,91 @@ func isFailed(ctx context.Context, unit string, opts Options, args ...string) (b
} }
} }
func mask(ctx context.Context, unit string, opts Options, args ...string) error { // Mask one or more units, as specified on the command line. This will link
a := prepareArgs("mask", opts, append([]string{unit}, args...)...) // these unit files to /dev/null, making it impossible to start them.
_, _, _, err := execute(ctx, a) //
// Notably, Mask may return ErrDoesNotExist if a unit doesn't exist, but it will
// continue masking anyway. Calling Mask on a non-existing masked unit does not
// return an error. Similarly, see Unmask.
func mask(ctx context.Context, unit string, opts Options) error {
args := []string{"mask", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func restart(ctx context.Context, unit string, opts Options, args ...string) error { // Stop and then start one or more units specified on the command line.
a := prepareArgs("restart", opts, append([]string{unit}, args...)...) // If the units are not running yet, they will be started.
_, _, _, err := execute(ctx, a) func restart(ctx context.Context, unit string, opts Options) error {
args := []string{"restart", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func show(ctx context.Context, unit string, property properties.Property, opts Options, args ...string) (string, error) { // Show a selected property of a unit. Accepted properties are predefined in the
extra := append([]string{unit, "--property", string(property)}, args...) // properties subpackage to guarantee properties are valid and assist code-completion.
a := prepareArgs("show", opts, extra...) func show(ctx context.Context, unit string, property properties.Property, opts Options) (string, error) {
stdout, _, _, err := execute(ctx, a) args := []string{"show", "--system", unit, "--property", string(property)}
if opts.UserMode {
args[1] = "--user"
}
stdout, _, _, err := execute(ctx, args)
stdout = strings.TrimPrefix(stdout, string(property)+"=") stdout = strings.TrimPrefix(stdout, string(property)+"=")
stdout = strings.TrimSuffix(stdout, "\n") stdout = strings.TrimSuffix(stdout, "\n")
return stdout, err return stdout, err
} }
func start(ctx context.Context, unit string, opts Options, args ...string) error { // Start (activate) a given unit
a := prepareArgs("start", opts, append([]string{unit}, args...)...) func start(ctx context.Context, unit string, opts Options) error {
_, _, _, err := execute(ctx, a) args := []string{"start", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func status(ctx context.Context, unit string, opts Options, args ...string) (string, error) { // Get back the status string which would be returned by running
a := prepareArgs("status", opts, append([]string{unit}, args...)...) // `systemctl status [unit]`.
stdout, _, _, err := execute(ctx, a) //
// Generally, it makes more sense to programmatically retrieve the properties
// using Show, but this command is provided for the sake of completeness
func status(ctx context.Context, unit string, opts Options) (string, error) {
args := []string{"status", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
stdout, _, _, err := execute(ctx, args)
return stdout, err return stdout, err
} }
func stop(ctx context.Context, unit string, opts Options, args ...string) error { // Stop (deactivate) a given unit
a := prepareArgs("stop", opts, append([]string{unit}, args...)...) func stop(ctx context.Context, unit string, opts Options) error {
_, _, _, err := execute(ctx, a) args := []string{"stop", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }
func unmask(ctx context.Context, unit string, opts Options, args ...string) error { // Unmask one or more unit files, as specified on the command line.
a := prepareArgs("unmask", opts, append([]string{unit}, args...)...) // This will undo the effect of Mask.
_, _, _, err := execute(ctx, a) //
// In line with systemd, Unmask will return ErrDoesNotExist if the unit
// doesn't exist, but only if it's not already masked.
// If the unit doesn't exist but it's masked anyway, no error will be
// returned. Gross, I know. Take it up with Poettering.
func unmask(ctx context.Context, unit string, opts Options) error {
args := []string{"unmask", "--system", unit}
if opts.UserMode {
args[1] = "--user"
}
_, _, _, err := execute(ctx, args)
return err return err
} }

14
util.go
View File

@@ -55,20 +55,6 @@ func execute(ctx context.Context, args []string) (string, string, int, error) {
return output, warnings, code, err return output, warnings, code, err
} }
// prepareArgs builds the systemctl command arguments from a base command,
// options, and any additional arguments the caller wants to pass through.
func prepareArgs(base string, opts Options, extra ...string) []string {
args := make([]string, 0, 2+len(extra))
args = append(args, base)
if opts.UserMode {
args = append(args, "--user")
} else {
args = append(args, "--system")
}
args = append(args, extra...)
return args
}
func filterErr(stderr string) error { func filterErr(stderr string) error {
switch { switch {
case strings.Contains(stderr, `does not exist`): case strings.Contains(stderr, `does not exist`):

View File

@@ -1,62 +0,0 @@
package systemctl
import (
"reflect"
"testing"
)
func TestPrepareArgs(t *testing.T) {
tests := []struct {
name string
base string
opts Options
extra []string
expected []string
}{
{
name: "system mode no extra",
base: "start",
opts: Options{},
extra: nil,
expected: []string{"start", "--system"},
},
{
name: "user mode no extra",
base: "start",
opts: Options{UserMode: true},
extra: nil,
expected: []string{"start", "--user"},
},
{
name: "system mode with unit",
base: "start",
opts: Options{},
extra: []string{"nginx.service"},
expected: []string{"start", "--system", "nginx.service"},
},
{
name: "user mode with unit and extra args",
base: "restart",
opts: Options{UserMode: true},
extra: []string{"foo.service", "--no-block"},
expected: []string{"restart", "--user", "foo.service", "--no-block"},
},
{
name: "daemon-reload no extra",
base: "daemon-reload",
opts: Options{},
extra: nil,
expected: []string{"daemon-reload", "--system"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := prepareArgs(tt.base, tt.opts, tt.extra...)
if !reflect.DeepEqual(got, tt.expected) {
t.Errorf("prepareArgs(%q, %+v, %v) = %v, want %v",
tt.base, tt.opts, tt.extra, got, tt.expected)
}
})
}
}