-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecutor.go
More file actions
322 lines (270 loc) · 9.29 KB
/
executor.go
File metadata and controls
322 lines (270 loc) · 9.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package executor
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/gnodet/mvx/pkg/config"
"github.com/gnodet/mvx/pkg/shell"
"github.com/gnodet/mvx/pkg/tools"
"github.com/gnodet/mvx/pkg/util"
)
// Executor handles command execution with proper environment setup
type Executor struct {
config *config.Config
toolManager *tools.Manager
projectRoot string
}
// NewExecutor creates a new command executor
func NewExecutor(cfg *config.Config, toolManager *tools.Manager, projectRoot string) *Executor {
return &Executor{
config: cfg,
toolManager: toolManager,
projectRoot: projectRoot,
}
}
// ExecuteCommand executes a configured command with arguments
func (e *Executor) ExecuteCommand(commandName string, args []string) error {
// Get command configuration
cmdConfig, exists := e.config.Commands[commandName]
if !exists {
return fmt.Errorf("unknown command: %s", commandName)
}
// Setup environment
env, err := e.setupEnvironment(cmdConfig)
if err != nil {
return fmt.Errorf("failed to setup environment: %w", err)
}
// Determine working directory
workDir := e.projectRoot
if cmdConfig.WorkingDir != "" {
workDir = filepath.Join(e.projectRoot, cmdConfig.WorkingDir)
}
// Process script and resolve interpreter (handle platform-specific scripts)
script, interpreter, err := config.ResolvePlatformScriptWithInterpreter(cmdConfig.Script, cmdConfig.Interpreter)
if err != nil {
return fmt.Errorf("failed to resolve script: %w", err)
}
// Process script arguments
processedScript := e.processScriptString(script, args)
// Execute command
fmt.Printf("🔨 Running command: %s\n", commandName)
if cmdConfig.Description != "" {
fmt.Printf(" %s\n", cmdConfig.Description)
}
return e.executeScriptWithInterpreter(processedScript, workDir, env, interpreter)
}
// ExecuteTool executes a tool command with mvx-managed environment
func (e *Executor) ExecuteTool(toolName string, args []string) error {
// Check if the tool is configured
toolConfig, exists := e.config.Tools[toolName]
if !exists {
return fmt.Errorf("tool %s is not configured in this project", toolName)
}
// EnsureTool handles everything: resolve, check, install, get path
toolBinPath, err := e.toolManager.EnsureTool(toolName, toolConfig)
if err != nil {
return fmt.Errorf("failed to ensure %s is installed: %w", toolName, err)
}
// Setup environment with tool paths
env, err := e.setupToolEnvironment(toolName, toolBinPath)
if err != nil {
return fmt.Errorf("failed to setup environment for %s: %w", toolName, err)
}
// Execute the tool
toolExecutable := toolName
if len(args) == 0 {
args = []string{"--version"} // Default to showing version if no args
}
// Create and execute command
cmd := exec.Command(toolExecutable, args...)
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Dir = e.projectRoot
return cmd.Run()
}
// ListCommands returns available commands from configuration
func (e *Executor) ListCommands() map[string]string {
commands := make(map[string]string)
for name, cmd := range e.config.Commands {
commands[name] = cmd.Description
}
return commands
}
// GetCommandInfo returns detailed information about a command
func (e *Executor) GetCommandInfo(commandName string) (*config.CommandConfig, error) {
cmdConfig, exists := e.config.Commands[commandName]
if !exists {
return nil, fmt.Errorf("unknown command: %s", commandName)
}
return &cmdConfig, nil
}
// setupEnvironment prepares the environment for command execution
func (e *Executor) setupEnvironment(cmdConfig config.CommandConfig) ([]string, error) {
// Create environment map starting with current environment
envVars := make(map[string]string)
for _, envVar := range os.Environ() {
parts := strings.SplitN(envVar, "=", 2)
if len(parts) == 2 {
envVars[parts[0]] = parts[1]
}
}
// Add global environment variables from config (these override system ones)
globalEnv, err := e.toolManager.SetupEnvironment(e.config)
if err != nil {
return nil, err
}
for key, value := range globalEnv {
envVars[key] = value
}
// Add command-specific environment variables (these override global ones)
for key, value := range cmdConfig.Environment {
envVars[key] = value
}
// Add tool paths to PATH
pathDirs := []string{}
// Get required tools for this command
requiredTools := cmdConfig.Requires
if len(requiredTools) == 0 {
// If no specific requirements, use all configured tools
for toolName := range e.config.Tools {
requiredTools = append(requiredTools, toolName)
}
}
util.LogVerbose("Required tools for command: %v", requiredTools)
// Add tool bin directories to PATH
for _, toolName := range requiredTools {
if toolConfig, exists := e.config.Tools[toolName]; exists {
// EnsureTool handles version resolution, installation check, auto-install, and path retrieval
binPath, err := e.toolManager.EnsureTool(toolName, toolConfig)
if err != nil {
util.LogVerbose("Skipping tool %s: %v", toolName, err)
continue
}
util.LogVerbose("Adding %s bin path to PATH: %s", toolName, binPath)
pathDirs = append(pathDirs, binPath)
}
}
// Prepend tool paths to existing PATH
if len(pathDirs) > 0 {
currentPath := envVars["PATH"]
newPath := strings.Join(pathDirs, string(os.PathListSeparator))
if currentPath != "" {
newPath = newPath + string(os.PathListSeparator) + currentPath
}
envVars["PATH"] = newPath
util.LogVerbose("Updated PATH with %d tool directories: %s", len(pathDirs), newPath)
} else {
util.LogVerbose("No tool directories added to PATH")
}
// Convert environment map back to slice format
var env []string
for key, value := range envVars {
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
return env, nil
}
// processScriptString processes a script string with arguments
func (e *Executor) processScriptString(script string, args []string) string {
// If there are arguments, append them to the script
if len(args) > 0 {
// Join arguments with spaces and append to script
argsStr := strings.Join(args, " ")
script = script + " " + argsStr
}
return script
}
// executeScriptWithInterpreter executes a script using the specified interpreter
func (e *Executor) executeScriptWithInterpreter(script, workDir string, env []string, interpreter string) error {
util.LogVerbose("executeScriptWithInterpreter called with interpreter: '%s', script: '%s'", interpreter, script)
// Default to native interpreter if not specified
if interpreter == "" || interpreter == "native" {
util.LogVerbose("Using native interpreter")
return e.executeNativeScript(script, workDir, env)
}
// Use mvx-shell interpreter
if interpreter == "mvx-shell" {
mvxShell := shell.NewMVXShell(workDir, env)
return mvxShell.Execute(script)
}
return fmt.Errorf("unknown interpreter: %s", interpreter)
}
// executeNativeScript executes a script using the native system shell
func (e *Executor) executeNativeScript(script, workDir string, env []string) error {
// Determine shell
shell := "/bin/bash"
shellArgs := []string{"-c"}
if runtime.GOOS == "windows" {
shell = "cmd"
shellArgs = []string{"/c"}
}
util.LogVerbose("Executing native script: %s", script)
util.LogVerbose("Working directory: %s", workDir)
util.LogVerbose("Environment variables count: %d", len(env))
// Log PATH specifically
for _, envVar := range env {
if strings.HasPrefix(envVar, "PATH=") {
util.LogVerbose("PATH in environment: %s", envVar)
break
}
}
// Create command
cmd := exec.Command(shell, append(shellArgs, script)...)
cmd.Dir = workDir
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// Execute command
return cmd.Run()
}
// ValidateCommand is deprecated - tools are now auto-installed via EnsureTool
// This method is kept for backward compatibility but does nothing
func (e *Executor) ValidateCommand(commandName string) error {
// Just check if command exists
_, exists := e.config.Commands[commandName]
if !exists {
return fmt.Errorf("unknown command: %s", commandName)
}
// Note: Tool installation checks removed - EnsureTool handles automatic installation
return nil
}
// setupToolEnvironment prepares the environment for tool execution
func (e *Executor) setupToolEnvironment(toolName, toolBinPath string) ([]string, error) {
// Create environment map starting with current environment
envVars := make(map[string]string)
for _, envVar := range os.Environ() {
parts := strings.SplitN(envVar, "=", 2)
if len(parts) == 2 {
envVars[parts[0]] = parts[1]
}
}
// Add global environment variables from config
globalEnv, err := e.toolManager.SetupEnvironment(e.config)
if err != nil {
return nil, err
}
for key, value := range globalEnv {
envVars[key] = value
}
// Add tool binary directory to PATH
pathDirs := []string{toolBinPath}
// Add existing PATH
if existingPath, exists := envVars["PATH"]; exists {
pathDirs = append(pathDirs, existingPath)
}
// Set PATH with tool directory first
envVars["PATH"] = strings.Join(pathDirs, string(os.PathListSeparator))
// Tool-specific environment variables are already set by SetupEnvironment above
// which calls each tool's EnvironmentProvider.SetupEnvironment() method
// Convert map back to slice
env := make([]string, 0, len(envVars))
for key, value := range envVars {
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
return env, nil
}