Skip to content

Commit

Permalink
Save history to .go-pry_history
Browse files Browse the repository at this point in the history
  • Loading branch information
d4l3k committed Jul 19, 2017
1 parent 911b948 commit 88f35be
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 2 deletions.
53 changes: 51 additions & 2 deletions pry/pry.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package pry

import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"runtime"
"strings"
Expand All @@ -14,13 +17,57 @@ import (
"github.com/mattn/go-colorable"
gotty "github.com/mattn/go-tty"
"github.com/mgutz/ansi"
homedir "github.com/mitchellh/go-homedir"
)

var (
out io.Writer = os.Stdout
tty *gotty.TTY
)

var historyFile = ".go-pry_history"

func historyPath() (string, error) {
dir, err := homedir.Dir()
if err != nil {
return "", err
}
return path.Join(dir, historyFile), nil
}

func loadHistory() []string {
path, err := historyPath()
if err != nil {
log.Printf("Error finding user home dir: %s", err)
return nil
}
body, err := ioutil.ReadFile(path)
if err != nil {
return nil
}
var history []string
if err := json.Unmarshal(body, &history); err != nil {
log.Printf("Error reading history file! %s", err)
return nil
}
return history
}

func saveHistory(history *[]string) {
body, err := json.Marshal(history)
if err != nil {
log.Printf("Err marshalling history: %s", err)
}
path, err := historyPath()
if err != nil {
log.Printf("Error finding user home dir: %s", err)
return
}
if err := ioutil.WriteFile(path, body, 0755); err != nil {
log.Printf("Error writing history: %s", err)
}
}

// Pry does nothing. It only exists so running code without go-pry doesn't throw an error.
func Pry(v ...interface{}) {
}
Expand Down Expand Up @@ -50,8 +97,10 @@ func Apply(scope *Scope) {

displayFilePosition(filePathRaw, filePath, lineNum)

history := []string{}
currentPos := 0
history := loadHistory()
defer saveHistory(&history)

currentPos := len(history)

line := ""
count := 0
Expand Down
25 changes: 25 additions & 0 deletions pry/pry_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
package pry

import (
"fmt"
"math/rand"
"reflect"
"testing"
"time"
)

func TestHistory(t *testing.T) {
rand.Seed(time.Now().UnixNano())

historyFile = ".go-pry_history_test"

want := []string{
"test",
fmt.Sprintf("rand: %d", rand.Int63()),
}
saveHistory(&want)

out := loadHistory()
if !reflect.DeepEqual(want, out) {
t.Errorf("loadHistory() = %+v; expected %+v", out, want)
}
}

0 comments on commit 88f35be

Please sign in to comment.