Skip to content

Commit

Permalink
Merge pull request #322 from csessh/feat-syspath
Browse files Browse the repository at this point in the history
Support relative path for snippet's filename attribute
  • Loading branch information
RamiAwar authored Nov 28, 2024
2 parents e68366c + 204a548 commit 3d34c13
Show file tree
Hide file tree
Showing 19 changed files with 395 additions and 86 deletions.
6 changes: 5 additions & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ on:
jobs:
test:
name: Test
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v4.1.1

Expand All @@ -22,3 +25,4 @@ jobs:

- name: Run unit tests
run: make test
shell: bash # Use bash shell for both Ubuntu and Windows (Git Bash is used on Windows)
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ All `toml` files will be scraped and found snippets will be added.

Example1: single directory

```toml
[GHEGist]
base_url = "" # GHE base URL
upload_url = "" # GHE upload URL (often the same as the base URL)
Expand All @@ -275,6 +276,7 @@ Example1: single directory
gist_id = "" # Gist ID
public = false # public or priate
auto_sync = false # sync automatically when editing snippets
```

```
$ pet configure
Expand Down
7 changes: 6 additions & 1 deletion cmd/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
"github.com/spf13/cobra"
)

Expand All @@ -15,7 +16,11 @@ var configureCmd = &cobra.Command{

func configure(cmd *cobra.Command, args []string) (err error) {
editor := config.Conf.General.Editor
return editFile(editor, configFile, 0)
configFilePath, err := path.NewAbsolutePath(configFile)
if err != nil {
return err
}
return editFile(editor, configFilePath, 0)
}

func init() {
Expand Down
31 changes: 16 additions & 15 deletions cmd/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"

"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
petSync "github.com/knqyf263/pet/sync"
"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand All @@ -22,7 +23,10 @@ var editCmd = &cobra.Command{
func edit(cmd *cobra.Command, args []string) (err error) {
flag := config.Flag
editor := config.Conf.General.Editor
snippetFile := config.Conf.General.SnippetFile
snippetFilePath, err := path.NewAbsolutePath(config.Conf.General.SnippetFile)
if err != nil {
return err
}

var options []string
if flag.Query != "" {
Expand All @@ -32,39 +36,36 @@ func edit(cmd *cobra.Command, args []string) (err error) {
// If we have multiple snippet directories, we need to find the right
// snippet file to edit - so we need to prompt the user to select a snippet first
if len(config.Conf.General.SnippetDirs) > 0 {
snippetFile, err = selectFile(options, flag.FilterTag)
snippetFilePath, err = selectFile(options, flag.FilterTag)
if err != nil {
return err
}
}

if snippetFile == "" {
return errors.New("No sippet file seleted")
if snippetFilePath.Get() == "" {
return errors.New("No snippet file seleted")
}

// file content before editing
contentBefore := fileContent(snippetFile)
err = editFile(editor, snippetFile, 0)
// only sync if content has changed
contentBefore := fileContent(snippetFilePath)
err = editFile(editor, snippetFilePath, 0)
if err != nil {
return
return err
}
contentAfter := fileContent(snippetFile)

// no need to try to sync if same file content
contentAfter := fileContent(snippetFilePath)
if contentBefore == contentAfter {
return nil
}

// sync snippet file
if config.Conf.Gist.AutoSync {
return petSync.AutoSync(snippetFile)
return petSync.AutoSync(snippetFilePath)
}

return nil
}

func fileContent(fname string) string {
data, _ := os.ReadFile(fname)
func fileContent(filePath path.AbsolutePath) string {
data, _ := os.ReadFile(filePath.Get())
return string(data)
}

Expand Down
30 changes: 25 additions & 5 deletions cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/chzyer/readline"
"github.com/fatih/color"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
"github.com/knqyf263/pet/snippet"
petSync "github.com/knqyf263/pet/sync"
"github.com/spf13/cobra"
Expand All @@ -34,6 +35,7 @@ func scan(prompt string, out io.Writer, in io.ReadCloser, allowEmpty bool) (stri
if err != nil {
return "", err
}

defer os.Remove(f.Name()) // clean up temp file
tempFile := f.Name()

Expand Down Expand Up @@ -89,6 +91,7 @@ func scanMultiLine(prompt string, secondMessage string, out io.Writer, in io.Rea
tempDir := os.Getenv("TEMP")
tempFile = filepath.Join(tempDir, "pet.tmp")
}

l, err := readline.NewEx(&readline.Config{
Stdout: out,
Stdin: in,
Expand Down Expand Up @@ -117,6 +120,7 @@ func scanMultiLine(prompt string, secondMessage string, out io.Writer, in io.Rea
} else if err == io.EOF {
break
}

switch state {
case start:
if line == "" {
Expand Down Expand Up @@ -152,25 +156,36 @@ func createAndEditSnippet(newSnippet snippet.SnippetInfo, snippets snippet.Snipp

// Open snippet for editing
snippetFile := config.Conf.General.SnippetFile
snippetFilePath, err := path.NewAbsolutePath(snippetFile)
if err != nil {
return err
}

editor := config.Conf.General.Editor
err := editFile(editor, snippetFile, startLine)
err = editFile(editor, snippetFilePath, startLine)
if err != nil {
return err
}

if config.Conf.Gist.AutoSync {
return petSync.AutoSync(snippetFile)
return petSync.AutoSync(snippetFilePath)
}

return nil
}

func countSnippetLines() int {
// Count lines in snippet file
f, err := os.Open(config.Conf.General.SnippetFile)
path, err := path.NewAbsolutePath(config.Conf.General.SnippetFile)
if err != nil {
panic(fmt.Sprintf("Error getting snippet file path: %v", err.Error()))
}

f, err := os.Open(path.Get())
if err != nil {
panic("Snippet file must be specified - could not read snippet file.")
}

lineCount, err := CountLines(f)
if err != nil {
panic("Error counting lines in snippet file")
Expand Down Expand Up @@ -218,10 +233,10 @@ func _new(in io.ReadCloser, out io.Writer, args []string) (err error) {
}

return createAndEditSnippet(newSnippet, snippets, lineCount+3)

} else {
command, err = scan(color.HiYellowString("Command> "), out, in, false)
}

if err != nil {
return err
}
Expand Down Expand Up @@ -258,13 +273,18 @@ func _new(in io.ReadCloser, out io.Writer, args []string) (err error) {
Command: command,
Tag: tags,
}

snippets.Snippets = append(snippets.Snippets, newSnippet)
if err = snippets.Save(); err != nil {
return err
}

if config.Conf.Gist.AutoSync {
return petSync.AutoSync(filename)
filePath, err := path.NewAbsolutePath(filename)
if err != nil {
return err
}
return petSync.AutoSync(filePath)
}

return nil
Expand Down
6 changes: 5 additions & 1 deletion cmd/new_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,15 @@ func TestScanMultiLine_ExitsOnTwoEmptyLines(t *testing.T) {

func TestNewSnippetCreationWithSnippetDirectory(t *testing.T) {
// Setup temporary directory for config
tempDir := t.TempDir()
tempDir, _ := os.MkdirTemp("", "testdata")
tempSnippetFile := filepath.Join(tempDir, "snippet.toml")
tempSnippetDir1 := filepath.Join(tempDir, "snippets1")
tempSnippetDir2 := filepath.Join(tempDir, "snippets2")

// Clean up temp dirs, needed for windows
// https://github.com/golang/go/issues/51442
defer os.RemoveAll(tempDir)

// Create snippet directories
if err := os.Mkdir(tempSnippetDir1, 0755); err != nil {
t.Fatalf("Failed to create temp snippet directory: %v", err)
Expand Down
8 changes: 7 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"path/filepath"

"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -79,7 +80,12 @@ func initConfig() {
configFile = filepath.Join(dir, "config.toml")
}

if err := config.Conf.Load(configFile); err != nil {
absPath, err := path.NewAbsolutePath(configFile)
if err != nil {
panic(err)
}

if err := config.Conf.Load(absPath); err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
petSync "github.com/knqyf263/pet/sync"
"github.com/spf13/cobra"
)
Expand All @@ -15,7 +16,8 @@ var syncCmd = &cobra.Command{
}

func sync(cmd *cobra.Command, args []string) (err error) {
return petSync.AutoSync(config.Conf.General.SnippetFile)
filePath, err := path.NewAbsolutePath(config.Conf.General.SnippetFile)
return petSync.AutoSync(filePath)
}

func init() {
Expand Down
18 changes: 13 additions & 5 deletions cmd/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package cmd

import (
"bytes"
"errors"
"fmt"
"io"
"strings"

"github.com/fatih/color"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/dialog"
"github.com/knqyf263/pet/path"
"github.com/knqyf263/pet/snippet"
)

Expand Down Expand Up @@ -98,7 +100,7 @@ func filter(options []string, tag string) (commands []string, err error) {
// selectFile returns a snippet file path from the list of snippets
// options are simply the list of arguments to pass to the select command (ex. --query for fzf)
// tag is used to filter the list of snippets by the tag field in the snippet
func selectFile(options []string, tag string) (snippetFile string, err error) {
func selectFile(options []string, tag string) (snippetFile path.AbsolutePath, err error) {
var snippets snippet.Snippets
if err := snippets.Load(true); err != nil {
return snippetFile, fmt.Errorf("load snippet failed: %v", err)
Expand Down Expand Up @@ -143,14 +145,20 @@ func selectFile(options []string, tag string) (snippetFile string, err error) {
config.Conf.General.SelectCmd, strings.Join(options, " "))
err = run(selectCmd, strings.NewReader(text), &buf)
if err != nil {
return snippetFile, nil
return nil, err
}

// Parse the selected line and return the corresponding snippet file
// We might have multiple lines selected, but we only care about the first one
lines := strings.Split(strings.TrimSuffix(buf.String(), "\n"), "\n")
for _, line := range lines {
snippetInfo := snippetTexts[line]
snippetFile = fmt.Sprint(snippetInfo.Filename)
if len(lines) == 0 {
return nil, errors.New("no snippet file selected")
}

snippetInfo := snippetTexts[lines[0]]
snippetFile, err = path.NewAbsolutePath(snippetInfo.Filename)
if err != nil {
return nil, err
}
return snippetFile, nil
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/util_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strconv"

"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
)

func run(command string, r io.Reader, w io.Writer) error {
Expand All @@ -25,7 +26,7 @@ func run(command string, r io.Reader, w io.Writer) error {
return cmd.Run()
}

func editFile(command, file string, startingLine int) error {
command += " +" + strconv.Itoa(startingLine) + " " + file
func editFile(command string, filePath path.AbsolutePath, startingLine int) error {
command += " +" + strconv.Itoa(startingLine) + " " + filePath.Get()
return run(command, os.Stdin, os.Stdout)
}
5 changes: 3 additions & 2 deletions cmd/util_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"syscall"

"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/path"
)

func run(command string, r io.Reader, w io.Writer) error {
Expand All @@ -27,7 +28,7 @@ func run(command string, r io.Reader, w io.Writer) error {
return cmd.Run()
}

func editFile(command, file string, startingLine int) error {
command += " " + file
func editFile(command string, filePath path.AbsolutePath, startingLine int) error {
command += " " + filePath.Get()
return run(command, os.Stdin, os.Stdout)
}
Loading

0 comments on commit 3d34c13

Please sign in to comment.