Skip to content

Commit

Permalink
Add docs for run funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
briancain committed Nov 27, 2023
1 parent fdf6e92 commit f9d1512
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 30 deletions.
38 changes: 9 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,43 +15,23 @@ default if no env var is found, it will use `vim` to edit the requested file.

This repo is meant to be used as a package for other Golang CLI projects.

The example below is a shortened version of `main.go`:
It has two main functions you can use as a CLI author for editing files:

```golang
// Read the original contents of the file
contents, err := os.ReadFile(filePathToEdit)
if err != nil {
fmt.Println("File reading error: ", err)
os.Exit(1)
}
* Run(originalContent []byte, originalFilePath string)
+ `originalContent` is the content of the text to edit in bytes
+ `originalFilePath` is where the file originated, can be empty if remote. Used to determine the file ext for the tmp file.
* RunLocal(originalFilePath string)
+ `originalFilePath` is where the file originated, can be empty if remote. Used to determine the file ext for the tmp file.

The example below is a shortened version of `main.go` using the Run version:

```golang
// Run the editor to let the user edit the contents in a tmp file
edited, _, err := Run(contents, filePathToEdit)
if err != nil {
fmt.Println("File editing error: ", err)
os.Exit(1)
}

// You could also send this edited content back to a server to update it.

// If changes, overwrite the original existing file
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)
```

### Examples
Expand Down
3 changes: 2 additions & 1 deletion editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ func setupDefaultEditorArgs() ([]string, error) {

// RunLocal is like Run, but assumes the file to edit is locally saved on
// disk rather than some remote content
func RunLocal(o []byte, of string) error {
func RunLocal(of string) error {
contents, err := os.ReadFile(of)
if err != nil {
return err
}

// Call run on the local file, given its contents
edited, _, err := Run(contents, of)
if err != nil {
return err
Expand Down

0 comments on commit f9d1512

Please sign in to comment.