github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/utils/cmdutil/command.go (about) 1 /* 2 * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package cmdutil 19 20 import ( 21 "os/exec" 22 "strings" 23 24 "github.com/pkg/errors" 25 "github.com/rs/zerolog/log" 26 ) 27 28 // Duplicate logic in function bodies is intentional. 29 // This is to keep frame count the same (can't call one from the other), so that the caller may be logged. 30 31 // SudoExec executes external command with sudo privileges and logs output on the debug level. 32 // It returns a combined stderr and stdout output and exit code in case of an error. 33 func SudoExec(args ...string) error { 34 out, err := exec.Command("sudo", args...).CombinedOutput() 35 logSkipFrame := log.With().CallerWithSkipFrameCount(3).Logger() 36 (&logSkipFrame).Debug().Msgf("%q output:\n%s", strings.Join(args, " "), out) 37 return errors.Wrapf(err, "%q: %v output: %s", strings.Join(args, " "), err, out) 38 } 39 40 // Exec executes external command and logs output on the debug level. 41 // It returns a combined stderr and stdout output and exit code in case of an error. 42 func Exec(args ...string) error { 43 out, err := exec.Command(args[0], args[1:]...).CombinedOutput() 44 logSkipFrame := log.With().CallerWithSkipFrameCount(3).Logger() 45 (&logSkipFrame).Debug().Msgf("%q output:\n%s", strings.Join(args, " "), out) 46 return errors.Wrapf(err, "%q: %v output: %s", strings.Join(args, " "), err, out) 47 } 48 49 // ExecOutput executes external command and logs output on the debug level. 50 // It returns a combined stderr and stdout output and exit code in case of an error. 51 func ExecOutput(args ...string) (output string, err error) { 52 out, err := exec.Command(args[0], args[1:]...).CombinedOutput() 53 logSkipFrame := log.With().CallerWithSkipFrameCount(3).Logger() 54 (&logSkipFrame).Debug().Msgf("%q output:\n%s", strings.Join(args, " "), out) 55 if err != nil { 56 return string(out), errors.Errorf("%q: %v output: %s", strings.Join(args, " "), err, out) 57 } 58 return string(out), nil 59 }