Pull request: AGDNS-3826-use-executil-run

Squashed commit of the following:

commit 59e53b9e5fe5f0ed342c4c4581f847613e3268d5
Merge: b965a7dcd a3866c68e
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Apr 2 10:11:29 2026 +0700

    Merge remote-tracking branch 'origin/master' into AGDNS-3826-use-executil-run

commit b965a7dcdbbed2058ec0f05800a2c5925a8b2766
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Apr 2 10:08:26 2026 +0700

    scripts: imp code

commit ea8efa085bd9fd5bacd6b899c052f0197f2ea9af
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Apr 2 08:50:17 2026 +0700

    ossvc: imp code

commit 2ba0269f9cd13298dd1aaa0e6d9dd9e0c9879df2
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Wed Apr 1 08:32:10 2026 +0700

    ossvc: imp tests

commit 5141a0a86ae17173a502d4a65315917bc36143b0
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Tue Mar 31 12:33:45 2026 +0700

    ossvc: imp tests

commit 3ec53df0c200cb59ef0d7841b21aeab9f39bf8ad
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Tue Mar 31 10:53:23 2026 +0700

    ossvc: imp tests

commit 3030f92f7f8b745e387bb42e6d9af3f0fd8fbb6b
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Tue Mar 31 09:19:16 2026 +0700

    ossvc: imp code

commit 4644f3fe20e0f711da91adf98faf4a88dad932a2
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Tue Mar 31 09:18:54 2026 +0700

    all: imp code

commit 282ee76141dabcaf37df555db41db2c2cc82472d
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Tue Mar 31 09:08:54 2026 +0700

    osvc: imp tests

commit 8e4634570ac71ce4f16fe3796cc64d774c7dc257
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Mon Mar 30 16:14:15 2026 +0700

    osvc: imp tests

commit 3abade03bed5d45e900c2e579c65eb5cc66990a7
Merge: 56ae2eb4f 55d0d6ae5
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Mon Mar 30 11:03:35 2026 +0700

    Merge remote-tracking branch 'origin/master' into AGDNS-3826-use-executil-run

commit 56ae2eb4f8caea427afb87f46e90f21ae8d9fa39
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Fri Mar 27 10:43:07 2026 +0700

    aghnet: imp logs

commit 7ead0907d39fab66602ab1d94ec17a477338b371
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 12:47:23 2026 +0700

    all: imp code

commit afa235d8acfeb8b4286a26b60dddd61545533761
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 12:38:30 2026 +0700

    all: rm aghos.RunCommand

commit bd36b286f26b068e145b5ffe2d2d23fb7c5525fa
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 12:38:21 2026 +0700

    ossvc: rm aghos.RunCommand

commit bba1e37aa4a34f557cec9653abc2e90816e39054
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 12:13:05 2026 +0700

    ossvc: pass cmd cons

commit 6cc18f7801d669beb2188f79692a4a590fce2885
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 11:38:21 2026 +0700

    scripts: rm aghos.RunCommand

commit 37d188db6fa5d5da1138299be549dbc9d00fd1b7
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Mar 26 11:02:46 2026 +0700

    aghnet: rm aghos.RunCommand
This commit is contained in:
Dimitry Kolyshev committed 2026-04-06 02:17:26 +00:00
1 parent a3866c68ed
commit 1d491ad0f3
18 files changed
+550 -213

No files matched your search

-4
View File
@@ -11,10 +11,6 @@ import (
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec" "github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
) )
// DefaultOutputLimit is the default limit of bytes for commands' standard
// output and standard error.
const DefaultOutputLimit = 512
// ConfigModifier defines an interface for updating the global configuration. // ConfigModifier defines an interface for updating the global configuration.
type ConfigModifier interface { type ConfigModifier interface {
// Apply applies changes to the global configuration. // Apply applies changes to the global configuration.
+30 -14
View File
@@ -13,9 +13,13 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/osutil/executil" "github.com/AdguardTeam/golibs/osutil/executil"
) )
// networkSetupCmd is the command to configure network settings.
const networkSetupCmd = "networksetup"
// hardwarePortInfo contains information about the current state of the internet // hardwarePortInfo contains information about the current state of the internet
// connection obtained from macOS networksetup. // connection obtained from macOS networksetup.
type hardwarePortInfo struct { type hardwarePortInfo struct {
@@ -72,14 +76,21 @@ func getNetworkSetupHardwareReports(
ctx context.Context, ctx context.Context,
cmdCons executil.CommandConstructor, cmdCons executil.CommandConstructor,
) (reports map[string]string) { ) (reports map[string]string) {
_, out, err := aghos.RunCommand(ctx, cmdCons, "networksetup", "-listallhardwareports") stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
err := executil.Run(ctx, cmdCons, &executil.CommandConfig{
Stderr: &stderr,
Stdout: ioutil.NewTruncatedWriter(&stdout, aghos.MaxCmdOutputSize),
Path: networkSetupCmd,
Args: []string{"-listallhardwareports"},
})
if err != nil { if err != nil {
return nil return nil
} }
reports = make(map[string]string) reports = make(map[string]string)
matches := hardwareReportsReg.FindAllSubmatch(out, -1) matches := hardwareReportsReg.FindAllSubmatch(stdout.Bytes(), -1)
for _, m := range matches { for _, m := range matches {
reports[string(m[2])] = string(m[1]) reports[string(m[2])] = string(m[1])
} }
@@ -98,11 +109,19 @@ func getHardwarePortInfo(
cmdCons executil.CommandConstructor, cmdCons executil.CommandConstructor,
hardwarePort string, hardwarePort string,
) (h hardwarePortInfo, err error) { ) (h hardwarePortInfo, err error) {
_, out, err := aghos.RunCommand(ctx, cmdCons, "networksetup", "-getinfo", hardwarePort) stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
err = executil.Run(ctx, cmdCons, &executil.CommandConfig{
Stderr: &stderr,
Stdout: ioutil.NewTruncatedWriter(&stdout, aghos.MaxCmdOutputSize),
Path: networkSetupCmd,
Args: []string{"-getinfo", hardwarePort},
})
if err != nil { if err != nil {
return h, err return h, err
} }
out := stdout.Bytes()
match := hardwarePortReg.FindSubmatch(out) match := hardwarePortReg.FindSubmatch(out)
if len(match) != 4 { if len(match) != 4 {
return h, errors.Error("could not find hardware port info") return h, errors.Error("could not find hardware port info")
@@ -140,19 +159,18 @@ func ifaceSetStaticIP(
args := append([]string{"-setdnsservers", portInfo.name}, dnsAddrs...) args := append([]string{"-setdnsservers", portInfo.name}, dnsAddrs...)
// Setting DNS servers is necessary when configuring a static IP // Setting DNS servers is necessary when configuring a static IP.
code, _, err := aghos.RunCommand(ctx, cmdCons, "networksetup", args...) err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, networkSetupCmd, args...)
if err != nil { if err != nil {
return err return fmt.Errorf("networksetup failed to set dns servers: %w", err)
} else if code != 0 {
return fmt.Errorf("failed to set DNS servers, code=%d", code)
} }
// Actually configures hardware port to have static IP // Actually configures hardware port to have static IP.
code, _, err = aghos.RunCommand( err = executil.RunWithPeek(
ctx, ctx,
cmdCons, cmdCons,
"networksetup", aghos.MaxCmdOutputSize,
networkSetupCmd,
"-setmanual", "-setmanual",
portInfo.name, portInfo.name,
portInfo.ip, portInfo.ip,
@@ -160,9 +178,7 @@ func ifaceSetStaticIP(
portInfo.gatewayIP, portInfo.gatewayIP,
) )
if err != nil { if err != nil {
return err return fmt.Errorf("networksetup failed to configure dns servers: %w", err)
} else if code != 0 {
return fmt.Errorf("failed to set DNS servers, code=%d", code)
} }
return nil return nil
+7 -5
View File
@@ -81,7 +81,7 @@ func TestIfaceHasStaticIP(t *testing.T) {
}), }),
ifaceName: "en0", ifaceName: "en0",
wantHas: assert.False, wantHas: assert.False,
wantErrMsg: `command "networksetup" failed: running: can't get: `, wantErrMsg: "running: can't get",
}, { }, {
name: "port_bad_output", name: "port_bad_output",
cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{ cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{
@@ -215,8 +215,9 @@ func TestIfaceSetStaticIP(t *testing.T) {
Out: "", Out: "",
Code: 0, Code: 0,
}), }),
fsys: succFsys, fsys: succFsys,
wantErrMsg: `command "networksetup" failed: running: can't set: `, wantErrMsg: `networksetup failed to set dns servers: running: can't set; ` +
`stderr peek: ""; stdout peek: ""`,
}, { }, {
name: "set_manual_error", name: "set_manual_error",
cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{ cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{
@@ -240,8 +241,9 @@ func TestIfaceSetStaticIP(t *testing.T) {
Out: "", Out: "",
Code: 0, Code: 0,
}), }),
fsys: succFsys, fsys: succFsys,
wantErrMsg: `command "networksetup" failed: running: can't set: `, wantErrMsg: `networksetup failed to configure dns servers: running: can't set; ` +
`stderr peek: ""; stdout peek: ""`,
}} }}
for _, tc := range testCases { for _, tc := range testCases {
-3
View File
@@ -38,9 +38,6 @@ func substRootDirFS(tb testing.TB, fsys fs.FS) {
rootDirFS = fsys rootDirFS = fsys
} }
// RunCmdFunc is the signature of aghos.RunCommand function.
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
// ifaceAddrsFunc is the signature of net.InterfaceAddrs function. // ifaceAddrsFunc is the signature of net.InterfaceAddrs function.
type ifaceAddrsFunc func() (ifaces []net.Addr, err error) type ifaceAddrsFunc func() (ifaces []net.Addr, err error)
-42
View File
@@ -19,8 +19,6 @@ import (
"strings" "strings"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/osutil"
"github.com/AdguardTeam/golibs/osutil/executil" "github.com/AdguardTeam/golibs/osutil/executil"
) )
@@ -52,46 +50,6 @@ func HaveAdminRights() (bool, error) {
// bytes. // bytes.
const MaxCmdOutputSize = 64 * 1024 const MaxCmdOutputSize = 64 * 1024
// RunCommand runs shell command.
//
// TODO(s.chzhen): Consider removing this after addressing the current behavior
// where a non-zero exit code is returned together with a nil error.
func RunCommand(
ctx context.Context,
cmdCons executil.CommandConstructor,
command string,
arguments ...string,
) (code int, output []byte, err error) {
stdoutBuf := bytes.Buffer{}
stderrBuf := bytes.Buffer{}
err = executil.Run(
ctx,
cmdCons,
&executil.CommandConfig{
Path: command,
Args: arguments,
Stdout: ioutil.NewTruncatedWriter(&stdoutBuf, MaxCmdOutputSize),
Stderr: &stderrBuf,
},
)
if err == nil {
return osutil.ExitCodeSuccess, stdoutBuf.Bytes(), nil
}
code, ok := executil.ExitCodeFromError(err)
if ok {
// Mirror the old behavior and return a nil-error on non-zero code
// status.
return code, stderrBuf.Bytes(), nil
}
code = osutil.ExitCodeFailure
return code, nil, fmt.Errorf("command %q failed: %w: %s", command, err, &stdoutBuf)
}
// psArgs holds the default ps arguments to avoid per-call slice allocations. // psArgs holds the default ps arguments to avoid per-call slice allocations.
// //
// Don't use -C flag here since it's a feature of linux's ps // Don't use -C flag here since it's a feature of linux's ps
-3
View File
@@ -24,9 +24,6 @@ const testTimeout = 1 * time.Second
// testdata is the filesystem containing data for testing the package. // testdata is the filesystem containing data for testing the package.
var testdata fs.FS = os.DirFS("./testdata") var testdata fs.FS = os.DirFS("./testdata")
// RunCmdFunc is the signature of aghos.RunCommand function.
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
func Test_New(t *testing.T) { func Test_New(t *testing.T) {
var a Interface var a Interface
require.NotPanics(t, func() { a = New(slogutil.NewDiscardLogger()) }) require.NotPanics(t, func() { a = New(slogutil.NewDiscardLogger()) })
+12 -6
View File
@@ -18,6 +18,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghalg" "github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp" "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/container" "github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
@@ -171,7 +172,7 @@ func (req *checkConfReq) validateDNS(
} }
// Try to fix automatically. // Try to fix automatically.
canAutofix = checkDNSStubListener(ctx, l) canAutofix = checkDNSStubListener(ctx, l, cmdCons)
if canAutofix && req.DNS.Autofix { if canAutofix && req.DNS.Autofix {
if derr := disableDNSStubListener(ctx, l, cmdCons); derr != nil { if derr := disableDNSStubListener(ctx, l, cmdCons); derr != nil {
l.ErrorContext(ctx, "disabling DNSStubListener", slogutil.KeyError, derr) l.ErrorContext(ctx, "disabling DNSStubListener", slogutil.KeyError, derr)
@@ -262,8 +263,13 @@ func handleStaticIP(
return ipResp return ipResp
} }
// checkDNSStubListener returns true if DNSStubListener is active. // checkDNSStubListener returns true if DNSStubListener is active. l and
func checkDNSStubListener(ctx context.Context, l *slog.Logger) (ok bool) { // cmdCons must not be nil.
func checkDNSStubListener(
ctx context.Context,
l *slog.Logger,
cmdCons executil.CommandConstructor,
) (ok bool) {
if runtime.GOOS != "linux" { if runtime.GOOS != "linux" {
return false return false
} }
@@ -281,8 +287,8 @@ func checkDNSStubListener(ctx context.Context, l *slog.Logger) (ok bool) {
err := executil.RunWithPeek( err := executil.RunWithPeek(
ctx, ctx,
executil.SystemCommandConstructor{}, cmdCons,
agh.DefaultOutputLimit, aghos.MaxCmdOutputSize,
cmd.Key, cmd.Key,
cmd.Value..., cmd.Value...,
) )
@@ -339,7 +345,7 @@ func disableDNSStubListener(
err = executil.RunWithPeek( err = executil.RunWithPeek(
ctx, ctx,
cmdCons, cmdCons,
agh.DefaultOutputLimit, aghos.MaxCmdOutputSize,
systemctlCmd, systemctlCmd,
systemctlArgs..., systemctlArgs...,
) )
+60
View File
@@ -0,0 +1,60 @@
package ossvc_test
import (
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/ossvc"
"github.com/kardianos/service"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfigureServiceOptions(t *testing.T) {
t.Parallel()
const (
vInfo = "v1.0.0"
serviceName = "test-service"
svcInfoKey = "SvcInfo"
)
t.Run("nil_option", func(t *testing.T) {
conf := &service.Config{
Name: serviceName,
}
ossvc.ConfigureServiceOptions(conf, vInfo)
require.NotNil(t, conf.Option)
svcInfo, ok := conf.Option[svcInfoKey]
require.True(t, ok)
assert.Contains(t, svcInfo, vInfo)
})
t.Run("existing_option", func(t *testing.T) {
t.Parallel()
const (
key = "ExistingKey"
val = "ExistingValue"
)
conf := &service.Config{
Name: serviceName,
Option: map[string]any{
key: val,
},
}
ossvc.ConfigureServiceOptions(conf, vInfo)
require.NotNil(t, conf.Option)
assert.Equal(t, val, conf.Option[key])
svcInfo, ok := conf.Option[svcInfoKey]
require.True(t, ok)
assert.Contains(t, svcInfo, vInfo)
})
}
+24 -17
View File
@@ -10,6 +10,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil/executil" "github.com/AdguardTeam/golibs/osutil/executil"
"github.com/kardianos/service" "github.com/kardianos/service"
) )
@@ -30,7 +31,7 @@ type manager struct {
func newManager(ctx context.Context, conf *ManagerConfig) (mgr *manager) { func newManager(ctx context.Context, conf *ManagerConfig) (mgr *manager) {
// Call chooseSystem explicitly to introduce platform-specific support for // Call chooseSystem explicitly to introduce platform-specific support for
// service package. It's a noop for other GOOS values. // service package. It's a noop for other GOOS values.
chooseSystem(ctx, conf.Logger) chooseSystem(ctx, conf.Logger, conf.CommandConstructor)
return &manager{ return &manager{
logger: conf.Logger, logger: conf.Logger,
@@ -91,9 +92,12 @@ func (m *manager) Status(ctx context.Context, name ServiceName) (status Status,
svcStatus, err := s.Status() svcStatus, err := s.Status()
if err != nil && m.isUnixSystemV { if err != nil && m.isUnixSystemV {
var code int m.logger.DebugContext(ctx, "got error from status request", slogutil.KeyError, err)
code, err = m.runInitdCommand(ctx, string(name), "status")
if err != nil || code != 0 { err = m.runInitdCommand(ctx, string(name), "status")
if err != nil {
m.logger.DebugContext(ctx, "got error from init.d command", slogutil.KeyError, err)
// Treat an error or non-zero exit code as stopped status on Unix // Treat an error or non-zero exit code as stopped status on Unix
// System V. // System V.
// //
@@ -151,7 +155,7 @@ func (m *manager) install(ctx context.Context, action *ActionInstall) (err error
// On OpenWrt it is important to run enable after the service // On OpenWrt it is important to run enable after the service
// installation. Otherwise, the service won't start on the system // installation. Otherwise, the service won't start on the system
// startup. // startup.
_, err = m.runInitdCommand(ctx, string(action.ServiceName), "enable") err = m.runInitdCommand(ctx, string(action.ServiceName), "enable")
if err != nil { if err != nil {
return fmt.Errorf("enabling service on openwrt: %w", err) return fmt.Errorf("enabling service on openwrt: %w", err)
} }
@@ -174,7 +178,7 @@ func (m *manager) restart(ctx context.Context, action *ActionRestart) (err error
err = s.Restart() err = s.Restart()
if err != nil && m.isUnixSystemV { if err != nil && m.isUnixSystemV {
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "restart") initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "restart")
if initdErr != nil { if initdErr != nil {
return fmt.Errorf("%w (restarting via init.d: %w)", err, initdErr) return fmt.Errorf("%w (restarting via init.d: %w)", err, initdErr)
} }
@@ -201,7 +205,7 @@ func (m *manager) start(ctx context.Context, action *ActionStart) (err error) {
err = s.Start() err = s.Start()
if err != nil && m.isUnixSystemV { if err != nil && m.isUnixSystemV {
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "start") initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "start")
if initdErr != nil { if initdErr != nil {
return fmt.Errorf("%w (starting via init.d: %w)", err, initdErr) return fmt.Errorf("%w (starting via init.d: %w)", err, initdErr)
} }
@@ -225,7 +229,7 @@ func (m *manager) stop(ctx context.Context, action *ActionStop) (err error) {
err = s.Stop() err = s.Stop()
if err != nil && m.isUnixSystemV { if err != nil && m.isUnixSystemV {
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "stop") initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "stop")
if initdErr != nil { if initdErr != nil {
return fmt.Errorf("%w (stopping via init.d: %w)", err, initdErr) return fmt.Errorf("%w (stopping via init.d: %w)", err, initdErr)
} }
@@ -241,7 +245,7 @@ func (m *manager) uninstall(ctx context.Context, action *ActionUninstall) (err e
if m.isOpenWrt { if m.isOpenWrt {
// On OpenWrt it is important to run disable command first as it will // On OpenWrt it is important to run disable command first as it will
// remove the symlink. // remove the symlink.
_, err = m.runInitdCommand(ctx, string(action.ServiceName), "disable") err = m.runInitdCommand(ctx, string(action.ServiceName), "disable")
if err != nil { if err != nil {
return fmt.Errorf("disabling service on openwrt: %w", err) return fmt.Errorf("disabling service on openwrt: %w", err)
} }
@@ -299,22 +303,25 @@ func removeLaunchdStdLogs(ctx context.Context, logger *slog.Logger) {
} }
} }
// runInitdCommand runs init.d service command. It returns command code or // runInitdCommand runs init.d service command. Returns an error if any.
// error if any.
// //
// TODO(e.burkov): Move to manager_linux.go. // TODO(e.burkov): Move to manager_linux.go.
func (m *manager) runInitdCommand( func (m *manager) runInitdCommand(
ctx context.Context, ctx context.Context,
serviceName string, serviceName string,
action string, action string,
) (code int, err error) { ) (err error) {
confPath := filepath.Join("/etc", "init.d", serviceName) confPath := filepath.Join("/etc", "init.d", serviceName)
// Pass the script and action as a single string argument. // Pass the script and action as a single string argument.
// return executil.RunWithPeek(
// TODO(e.burkov): Use CommandConstructor. ctx,
code, _, err = aghos.RunCommand(ctx, m.cmdCons, "sh", "-c", confPath, action) m.cmdCons,
aghos.MaxCmdOutputSize,
return code, err "sh",
"-c",
confPath,
action,
)
} }
// emptyInterface is an empty implementation of the [service.Interface], as the // emptyInterface is an empty implementation of the [service.Interface], as the
@@ -0,0 +1,155 @@
package ossvc
import (
"fmt"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/osutil/executil"
"github.com/AdguardTeam/golibs/testutil"
"github.com/kardianos/service"
"github.com/stretchr/testify/assert"
)
func TestManager_Status(t *testing.T) {
const invalidSvcStatus = statusRestartOnFail + 1
svc := newTestSvc(t)
m := &manager{
logger: testLogger,
cmdCons: executil.EmptyCommandConstructor{},
isOpenWrt: aghos.IsOpenWrt(),
isUnixSystemV: false,
}
testCases := []struct {
onStatus func() (s service.Status, err error)
name string
wantErrMessage string
wantStatus Status
}{{
onStatus: func() (s service.Status, err error) {
return service.StatusUnknown, service.ErrNotInstalled
},
name: "not_installed",
wantStatus: StatusNotInstalled,
wantErrMessage: "",
}, {
onStatus: func() (s service.Status, err error) {
return service.StatusRunning, errors.Error("test")
},
name: "error",
wantStatus: "",
wantErrMessage: "getting service status: test",
}, {
onStatus: func() (s service.Status, err error) {
return service.StatusRunning, nil
},
name: "running",
wantStatus: StatusRunning,
wantErrMessage: "",
}, {
onStatus: func() (s service.Status, err error) {
return service.StatusStopped, nil
},
name: "stopped",
wantStatus: StatusStopped,
wantErrMessage: "",
}, {
onStatus: func() (s service.Status, err error) {
return statusRestartOnFail, nil
},
name: "restart_on_fail",
wantStatus: StatusRestartOnFail,
wantErrMessage: "",
}, {
onStatus: func() (s service.Status, err error) {
return invalidSvcStatus, nil
},
name: "invalid_status",
wantStatus: "",
wantErrMessage: fmt.Sprintf(
"service status: %v: %v",
errors.ErrBadEnumValue,
invalidSvcStatus,
),
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
svc.OnStatus = tc.onStatus
ctx := testutil.ContextWithTimeout(t, testTimeout)
status, err := m.Status(ctx, testServiceName)
assert.Equal(t, tc.wantStatus, status)
testutil.AssertErrorMsg(t, tc.wantErrMessage, err)
})
}
}
func TestManager_Status_unixSystemV(t *testing.T) {
svc := newTestSvc(t)
svc.OnStatus = func() (s service.Status, err error) {
return service.StatusUnknown, errors.Error("test")
}
m := &manager{
logger: testLogger,
cmdCons: executil.EmptyCommandConstructor{},
isOpenWrt: aghos.IsOpenWrt(),
isUnixSystemV: true,
}
testCases := []struct {
cmdCons executil.CommandConstructor
name string
wantStatus Status
}{{
cmdCons: newTestCmdConstructor(t, "", nil),
name: "running",
wantStatus: StatusRunning,
}, {
cmdCons: newTestCmdConstructor(t, "", errors.Error("test")),
name: "stopped",
wantStatus: StatusStopped,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
m.cmdCons = tc.cmdCons
ctx := testutil.ContextWithTimeout(t, testTimeout)
status, err := m.Status(ctx, testServiceName)
assert.NoError(t, err)
assert.Equal(t, tc.wantStatus, status)
})
}
}
// newTestSvc creates a new *testService with all methods set to panic, sets it
// in the chosen system, and returns it. The caller can then set the desired
// behavior of the service via overriding its methods.
func newTestSvc(tb testing.TB) (svc *testService) {
tb.Helper()
svc = &testService{
OnRun: func() (err error) { panic(testutil.UnexpectedCall()) },
OnStart: func() (err error) { panic(testutil.UnexpectedCall()) },
OnStop: func() (err error) { panic(testutil.UnexpectedCall()) },
OnRestart: func() (err error) { panic(testutil.UnexpectedCall()) },
OnInstall: func() (err error) { panic(testutil.UnexpectedCall()) },
OnUninstall: func() (err error) { panic(testutil.UnexpectedCall()) },
OnStatus: func() (s service.Status, err error) { panic(testutil.UnexpectedCall()) },
}
service.ChooseSystem(&testSystem{
OnNew: func(_ service.Interface, _ *service.Config) (s service.Service, err error) {
return svc, nil
},
})
return svc
}
-2
View File
@@ -10,8 +10,6 @@ import (
// Manager is the interface for communication with the OS service manager. // Manager is the interface for communication with the OS service manager.
// //
// TODO(e.burkov): Move to golibs. // TODO(e.burkov): Move to golibs.
//
// TODO(e.burkov): Use.
type Manager interface { type Manager interface {
// Perform performs the specified action. // Perform performs the specified action.
Perform(ctx context.Context, action Action) (err error) Perform(ctx context.Context, action Action) (err error)
+152
View File
@@ -0,0 +1,152 @@
package ossvc
import (
"context"
"io"
"testing"
"time"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil/executil"
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
"github.com/kardianos/service"
"github.com/stretchr/testify/require"
)
// testTimeout is the common timeout for tests.
const testTimeout = 1 * time.Second
// testServiceName is a common service name for tests.
const testServiceName = "AdGuardHome"
// testLogger is a common logger for tests.
var testLogger = slogutil.NewDiscardLogger()
// testSystem is a mock implementation of [service.System] for tests.
type testSystem struct {
OnNew func(_ service.Interface, _ *service.Config) (svc service.Service, err error)
}
// type check
var _ service.System = (*testSystem)(nil)
// New implements the [service.System] interface for *testSystem.
func (ts *testSystem) New(i service.Interface, c *service.Config) (svc service.Service, err error) {
return ts.OnNew(i, c)
}
// String implements the [service.System] interface for *testSystem.
func (ts *testSystem) String() (s string) {
return "testSystem"
}
// Detect implements the [service.System] interface for *testSystem.
func (ts *testSystem) Detect() (ok bool) {
return true
}
// Interactive implements the [service.System] interface for *testSystem.
func (ts *testSystem) Interactive() (ok bool) {
return true
}
// testService is a mock implementation of [service.Service] for tests.
type testService struct {
OnRun func() (err error)
OnStart func() (err error)
OnStop func() (err error)
OnRestart func() (err error)
OnInstall func() (err error)
OnUninstall func() (err error)
OnStatus func() (s service.Status, err error)
}
// type check
var _ service.Service = (*testService)(nil)
// Run implements the [service.Service] interface for *testService.
func (t *testService) Run() (err error) {
return t.OnRun()
}
// Start implements the [service.Service] interface for *testService.
func (t *testService) Start() (err error) {
return t.OnStart()
}
// Stop implements the [service.Service] interface for *testService.
func (t *testService) Stop() (err error) {
return t.OnStop()
}
// Restart implements the [service.Service] interface for *testService.
func (t *testService) Restart() (err error) {
return t.OnRestart()
}
// Install implements the [service.Service] interface for *testService.
func (t *testService) Install() (err error) {
return t.OnInstall()
}
// Uninstall implements the [service.Service] interface for *testService.
func (t *testService) Uninstall() (err error) {
return t.OnUninstall()
}
// Logger implements the [service.Service] interface for *testService.
func (t *testService) Logger(errs chan<- error) (l service.Logger, err error) {
return nil, nil
}
// SystemLogger implements the [service.Service] interface for *testService.
func (t *testService) SystemLogger(errs chan<- error) (l service.Logger, err error) {
return nil, nil
}
// String implements the [service.Service] interface for *testService.
func (t *testService) String() (s string) {
return testServiceName
}
// Platform implements the [service.Service] interface for *testService.
func (t *testService) Platform() (s string) {
return "testPlatform"
}
// Status implements the [service.Service] interface for *testService.
func (t *testService) Status() (s service.Status, err error) {
return t.OnStatus()
}
// newTestCmdConstructor is a helper that creates a new command constructor. The
// returned constructor creates [fakeexec.Command] instances that print the
// given body to the command's standard output and return the error.
func newTestCmdConstructor(
tb testing.TB,
body string,
returnErr error,
) (c executil.CommandConstructor) {
tb.Helper()
onNew := func(
_ context.Context,
conf *executil.CommandConfig,
) (c executil.Command, err error) {
cmd := fakeexec.NewCommand()
cmd.OnStart = func(_ context.Context) (err error) {
_, err = io.WriteString(conf.Stdout, body)
require.NoError(tb, err)
return returnErr
}
cmd.OnWait = func(_ context.Context) (err error) { return nil }
return cmd, nil
}
return &fakeexec.CommandConstructor{
OnNew: onNew,
}
}
+9 -7
View File
@@ -18,13 +18,14 @@ import (
"github.com/kardianos/service" "github.com/kardianos/service"
) )
// chooseSystem replaces the currently selected system with a wrapper. l must // chooseSystem replaces the currently selected system with a wrapper. l and
// not be nil. // cmdCons must not be nil.
func chooseSystem(_ context.Context, l *slog.Logger) { func chooseSystem(_ context.Context, l *slog.Logger, cmdCons executil.CommandConstructor) {
sys := service.ChosenSystem() sys := service.ChosenSystem()
service.ChooseSystem(&darwinSystem{ service.ChooseSystem(&darwinSystem{
System: sys, System: sys,
logger: l, cmdCons: cmdCons,
logger: l,
}) })
} }
@@ -32,7 +33,8 @@ func chooseSystem(_ context.Context, l *slog.Logger) {
// implementation of the [service.Service] interface. // implementation of the [service.Service] interface.
type darwinSystem struct { type darwinSystem struct {
service.System service.System
logger *slog.Logger cmdCons executil.CommandConstructor
logger *slog.Logger
} }
// type check // type check
@@ -51,7 +53,7 @@ func (d *darwinSystem) New(i service.Interface, c *service.Config) (s service.Se
return newDarwinService(&darwinServiceConfig{ return newDarwinService(&darwinServiceConfig{
svc: s, svc: s,
logger: d.logger, logger: d.logger,
cmdCons: executil.SystemCommandConstructor{}, cmdCons: d.cmdCons,
name: c.Name, name: c.Name,
plistDir: "/Library/LaunchDaemons", plistDir: "/Library/LaunchDaemons",
}), nil }), nil
+24 -51
View File
@@ -3,70 +3,23 @@
package ossvc package ossvc
import ( import (
"context"
"io"
"os" "os"
"path" "path"
"testing" "testing"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil/executil" "github.com/AdguardTeam/golibs/osutil/executil"
"github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
"github.com/kardianos/service" "github.com/kardianos/service"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
// newTestCmdConstructor is a helper that creates a new command constructor. The
// returned constructor creates [fakeexec.Command] instances that print the
// given body to the command's standard output and return the error.
func newTestCmdConstructor(
tb testing.TB,
body string,
returnErr error,
) (c executil.CommandConstructor) {
tb.Helper()
onNew := func(
_ context.Context,
conf *executil.CommandConfig,
) (c executil.Command, err error) {
cmd := fakeexec.NewCommand()
cmd.OnStart = func(_ context.Context) (err error) {
_, err = io.WriteString(conf.Stdout, body)
require.NoError(tb, err)
return returnErr
}
cmd.OnWait = func(_ context.Context) (err error) { return nil }
return cmd, nil
}
return &fakeexec.CommandConstructor{
OnNew: onNew,
}
}
func TestDarwinService_Status(t *testing.T) { func TestDarwinService_Status(t *testing.T) {
name := "AdGuardHome" t.Parallel()
plistDir := t.TempDir() plistDir := t.TempDir()
svc := newDarwinService(&darwinServiceConfig{ plistPath := path.Join(plistDir, testServiceName+".plist")
logger: slogutil.NewDiscardLogger(),
plistDir: plistDir,
name: name,
})
t.Run("not_installed", func(t *testing.T) {
status, err := svc.Status()
assert.Equal(t, service.StatusUnknown, status)
assert.ErrorIs(t, err, service.ErrNotInstalled)
})
plistPath := path.Join(plistDir, name+".plist")
file, err := os.Create(plistPath) file, err := os.Create(plistPath)
require.NoError(t, err) require.NoError(t, err)
@@ -102,7 +55,13 @@ func TestDarwinService_Status(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
svc.cmdCons = newTestCmdConstructor(t, tc.body, tc.cmdErr) svc := newDarwinService(&darwinServiceConfig{
logger: testLogger,
cmdCons: newTestCmdConstructor(t, tc.body, tc.cmdErr),
plistDir: plistDir,
name: testServiceName,
})
var status service.Status var status service.Status
status, err = svc.Status() status, err = svc.Status()
require.NoError(t, err) require.NoError(t, err)
@@ -111,3 +70,17 @@ func TestDarwinService_Status(t *testing.T) {
}) })
} }
} }
func TestDarwinService_Status_notInstalled(t *testing.T) {
t.Parallel()
svc := newDarwinService(&darwinServiceConfig{
logger: testLogger,
cmdCons: executil.EmptyCommandConstructor{},
name: testServiceName,
})
status, err := svc.Status()
assert.Equal(t, service.StatusUnknown, status)
assert.ErrorIs(t, err, service.ErrNotInstalled)
}
+28 -14
View File
@@ -17,8 +17,8 @@ import (
) )
// chooseSystem checks the current system detected and substitutes it with local // chooseSystem checks the current system detected and substitutes it with local
// implementation if needed. l must not be nil. // implementation if needed. l and cmdCons must not be nil.
func chooseSystem(ctx context.Context, l *slog.Logger) { func chooseSystem(ctx context.Context, l *slog.Logger, cmdCons executil.CommandConstructor) {
sys := service.ChosenSystem() sys := service.ChosenSystem()
switch sys.String() { switch sys.String() {
case "unix-systemv": case "unix-systemv":
@@ -29,13 +29,13 @@ func chooseSystem(ctx context.Context, l *slog.Logger) {
// See https://github.com/AdguardTeam/AdGuardHome/issues/4480 and // See https://github.com/AdguardTeam/AdGuardHome/issues/4480 and
// https://github.com/AdguardTeam/AdGuardHome/issues/4677. // https://github.com/AdguardTeam/AdGuardHome/issues/4677.
if !aghos.IsOpenWrt() { if !aghos.IsOpenWrt() {
service.ChooseSystem(&sysvSystem{System: sys}) service.ChooseSystem(&sysvSystem{System: sys, cmdCons: cmdCons})
l.DebugContext(ctx, "using custom SysV system") l.DebugContext(ctx, "using custom SysV system")
return return
} }
case "linux-systemd": case "linux-systemd":
service.ChooseSystem(&systemdSystem{System: sys}) service.ChooseSystem(&systemdSystem{System: sys, cmdCons: cmdCons})
l.DebugContext(ctx, "using custom systemd system") l.DebugContext(ctx, "using custom systemd system")
return return
@@ -51,6 +51,9 @@ func chooseSystem(ctx context.Context, l *slog.Logger) {
type sysvSystem struct { type sysvSystem struct {
// System must have an unexported type *service.linuxSystemService. // System must have an unexported type *service.linuxSystemService.
service.System service.System
// cmdCons is used to run external commands. It must not be nil.
cmdCons executil.CommandConstructor
} }
// type check // type check
@@ -67,7 +70,7 @@ func (sys *sysvSystem) New(i service.Interface, c *service.Config) (s service.Se
} }
return &sysvService{ return &sysvService{
cmdCons: executil.SystemCommandConstructor{}, cmdCons: sys.cmdCons,
Service: s, Service: s,
name: c.Name, name: c.Name,
}, nil }, nil
@@ -99,10 +102,14 @@ func (svc *sysvService) Install() (err error) {
} }
// TODO(s.chzhen): Pass context. // TODO(s.chzhen): Pass context.
_, _, err = aghos.RunCommand(context.TODO(), svc.cmdCons, "update-rc.d", svc.name, "defaults") return executil.RunWithPeek(
context.TODO(),
// Don't wrap an error since it's informative enough as is. svc.cmdCons,
return err aghos.MaxCmdOutputSize,
"update-rc.d",
svc.name,
"defaults",
)
} }
// Uninstall implements the [service.Service] interface for *sysvService. // Uninstall implements the [service.Service] interface for *sysvService.
@@ -115,10 +122,14 @@ func (svc *sysvService) Uninstall() (err error) {
} }
// TODO(s.chzhen): Pass context. // TODO(s.chzhen): Pass context.
_, _, err = aghos.RunCommand(context.TODO(), svc.cmdCons, "update-rc.d", svc.name, "remove") return executil.RunWithPeek(
context.TODO(),
// Don't wrap an error since it's informative enough as is. svc.cmdCons,
return err aghos.MaxCmdOutputSize,
"update-rc.d",
svc.name,
"remove",
)
} }
// systemdSystem is a wrapper for a [service.System] that returns the custom // systemdSystem is a wrapper for a [service.System] that returns the custom
@@ -126,6 +137,9 @@ func (svc *sysvService) Uninstall() (err error) {
type systemdSystem struct { type systemdSystem struct {
// System must have an unexported type *service.linuxSystemService. // System must have an unexported type *service.linuxSystemService.
service.System service.System
// cmdCons is used to run external commands. It must not be nil.
cmdCons executil.CommandConstructor
} }
// type check // type check
@@ -142,7 +156,7 @@ func (sys *systemdSystem) New(i service.Interface, c *service.Config) (s service
} }
return &systemdService{ return &systemdService{
cmdCons: executil.SystemCommandConstructor{}, cmdCons: sys.cmdCons,
Service: s, Service: s,
unitName: fmt.Sprintf("%s.service", c.Name), unitName: fmt.Sprintf("%s.service", c.Name),
}, nil }, nil
+38 -28
View File
@@ -3,6 +3,7 @@
package ossvc package ossvc
import ( import (
"bytes"
"cmp" "cmp"
"context" "context"
"fmt" "fmt"
@@ -16,6 +17,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/osutil/executil" "github.com/AdguardTeam/golibs/osutil/executil"
"github.com/kardianos/service" "github.com/kardianos/service"
@@ -34,33 +36,37 @@ import (
const sysVersion = "openbsd-runcom" const sysVersion = "openbsd-runcom"
// chooseSystem checks the current system detected and substitutes it with local // chooseSystem checks the current system detected and substitutes it with local
// implementation if needed. // implementation if needed. cmdCons must not be nil.
func chooseSystem(_ context.Context, _ *slog.Logger) { func chooseSystem(_ context.Context, _ *slog.Logger, cmdCons executil.CommandConstructor) {
service.ChooseSystem(openbsdSystem{}) service.ChooseSystem(&openbsdSystem{
cmdCons: cmdCons,
})
} }
// openbsdSystem is the service.System to be used on the OpenBSD. // openbsdSystem is the service.System to be used on the OpenBSD.
type openbsdSystem struct{} type openbsdSystem struct {
cmdCons executil.CommandConstructor
}
// String implements service.System interface for openbsdSystem. // String implements service.System interface for openbsdSystem.
func (openbsdSystem) String() string { func (sys *openbsdSystem) String() string {
return sysVersion return sysVersion
} }
// Detect implements service.System interface for openbsdSystem. // Detect implements service.System interface for openbsdSystem.
func (openbsdSystem) Detect() (ok bool) { func (sys *openbsdSystem) Detect() (ok bool) {
return true return true
} }
// Interactive implements service.System interface for openbsdSystem. // Interactive implements service.System interface for openbsdSystem.
func (openbsdSystem) Interactive() (ok bool) { func (sys *openbsdSystem) Interactive() (ok bool) {
return os.Getppid() != 1 return os.Getppid() != 1
} }
// New implements service.System interface for openbsdSystem. // New implements service.System interface for openbsdSystem.
func (openbsdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) { func (sys *openbsdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) {
return &openbsdRunComService{ return &openbsdRunComService{
cmdCons: executil.SystemCommandConstructor{}, cmdCons: sys.cmdCons,
i: i, i: i,
cfg: c, cfg: c,
}, nil }, nil
@@ -216,16 +222,14 @@ func (s *openbsdRunComService) configureSysStartup(enable bool) (err error) {
} }
// TODO(s.chzhen): Pass context. // TODO(s.chzhen): Pass context.
ctx := context.TODO() return executil.RunWithPeek(
var code int context.TODO(),
code, _, err = aghos.RunCommand(ctx, s.cmdCons, "rcctl", cmd, s.cfg.Name) s.cmdCons,
if err != nil { aghos.MaxCmdOutputSize,
return err "rcctl",
} else if code != 0 { cmd,
return fmt.Errorf("rcctl finished with code %d", code) s.cfg.Name,
} )
return nil
} }
// writeScript tries to write the script for the service. // writeScript tries to write the script for the service.
@@ -319,19 +323,25 @@ func (s *openbsdRunComService) runCom(cmd string) (out string, err error) {
return "", err return "", err
} }
// TODO(s.chzhen): Pass context. stdoutBuf := bytes.Buffer{}
ctx := context.TODO() stderrBuf := bytes.Buffer{}
// TODO(e.burkov): It's possible that os.ErrNotExist is caused by // TODO(s.chzhen): Pass context.
// something different than the service script's non-existence. Keep it err = executil.Run(context.TODO(), s.cmdCons, &executil.CommandConfig{
// in mind, when replace the aghos.RunCommand. Stderr: &stderrBuf,
var outData []byte Stdout: ioutil.NewTruncatedWriter(&stdoutBuf, aghos.MaxCmdOutputSize),
_, outData, err = aghos.RunCommand(ctx, s.cmdCons, scriptPath, cmd) Path: scriptPath,
if errors.Is(err, os.ErrNotExist) { Args: []string{cmd},
})
switch {
case errors.Is(err, os.ErrNotExist):
return "", service.ErrNotInstalled return "", service.ErrNotInstalled
case err != nil:
return stderrBuf.String(), err
} }
return string(outData), err return stdoutBuf.String(), nil
} }
// Status implements service.Service interface for *openbsdRunComService. // Status implements service.Service interface for *openbsdRunComService.
+3 -1
View File
@@ -5,8 +5,10 @@ package ossvc
import ( import (
"context" "context"
"log/slog" "log/slog"
"github.com/AdguardTeam/golibs/osutil/executil"
) )
// chooseSystem checks the current system detected and substitutes it with local // chooseSystem checks the current system detected and substitutes it with local
// implementation if needed. // implementation if needed.
func chooseSystem(_ context.Context, _ *slog.Logger) {} func chooseSystem(_ context.Context, _ *slog.Logger, _ executil.CommandConstructor) {}
+8 -16
View File
@@ -315,16 +315,10 @@ func autoAdd(ctx context.Context, l *slog.Logger, basePath string) (err error) {
err = handleAdds(ctx, l, cmdCons, adds) err = handleAdds(ctx, l, cmdCons, adds)
if err != nil { if err != nil {
// Don't wrap the error since it's informative enough as is. // Don't wrap the error since it's informative enough as is.
return nil return err
} }
err = handleDels(ctx, l, cmdCons, dels) return handleDels(ctx, l, cmdCons, dels)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil
}
return nil
} }
// gitCmd is the shell command for Git. // gitCmd is the shell command for Git.
@@ -344,10 +338,9 @@ func handleAdds(
gitArgs := append([]string{"add"}, locales...) gitArgs := append([]string{"add"}, locales...)
l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs) l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs)
code, out, err := aghos.RunCommand(ctx, cmdCons, gitCmd, gitArgs...) err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, gitCmd, gitArgs...)
if err != nil {
if err != nil || code != 0 { return fmt.Errorf("git add failed: %w", err)
return fmt.Errorf("git add exited with code %d output %q: %w", code, out, err)
} }
return nil return nil
@@ -367,10 +360,9 @@ func handleDels(
gitArgs := append([]string{"restore"}, locales...) gitArgs := append([]string{"restore"}, locales...)
l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs) l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs)
code, out, err := aghos.RunCommand(ctx, cmdCons, gitCmd, gitArgs...) err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, gitCmd, gitArgs...)
if err != nil {
if err != nil || code != 0 { return fmt.Errorf("git restore failed: %w", err)
return fmt.Errorf("git restore exited with code %d output %q: %w", code, out, err)
} }
return nil return nil