-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
70 lines (59 loc) · 1.65 KB
/
exec.go
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
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"context"
"fmt"
"os"
"os/exec"
"github.com/google/generative-ai-go/genai"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
// execCmd represents the exec command
var execCmd = &cobra.Command{
Use: "exec",
Short: "Execute a shell command",
Long: `Execute a shell command and display the output.
If an error occurs during command execution, it will be analyzed using the Gemini API
to provide additional insights and suggestions for troubleshooting.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
shellCmd := exec.Command(args[0], args[1:]...)
output, cmdErr := shellCmd.CombinedOutput()
if cmdErr != nil {
fmt.Println("Error executing command: ", cmdErr)
// Analyze the error with the Gemini API
client, err := genai.NewClient(cmd.Context(), option.WithAPIKey(viper.GetString("gemini.api-key")))
if err != nil {
fmt.Println("Error creating client: ", err)
os.Exit(1)
}
defer client.Close()
model := client.GenerativeModel("gemini-pro")
iter := model.GenerateContentStream(context.Background(), genai.Text(cmdErr.Error()))
fmt.Println("\nGemini analysis of the error:\n")
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
fmt.Print("Error getting response: ", err)
break
}
for _, part := range resp.Candidates[0].Content.Parts {
fmt.Println(part)
}
}
return
}
fmt.Println("Command output: ", string(output))
},
}
func init() {
rootCmd.AddCommand(execCmd)
}