-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Commit a simple CLI example for editing
- Loading branch information
Showing
1 changed file
with
54 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |