-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
65 lines (54 loc) · 1.54 KB
/
main.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
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
// This function shows an example of how you would use this package
var rootCmd = &cobra.Command{
Use: "edit-cli",
Short: "A test CLI to showcase the editor package",
Run: func(cmd *cobra.Command, args []string) {
contents, err := os.ReadFile(filePathToEdit)
if err != nil {
fmt.Println("File reading error: ", err)
os.Exit(1)
}
// Run the editor to get the edited contents
edited, _, err := Run(contents, filePathToEdit)
if err != nil {
fmt.Println("File editing error: ", err)
os.Exit(1)
}
// TODO(briancain): This is where you can run your parsers and validators
// on the edited text so you can show any parse or lint errors prior to
// saving the file
// If changes, overwrite the existing file
// Open the file for writing, creating it if it doesn't exist
file, err := os.OpenFile(filePathToEdit, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
fmt.Println("Failed to open original file to update: ", err)
os.Exit(1)
}
defer file.Close()
// Write the content to the file
estr := string(edited)
_, err = file.WriteString(estr)
if err != nil {
fmt.Println("Failed to write content to file: ", err)
os.Exit(1)
}
fmt.Println(fmt.Sprintf("Successfully updated %q!", filePathToEdit))
os.Exit(0)
},
}
var filePathToEdit string
func init() {
rootCmd.PersistentFlags().StringVar(&filePathToEdit, "file", "", "the file to edit")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}