generated from brevdev/seed
-
Notifications
You must be signed in to change notification settings - Fork 9
/
files.go
370 lines (314 loc) · 8.89 KB
/
files.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package files
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"golang.org/x/text/encoding/charmap"
"github.com/google/uuid"
"github.com/spf13/afero"
)
const (
brevDirectory = ".brev"
// This might be better as a context.json??
activeOrgFile = "active_org.json"
orgCacheFile = "org_cache.json"
workspaceCacheFile = "workspace_cache.json"
// WIP: This will be used to let people "brev open" with editors other than VS Code
personalSettingsCache = "personal_settings.json"
kubeCertFileName = "brev.crt"
sshPrivateKeyFileName = "brev.pem"
backupSSHConfigFileNamePrefix = "config.bak"
tailscaleOutFileName = "tailscale_out.log"
sshPrivateKeyFilePermissions = 0o600
defaultFilePermission = 0o770
)
var AppFs = afero.NewOsFs()
func GetBrevDirectory() string {
return brevDirectory
}
func GetActiveOrgFile() string {
return activeOrgFile
}
func GetPersonalSettingsCache() string {
return personalSettingsCache
}
func GetOrgCacheFile() string {
return orgCacheFile
}
func GetWorkspaceCacheFile() string {
return workspaceCacheFile
}
func GetKubeCertFileName() string {
return kubeCertFileName
}
func GetSSHPrivateKeyFileName() string {
return sshPrivateKeyFileName
}
func GetTailScaleOutFileName() string {
return tailscaleOutFileName
}
func GetNewBackupSSHConfigFileName() string {
return fmt.Sprintf("%s.%s", backupSSHConfigFileNamePrefix, uuid.New())
}
func BuildBrevHome(fs afero.Fs, userHome string) error {
brevHome, err := GetBrevHome(userHome)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if err := fs.MkdirAll(brevHome, defaultFilePermission); err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func makeBrevFilePath(filename string, userHome string) (*string, error) {
brevHome, err := GetBrevHome(userHome)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
fpath := filepath.Join(brevHome, filename)
return &fpath, nil
}
func GetBrevHome(userHome string) (string, error) {
return filepath.Join(userHome, brevDirectory), nil
}
func GetActiveOrgsPath(home string) (string, error) {
fpath, err := makeBrevFilePath(activeOrgFile, home)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
return *fpath, nil
}
func GetPersonalSettingsCachePath(home string) (string, error) {
fpath, err := makeBrevFilePath(personalSettingsCache, home)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
return *fpath, nil
}
func GetSSHPrivateKeyPath(home string) (string, error) {
fpath, err := makeBrevFilePath(GetSSHPrivateKeyFileName(), home)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
return *fpath, nil
}
func GetUserSSHConfigPath(home string) (string, error) {
sshConfigPath := filepath.Join(home, ".ssh", "config")
return sshConfigPath, nil
}
func GetBrevSSHConfigPath(home string) (string, error) {
path, err := GetBrevHome(home)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
brevSSHConfigPath := filepath.Join(path, "ssh_config")
return brevSSHConfigPath, nil
}
func GetNewBackupSSHConfigFilePath(home string) (*string, error) {
fp, err := makeBrevFilePath(GetNewBackupSSHConfigFileName(), home)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return fp, nil
}
func GetTailScaleOutFilePath(home string) (*string, error) {
fp, err := makeBrevFilePath(GetTailScaleOutFileName(), home)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return fp, nil
}
// ReadJSON reads data from a file into the given struct
//
// Usage:
// var foo myStruct
// files.ReadJSON("tmp/a.json", &foo)
func ReadJSON(fs afero.Fs, unsafeFilePathString string, v interface{}) error {
safeFilePath := filepath.Clean(unsafeFilePathString)
f, err := fs.Open(safeFilePath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
dataBytes, err := afero.ReadAll(f)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = json.Unmarshal(dataBytes, v)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if err = f.Close(); err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func ReadString(fs afero.Fs, unsafeFilePathString string) (string, error) {
safeFilePath := filepath.Clean(unsafeFilePathString)
f, err := fs.Open(safeFilePath)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
dataBytes, err := ioutil.ReadAll(f)
if err != nil {
return "", breverrors.WrapAndTrace(err)
}
if err = f.Close(); err != nil {
return "", breverrors.WrapAndTrace(err)
}
return string(dataBytes), nil
// fmt.Println(dataBytes)
// fmt.Println(string(dataBytes))
}
// OverwriteJSON data in the target file with data from the given struct
//
// Usage (unstructured):
// OverwriteJSON("tmp/a/b/c.json", map[string]string{
// "hi": "there",
// })
//
//
// Usage (struct):
// var foo myStruct
// OverwriteJSON("tmp/a/b/c.json", foo)
func OverwriteJSON(fs afero.Fs, filepath string, v interface{}) error {
f, err := touchFile(fs, filepath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
// clear
err = f.Truncate(0)
if err != nil {
return breverrors.WrapAndTrace(err)
}
// write
dataBytes, err := json.MarshalIndent(v, "", " ")
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = ioutil.WriteFile(filepath, dataBytes, os.ModePerm)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if err = f.Close(); err != nil {
return breverrors.WrapAndTrace(err)
}
return breverrors.WrapAndTrace(err)
}
// OverwriteString data in the target file with data from the given string
//
// Usage
// OverwriteString("tmp/a/b/c.txt", "hi there")
func OverwriteString(fs afero.Fs, filepath string, data string) error {
f, err := touchFile(fs, filepath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
// clear
err = f.Truncate(0)
if err != nil {
return breverrors.WrapAndTrace(err)
}
// write
err = ioutil.WriteFile(filepath, []byte(data), os.ModePerm)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if err = f.Close(); err != nil {
return breverrors.WrapAndTrace(err)
}
return breverrors.WrapAndTrace(err)
}
func WriteSSHPrivateKey(fs afero.Fs, data string, home string) error {
pkPath, err := GetSSHPrivateKeyPath(home)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = afero.WriteFile(fs, pkPath, []byte(data), sshPrivateKeyFilePermissions)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
// Delete a single file altogether.
func DeleteFile(fs afero.Fs, filepath string) error {
err := fs.Remove(filepath)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
// Create file (and full path) if it does not already exit.
func touchFile(fs afero.Fs, path string) (afero.File, error) {
if err := fs.MkdirAll(filepath.Dir(path), defaultFilePermission); err != nil {
return nil, breverrors.WrapAndTrace(err)
}
f, err := fs.Create(path)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return f, nil
}
func CatFile(filePath string) (string, error) {
gocmd := exec.Command("cat", filePath) // #nosec G204
in, err := gocmd.Output()
if err != nil {
return "", breverrors.WrapAndTrace(err, "error reading file "+filePath)
} else {
d := charmap.CodePage850.NewDecoder()
out, err := d.Bytes(in)
if err != nil {
return "", breverrors.WrapAndTrace(err, "error reading file "+filePath)
}
return string(out), nil
}
}
func GetAliasesFromFile(file string) []string {
var result []string
dirname, err := os.UserHomeDir()
if err != nil {
// if this doesn't work, just exit
return nil
}
lines, err := CatFile(dirname + "/" + file)
if err != nil {
// if this doesn't work, just exit
return nil
}
for _, line := range strings.Split(lines, "\n") {
if strings.HasPrefix(line, "alias ") {
result = append(result, line)
}
}
return result
}
func GetAllAliases() []string {
var lines []string
lines = append(lines, GetAliasesFromFile(".zshrc")...)
lines = append(lines, GetAliasesFromFile(".bashrc")...)
lines = append(lines, GetAliasesFromFile(".zprofile")...)
lines = append(lines, GetAliasesFromFile(".bash_profile")...)
lines = append(lines, GetAliasesFromFile(".config/fish/config.fish")...)
var output []string
for _, line := range lines {
output = append(output, fmt.Sprintf("echo '%s' >> /home/brev/.zshrc", line))
output = append(output, fmt.Sprintf("echo '%s' >> /home/brev/.bashrc", line))
}
return output
}
func GenerateSetupScript(lines []string) string {
introString := `
#!/bin/bash
set -euo pipefail
##### This is your brev.dev setup script
##### Commit this file to the repo to make the environment reproducible
##### https://docs.brev.dev/howto/automatically-set-up
`
output := []string{introString, `##### Adding Aliases From Your Local Machine #####\n`, `(echo ""; echo "##### Adding Aliases From Your Local Machine #####"; echo "";)\n`}
output = append(output, lines...)
return strings.Join(output, "\n")
}