/
mod_show_config.go
254 lines (214 loc) · 6.76 KB
/
mod_show_config.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
/*
Copyright 2024 Stefan Prodan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"cuelang.org/go/cue/cuecontext"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
apiv1 "github.com/stefanprodan/timoni/api/v1alpha1"
"github.com/stefanprodan/timoni/internal/engine"
"github.com/stefanprodan/timoni/internal/engine/fetcher"
"github.com/stefanprodan/timoni/internal/flags"
)
var configShowModCmd = &cobra.Command{
Use: "config [MODULE PATH]",
Short: "Output the #Config structure of a local module",
Long: `The config command parses the local module configuration structure and outputs the information to stdout.`,
Example: ` # print the config of a module in the current directory
timoni mod show config
# output the config to a file, if the file is markdown, the table will overwrite a table in a Configuration section or
# be appended to the end of the file
timoni mod show config --output ./README.md
`,
RunE: runConfigShowModCmd,
}
type configModFlags struct {
path string
pkg flags.Package
name string
output string
}
var configShowModArgs = configModFlags{
name: "module-name",
}
func init() {
configShowModCmd.Flags().StringVarP(&configShowModArgs.output, "output", "o", "", "The file to output the config Markdown to, defaults to stdout")
showModCmd.AddCommand(configShowModCmd)
}
func runConfigShowModCmd(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
configShowModArgs.path = "."
} else {
configShowModArgs.path = args[0]
}
if fs, err := os.Stat(configShowModArgs.path); err != nil || !fs.IsDir() {
return fmt.Errorf("module not found at path %s", configShowModArgs.path)
}
cuectx := cuecontext.New()
tmpDir, err := os.MkdirTemp("", apiv1.FieldManager)
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
ctxPull, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
defer cancel()
f, err := fetcher.New(ctxPull, fetcher.Options{
Source: configShowModArgs.path,
Version: apiv1.LatestVersion,
Destination: tmpDir,
CacheDir: rootArgs.cacheDir,
Insecure: rootArgs.registryInsecure,
DefaultLocal: true,
})
if err != nil {
return err
}
mod, err := f.Fetch()
if err != nil {
return err
}
builder := engine.NewModuleBuilder(
cuectx,
configShowModArgs.name,
*kubeconfigArgs.Namespace,
f.GetModuleRoot(),
configShowModArgs.pkg.String(),
)
if err := builder.WriteSchemaFile(); err != nil {
return err
}
mod.Name, err = builder.GetModuleName()
if err != nil {
return fmt.Errorf("build failed: %w", err)
}
buildResult, err := builder.Build()
if err != nil {
return describeErr(f.GetModuleRoot(), "validation failed", err)
}
rows, err := builder.GetConfigDoc(buildResult)
if err != nil {
return describeErr(f.GetModuleRoot(), "failed to get config structure", err)
}
header := []string{"Key", "Type", "Default", "Description"}
if configShowModArgs.output == "" {
printMarkDownTable(rootCmd.OutOrStdout(), header, rows)
} else {
tmpFile, err := writeFile(configShowModArgs.output, header, rows, f)
if err != nil {
return err
}
err = os.Rename(tmpFile, configShowModArgs.output)
if err != nil {
return describeErr(f.GetModuleRoot(), "Unable to rename file", err)
}
}
return nil
}
func writeFile(readFile string, header []string, rows [][]string, f fetcher.Fetcher) (string, error) {
// Generate the markdown table
var tableBuffer bytes.Buffer
tableWriter := bufio.NewWriter(&tableBuffer)
printMarkDownTable(tableWriter, header, rows)
tableWriter.Flush()
// get a temporary file name
tmpFileName := readFile + ".tmp"
// open the input file
inputFile, err := os.Open(readFile)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
inputFile, err = os.Create(readFile)
if err != nil {
return "", describeErr(f.GetModuleRoot(), "Unable to create the temporary output file", err)
}
} else {
return "", describeErr(f.GetModuleRoot(), "Unable to create the temporary output file", err)
}
}
defer inputFile.Close()
// open the output file
outputFile, err := os.Create(tmpFileName)
if err != nil {
return "", describeErr(f.GetModuleRoot(), "Unable to create the temporary output file", err)
}
defer outputFile.Close()
// Create the scanner and writer
inputScanner := bufio.NewScanner(inputFile)
outputWriter := bufio.NewWriter(outputFile)
var configSection bool
var foundTable bool
// Scan the input file line by line to find the table and replace it or append it to the end
for inputScanner.Scan() {
line := inputScanner.Text()
if isMarkdownFile(readFile) {
if !configSection && line == "## Configuration" {
configSection = true
}
matched, err := regexp.MatchString(`^\|.*\|$`, line)
if err != nil {
return "", describeErr(f.GetModuleRoot(), "Regex Match for table content failed", err)
}
if configSection && !foundTable && matched {
foundTable = true
outputWriter.WriteString(tableBuffer.String() + "\n")
} else if configSection && foundTable && matched {
} else if configSection && foundTable && !matched {
configSection = false
} else {
outputWriter.WriteString(line + "\n")
}
} else {
outputWriter.WriteString(line + "\n")
}
}
// If no table was found, append it to the end of the file
if !foundTable {
outputWriter.WriteString("\n" + tableBuffer.String())
}
err = outputWriter.Flush()
if err != nil {
return "", describeErr(f.GetModuleRoot(), "Failed to Flush Writer", err)
}
return tmpFileName, nil
}
func printMarkDownTable(writer io.Writer, header []string, rows [][]string) {
table := tablewriter.NewWriter(writer)
table.SetHeader(header)
table.SetAutoWrapText(false)
table.SetAutoFormatHeaders(true)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetCenterSeparator("|")
table.SetColumnSeparator("|")
table.SetRowSeparator("-")
table.SetHeaderLine(true)
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetTablePadding("\t")
table.SetNoWhiteSpace(false)
table.AppendBulk(rows)
table.Render()
}
func isMarkdownFile(filename string) bool {
extension := strings.ToLower(filepath.Ext(filename))
return extension == ".md" || extension == ".markdown"
}