Skip to content

Commit

Permalink
Adds save option
Browse files Browse the repository at this point in the history
  • Loading branch information
tomnomnom committed Sep 16, 2018
1 parent bfdae25 commit 94ca246
Showing 1 changed file with 56 additions and 3 deletions.
59 changes: 56 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,39 @@ package main

import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
)

type pattern struct {
Flags string `json:"flags"`
Pattern string `json:"pattern"`
Patterns []string `json:"patterns"`
Flags string `json:"flags,omitempty"`
Pattern string `json:"pattern,omitempty"`
Patterns []string `json:"patterns,omitempty"`
}

func main() {
var saveMode bool
flag.BoolVar(&saveMode, "save", false, "save a pattern (e.g: gf -save pat-name -Hnri 'search-pattern')")
flag.Parse()

if saveMode {
name := flag.Arg(0)
flags := flag.Arg(1)
pattern := flag.Arg(2)

err := savePattern(name, flags, pattern)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
return
}

patName := flag.Arg(0)
files := flag.Arg(1)
if files == "" {
Expand Down Expand Up @@ -72,3 +88,40 @@ func getHomeDir() (string, error) {
}
return usr.HomeDir, nil
}

func savePattern(name, flags, pat string) error {
if name == "" {
return errors.New("name cannot be empty")
}

if pat == "" {
return errors.New("pattern cannot be empty")
}

p := &pattern{
Flags: flags,
Pattern: pat,
}

home, err := getHomeDir()
if err != nil {
return fmt.Errorf("failed to determine home directory: %s", err)
}

path := filepath.Join(home, ".gf", name+".json")
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return fmt.Errorf("failed to create pattern file: %s", err)
}
defer f.Close()

enc := json.NewEncoder(f)
enc.SetIndent("", " ")

err = enc.Encode(p)
if err != nil {
return fmt.Errorf("failed to write pattern file: %s", err)
}

return nil
}

0 comments on commit 94ca246

Please sign in to comment.