-
Notifications
You must be signed in to change notification settings - Fork 1
/
last.go
90 lines (84 loc) · 2.38 KB
/
last.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package cmd
import (
"encoding/json"
"fmt"
"github.com/islewis/ggpt/common"
"github.com/spf13/cobra"
"io/fs"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
// lastCmd represents the last command
var lastCmd = &cobra.Command{
Use: "last",
Short: "Returns the output of the previous query.",
Long: `Last repeats the output of the previous GPT query.
In comparison to querying again with the same prompt,
last guarentees the previous output, and prevents
unnecessary usage of OpenAI's API. This saves time
and money when a simple reuse is desired.
`,
Run: func(cmd *cobra.Command, args []string) {
// Make sure theres a record to use
home, _ := os.UserHomeDir()
histDir := home + "/.ggpt/history"
// Get list of files, via timestamped name
var records []int64
filepath.WalkDir(histDir, func(s string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Println("Unable to find any previous queries.")
log.Fatal(err)
}
if filepath.Ext(d.Name()) == ".json" {
file := strings.Split(s, "/")
timestamp := strings.Split(file[len(file)-1], ".")
// take first slice, conv to int64
timestampI64, err := strconv.ParseInt(timestamp[0], 10, 64)
if err != nil {
log.Fatal(err)
}
records = append(records, timestampI64)
}
return nil
})
// check there is a record to return
if len(records) == 0 {
fmt.Println("No previous queries found. Make one with \"ggpt prompt\"")
os.Exit(0)
}
// get latest record
latest := records[0]
for _, value := range records {
if value > latest {
latest = value
}
}
// return output of latest record
latestPath := histDir + "/" + strconv.FormatInt(latest, 10) + ".json"
jsonFile, err := os.Open(latestPath)
if err != nil {
log.Fatal(err)
}
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
log.Fatal(err)
}
var record common.Record
json.Unmarshal(byteValue, &record)
fmt.Println(record.Output)
},
}
func init() {
rootCmd.AddCommand(lastCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// lastCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// lastCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}