/
utils.go
63 lines (49 loc) · 1.21 KB
/
utils.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
package edit
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/9seconds/chore/internal/commands"
"github.com/9seconds/chore/internal/env"
)
const (
ConfigDefaultPermission = 0o666
ScriptDefaultPermissions = 0o755
DirDefaultPermissions = 0o777
)
func ensureFile(path string, content []byte) error {
if err := os.MkdirAll(filepath.Dir(path), DirDefaultPermissions); err != nil {
return fmt.Errorf("cannot ensure parent dir %s: %w", filepath.Dir(path), err)
}
writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, ConfigDefaultPermission)
switch {
case errors.Is(err, fs.ErrExist):
return nil
case err != nil:
return fmt.Errorf("cannot create a file: %w", err)
}
_, err = writer.Write(content)
return err
}
func openEditor(ctx context.Context, editor, path string) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
cmd := commands.New(
editor,
[]string{path},
env.Environ(),
os.Stdin,
os.Stdout,
os.Stderr)
if err := cmd.Start(ctx); err != nil {
return fmt.Errorf("cannot start editor: %w", err)
}
result := cmd.Wait()
if result.ExitCode != 0 {
return fmt.Errorf("command exited with %d", result.ExitCode)
}
return nil
}