Skip to content

Commit ab03838

Browse files
committed
load and save history.
1 parent 714c66f commit ab03838

1 file changed

Lines changed: 36 additions & 3 deletions

File tree

nextone.go

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import (
77
"io"
88
"log"
99
"os"
10+
"os/signal"
1011
"os/user"
1112
"path/filepath"
1213
"sort"
1314
"strings"
15+
"syscall"
1416

1517
"github.com/mattn/go-colorable"
1618
"github.com/mgutz/ansi"
@@ -20,6 +22,9 @@ import (
2022
// DbFileName is the default file name find in user home
2123
const DbFileName = "db.task"
2224

25+
// HistoryFileName is the name of the nextone cmd line history
26+
const HistoryFileName = ".nextone_history"
27+
2328
// DbEnvPath is an environment variable that helps configure db path
2429
const DbEnvPath = "NEXTONE_DB_PATH"
2530

@@ -34,11 +39,11 @@ func main() {
3439

3540
flag.Parse()
3641

42+
u, err := user.Current()
3743
if *dbFlag == "" {
3844
// open db.task file in user home
3945
dbPath = os.Getenv(DbEnvPath)
4046
if dbPath == "" {
41-
u, err := user.Current()
4247
if err != nil {
4348
fmt.Print(err)
4449
return
@@ -59,7 +64,8 @@ func main() {
5964
// sort task
6065
sort.Sort(TaskByTime(db.Tasks))
6166

62-
interactive(stdout, db)
67+
historyPath := filepath.Join(u.HomeDir, HistoryFileName)
68+
interactive(stdout, db, historyPath)
6369
}
6470

6571
func openDatabase(dbPath string) (*JSONDb, error) {
@@ -118,10 +124,16 @@ func saveDatabase(dbPath string, db *JSONDb) (err error) {
118124
return nil
119125
}
120126

121-
func interactive(stdout io.Writer, db *JSONDb) {
127+
func interactive(stdout io.Writer, db *JSONDb, historyPath string) {
122128
line := liner.NewLiner()
123129
defer line.Close()
124130

131+
f, err := os.Open(historyPath)
132+
if err == nil {
133+
defer f.Close()
134+
line.ReadHistory(f)
135+
}
136+
125137
line.SetCtrlCAborts(true)
126138

127139
line.SetCompleter(func(line string) (c []string) {
@@ -133,7 +145,28 @@ func interactive(stdout io.Writer, db *JSONDb) {
133145
return
134146
})
135147

148+
saveHistory := func() {
149+
fmt.Println("save history")
150+
f, err := os.Create(historyPath)
151+
if err != nil {
152+
log.Print("Error writing history file: ", err)
153+
} else {
154+
defer f.Close()
155+
line.WriteHistory(f)
156+
}
157+
}
158+
159+
c := make(chan os.Signal)
160+
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
161+
go func() {
162+
<-c
163+
// handle ctrl+c event here
164+
saveHistory()
165+
os.Exit(0)
166+
}()
167+
136168
mainPrompt(line, stdout, db)
169+
saveHistory()
137170
}
138171

139172
func mainPrompt(line *liner.State, stdout io.Writer, db *JSONDb) {

0 commit comments

Comments
 (0)