-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_init.go
118 lines (94 loc) · 2.37 KB
/
cmd_init.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
package cli
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"time"
"github.com/michenriksen/tmpl/config"
"github.com/michenriksen/tmpl/internal/env"
"github.com/michenriksen/tmpl/internal/static"
)
var cleanSessNameRE = regexp.MustCompile(`[^\w._-]+`)
func (a *App) runInit(_ context.Context) error {
a.initLogger()
dst := ""
if len(a.opts.args) != 0 {
dst = a.opts.args[0]
}
if dst == "" {
wd, err := env.Getwd()
if err != nil {
return fmt.Errorf("getting current working directory: %w", err)
}
dst = filepath.Join(wd, config.ConfigFileName())
}
info, err := os.Stat(dst)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("getting file info for destination path: %w", err)
}
}
if info != nil {
if !info.IsDir() {
a.logger.Info("file already exists, skipping",
"path", info.Name(), "size", info.Size(), "modified", info.ModTime(),
)
return nil
}
dst = filepath.Join(dst, config.ConfigFileName())
}
text := static.ConfigTemplate
if a.opts.Plain {
text = stripCfgComments(text)
}
cfgTmpl, err := template.New(config.DefaultConfigFile).Parse(text)
if err != nil {
return fmt.Errorf("parsing embedded configuration template: %w", err)
}
data := templateData{
AppName: AppName,
Version: Version(),
Name: cleanSessionName(filepath.Base(filepath.Dir(dst))),
Time: time.Now(),
DocsURL: "https://github.com/michenriksen/tmpl",
}
cfgFile, err := os.Create(dst)
if err != nil {
return fmt.Errorf("creating configuration file: %w", err)
}
defer cfgFile.Close()
if err := cfgTmpl.Execute(cfgFile, data); err != nil {
return fmt.Errorf("writing configuration file: %w", err)
}
a.logger.Info("configuration file created", "path", cfgFile.Name())
return nil
}
func cleanSessionName(name string) string {
name = cleanSessNameRE.ReplaceAllString(strings.TrimSpace(name), "_")
return strings.Trim(name, "._-")
}
func stripCfgComments(text string) string {
lines := strings.Split(text, "\n")
b := strings.Builder{}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if len(trimmed) == 0 || strings.HasPrefix(trimmed, "#") {
continue
}
b.WriteString(line + "\n")
}
return strings.TrimSpace(b.String())
}
type templateData struct {
AppName string
Time time.Time
DocsURL string
Name string
Version string
}