Skip to content

Commit

Permalink
Commit a simple CLI example for editing
Browse files Browse the repository at this point in the history
  • Loading branch information
briancain committed Nov 27, 2023
1 parent 87eab7d commit 30c1ab0
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,61 @@
package main

import "fmt"
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
edited, _, err := Run(contents, filePathToEdit)
if err != nil {
fmt.Println("File editing error: ", err)
os.Exit(1)
}

// 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() {
fmt.Println("Hello, world.")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

0 comments on commit 30c1ab0

Please sign in to comment.