~adnano/astronaut

astronaut/main.go -rw-r--r-- 2.3 KiB
947cfac7Adnan Maolood Update default bindings 17 days ago
                                                                                
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main

import (
	"astronaut/styles"
	"astronaut/ui"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"time"

	"git.sr.ht/~adnano/go-xdg"
	"git.sr.ht/~emersion/go-scfg"
)

var (
	Version  string
	ShareDir string
)

func main() {
	version := flag.Bool("v", false, "print version")
	flag.Parse()
	if *version {
		fmt.Println("astronaut", Version)
		return
	}

	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	os.MkdirAll(filepath.Join(xdg.DataHome(), "astronaut"), 0700)
	configHome := filepath.Join(xdg.ConfigHome(), "astronaut")

	config := &Config{Binds: Binds{}}
	if err := parseConfig("astronaut.conf", configHome, ShareDir, config.Parse); err != nil {
		return err
	}
	if err := parseConfig("style.conf", configHome, ShareDir, styles.Parse); err != nil {
		return err
	}

	// Disable logging if os.Stderr is a TTY
	stat, err := os.Stderr.Stat()
	if err != nil {
		return err
	}
	if (stat.Mode() & os.ModeCharDevice) != 0 {
		// Discard log entries
		log.Default().SetOutput(io.Discard)
	}

	ui, err := ui.New()
	if err != nil {
		return err
	}
	defer ui.Close()

	browser := NewBrowser(ui, config)
	ui.Init(browser)

	for !ui.Exiting() {
		browser.Update()

		if !ui.Tick(browser) {
			// ~60 FPS
			time.Sleep(16 * time.Millisecond)
		}
	}

	return nil
}

func openConfigFile(name, dir, sharedir string) (fs.File, error) {
	// Try to open the file
	path := filepath.Join(dir, name)
	f, err := os.Open(path)
	if err == nil {
		return f, nil
	}

	// Return the error if the file exists or sharedir is empty
	if !errors.Is(err, os.ErrNotExist) || len(sharedir) == 0 {
		return nil, err
	}

	// Create the directory if it does not exist
	if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
		if err := os.MkdirAll(dir, 0755); err != nil {
			return nil, err
		}
	}

	// Copy the file
	data, err := os.ReadFile(filepath.Join(sharedir, name))
	if err != nil {
		return nil, err
	}
	if err := os.WriteFile(path, data, 0644); err != nil {
		return nil, err
	}
	return os.Open(path)
}

func parseConfig(name, dir, sharedir string, parse func(scfg.Block) error) error {
	f, err := openConfigFile(name, dir, sharedir)
	if err != nil {
		return err
	}
	defer f.Close()
	block, err := scfg.Read(f)
	if err != nil {
		return err
	}
	return parse(block)
}