github.com/BarDweller/libpak@v0.0.0-20230630201634-8dd5cfc15ec9/effect/executor.go (about) 1 /* 2 * Copyright 2018-2020 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package effect 18 19 import ( 20 "io" 21 "os/exec" 22 ) 23 24 // Execution is information about a command to run. 25 type Execution struct { 26 27 // Command is the command to run. 28 Command string 29 30 // Args is the arguments to the command. 31 Args []string 32 33 // Dir is the working directory the command is run in. Defaults to the current working directory. 34 Dir string 35 36 // Environment is the environment variables that the command is run with. Defaults to current environment. 37 Env []string 38 39 // Stdin is the Reader to use for stdin. 40 Stdin io.Reader 41 42 // Stdout is the Writer to use for stdout. 43 Stdout io.Writer 44 45 // Stderr is the Writer to use for stderr. 46 Stderr io.Writer 47 } 48 49 //go:generate mockery -name Executor -case=underscore 50 51 // Executor is the interface for types that can execute an Execution. 52 type Executor interface { 53 54 // Execute executes the command described in the Execution. 55 Execute(execution Execution) error 56 } 57 58 // CommandExecutor is an implementation of Executor that uses exec.Command and runs the command without a TTY. 59 type CommandExecutor struct{} 60 61 func (CommandExecutor) Execute(execution Execution) error { 62 cmd := exec.Command(execution.Command, execution.Args...) 63 64 if execution.Dir != "" { 65 cmd.Dir = execution.Dir 66 } 67 68 if len(execution.Env) > 0 { 69 cmd.Env = execution.Env 70 } 71 72 cmd.Stdin = execution.Stdin 73 cmd.Stdout = execution.Stdout 74 cmd.Stderr = execution.Stderr 75 76 return cmd.Run() 77 }