commit 7f70f10

Duc Nguyen  ·  2021-11-05 14:24:27 +0000 UTC
parent cc20367
Also write the last buffer on SIGTERM, SIGINT and SIGHUP
1 files changed,  +20, -8
+20, -8
 1@@ -6,8 +6,10 @@ import (
 2 	"io/ioutil"
 3 	"math/rand"
 4 	"os"
 5+	"os/signal"
 6 	"path"
 7 	"strings"
 8+	"syscall"
 9 	"time"
10 
11 	"git.sr.ht/~taiite/senpai"
12@@ -51,16 +53,17 @@ func main() {
13 	lastNetID, lastBuffer := getLastBuffer()
14 	app.SwitchToBuffer(lastNetID, lastBuffer)
15 
16+	sigCh := make(chan os.Signal, 1)
17+	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
18+
19+	go func() {
20+		<-sigCh
21+		app.Close()
22+	}()
23+
24 	app.Run()
25 	app.Close()
26-
27-	// Write last buffer on close
28-	lastBufferPath := getLastBufferPath()
29-	lastNetID, lastBuffer = app.CurrentBuffer()
30-	err = os.WriteFile(lastBufferPath, []byte(fmt.Sprintf("%s %s", lastNetID, lastBuffer)), 0666)
31-	if err != nil {
32-		fmt.Fprintf(os.Stderr, "failed to write last buffer at %q: %s\n", lastBufferPath, err)
33-	}
34+	writeLastBuffer(app)
35 }
36 
37 func getLastBufferPath() string {
38@@ -91,3 +94,12 @@ func getLastBuffer() (netID, buffer string) {
39 
40 	return fields[0], fields[1]
41 }
42+
43+func writeLastBuffer(app *senpai.App) {
44+	lastBufferPath := getLastBufferPath()
45+	lastNetID, lastBuffer := app.CurrentBuffer()
46+	err := os.WriteFile(lastBufferPath, []byte(fmt.Sprintf("%s %s", lastNetID, lastBuffer)), 0666)
47+	if err != nil {
48+		fmt.Fprintf(os.Stderr, "failed to write last buffer at %q: %s\n", lastBufferPath, err)
49+	}
50+}