-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
112 lines (87 loc) · 2.4 KB
/
io.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
// Helper methods used for config file handling
import (
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
)
const configDirectoryName = ".ewvm"
func WriteFile(name string, data []byte, perm fs.FileMode) error {
if _, err := os.Stat(configDirectory()); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(configDirectory(), 0700)
if err != nil {
Fatalf("Error creating config file directory at %s: %s", configDirectory(), err)
}
}
targetFilePath := filepath.Join(configDirectory(), name)
if err := os.WriteFile(targetFilePath, data, perm); err != nil {
return err
}
return nil
}
func ReadFile(name string) ([]byte, error) {
if _, err := os.Stat(configDirectory()); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(configDirectory(), 0700)
if err != nil {
Fatalf("Error creating config file directory at %s: %s", configDirectory(), err)
}
}
targetFilePath := filepath.Join(configDirectory(), name)
return os.ReadFile(targetFilePath)
}
func copyToClipboard(content string) error {
cmd := exec.Command("/usr/bin/pbcopy")
stdIn, err := cmd.StdinPipe()
if err != nil {
return err
}
if err = cmd.Start(); err != nil {
return err
}
if _, err := io.WriteString(stdIn, content); err != nil {
return err
}
if err = stdIn.Close(); err != nil {
return err
}
if err = cmd.Wait(); err != nil {
return err
}
return nil
}
func baseConfigDirectory() string {
homeDir, err := os.UserHomeDir()
if err != nil {
Fatalf("Error getting user's home directory: %s", err)
}
return homeDir
}
func configDirectory() string {
return filepath.Join(baseConfigDirectory(), configDirectoryName)
}
func setLogFile(name string) *os.File {
if _, err := os.Stat(configDirectory()); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(configDirectory(), 0700)
if err != nil {
Fatalf("Error creating config file directory at %s: %s", configDirectory(), err)
}
}
targetFilePath := filepath.Join(configDirectory(), name)
logFile, err := os.OpenFile(targetFilePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0700)
if err != nil {
Fatalf("Error creating logger: %s", err)
}
log.SetOutput(logFile)
return logFile
}
// Small wrapper over Fatalf so that any Fatalf's both write to the verbose log file configured for it,
// and to stdout so the user sees what went wrong
func Fatalf(format string, v ...any) {
fmt.Println(fmt.Sprintf(format, v...))
log.Fatalf(format, v...)
}