Skip to content

Commit 81bcf08

Browse files
authored
Merge pull request #9 from adam-huganir/feature/file-and-path-methods
added some file and path methods, added ls example
2 parents 13bd6ce + d8adf7e commit 81bcf08

8 files changed

+188
-14
lines changed

.pre-commit-config.yaml

+10-1
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,19 @@ repos:
1515
args: ["--fix", "lf"]
1616

1717

18+
- repo: local
19+
hooks:
20+
- id: go-fmt
21+
name: go format
22+
language: system
23+
entry: gofmt
24+
types:
25+
- go
26+
args: ["-l", "-w"]
27+
1828
- repo: https://github.com/dnephin/pre-commit-golang
1929
rev: v0.5.1
2030
hooks:
21-
- id: go-fmt
2231
- id: go-build
2332
- id: go-mod-tidy
2433
- repo: local

README.md

+23
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,29 @@ alternate form using matching
100100
--data-match './talosPatches/.*\.yaml' \
101101
<(echo "{{ . | toYaml }}")
102102
```
103+
### Listing files in a directory
104+
105+
For some reason you want to list the files in a directory and embed them in a file in a custom format:
106+
107+
```template
108+
{{- $files := fileGlob "./*/*" -}}
109+
{{- range $path := $files }}
110+
{{- $stat := fileStat $path }}
111+
{{- $username := (env "USERNAME" | default (env "USER") )}}
112+
{{- $usernameFString := printf "%s%d%s " "%-" (len $username) "s"}}
113+
{{ printf "%-12s" $stat.Mode }}{{ printf $usernameFString $username }}{{ pathAbsolute $path}}
114+
{{- end }}
115+
```
116+
```
117+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\COMMIT_EDITMSG
118+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\FETCH_HEAD
119+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\HEAD
120+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\ORIG_HEAD
121+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\config
122+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\description
123+
drwxrwxrwx adam C:\Users\adam\code\yet-unnamed-template-cli\.git\hooks
124+
........
125+
```
103126
### Merging 2 data files and applying them to a template
104127

105128
```pwsh

Taskfile.yaml

+4-5
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,12 @@ tasks:
4343
cmd: |-
4444
go run ./cmd/yutc/yutc.go --help
4545
46-
run-test1:
46+
run-tests:
4747
desc: "Run X"
4848
vars:
4949
ARGS: ""
50-
deps:
51-
- "build"
5250
run: always
53-
dir: "./tests"
5451
cmd: |-
55-
go run ../cmd/yutc/yutc.go --shared ./testTemplates/def1.tmpl --data ./testFiles/data1.yaml ./testTemplates/template1.tmpl
52+
go test ./cmd/yutc
53+
go test ./internal
54+
go test ./pkg

docs/_data/README.data.yaml

+25
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,31 @@ examples:
9191
--data-match './talosPatches/.*\.yaml' \
9292
<(echo "{{ . | toYaml }}")
9393
```
94+
- |-
95+
### Listing files in a directory
96+
97+
For some reason you want to list the files in a directory and embed them in a file in a custom format:
98+
99+
```template
100+
{{- $files := fileGlob "./*/*" -}}
101+
{{- range $path := $files }}
102+
{{- $stat := fileStat $path }}
103+
{{- $username := (env "USERNAME" | default (env "USER") )}}
104+
{{- $usernameFString := printf "%s%d%s " "%-" (len $username) "s"}}
105+
{{ printf "%-12s" $stat.Mode }}{{ printf $usernameFString $username }}{{ pathAbsolute $path}}
106+
{{- end }}
107+
```
108+
```
109+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\COMMIT_EDITMSG
110+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\FETCH_HEAD
111+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\HEAD
112+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\ORIG_HEAD
113+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\config
114+
-rw-rw-rw- adam C:\Users\adam\code\yet-unnamed-template-cli\.git\description
115+
drwxrwxrwx adam C:\Users\adam\code\yet-unnamed-template-cli\.git\hooks
116+
........
117+
```
118+
94119
- |-
95120
### Merging 2 data files and applying them to a template
96121

internal/template.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,17 @@ func BuildTemplate(text string, sharedTemplateBuffers []*bytes.Buffer, name stri
2323
"mustToToml": yutc.MustToToml,
2424
"mustFromToml": yutc.MustFromToml,
2525
// "stringMap": yutc.stringMap,
26-
"wrapText": yutc.WrapText,
27-
"wrapComment": yutc.WrapComment,
26+
"wrapText": yutc.WrapText,
27+
"wrapComment": yutc.WrapComment,
28+
"fileGlob": yutc.PathGlob,
29+
"fileStat": yutc.PathStat,
30+
"fileRead": yutc.FileRead,
31+
"fileReadN": yutc.FileReadN,
32+
"type": yutc.TypeOf,
33+
"pathAbsolute": yutc.PathAbsolute,
34+
"pathIsDir": yutc.PathIsDir,
35+
"pathIsFile": yutc.PathIsFile,
36+
"pathExists": yutc.PathExists,
2837
})
2938
for _, sharedTemplateBuffer := range sharedTemplateBuffers {
3039
tmpl, err = tmpl.Parse(sharedTemplateBuffer.String())

internal/version.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package internal
22

33
import "fmt"
44

5-
var yutcVersion = "0.0.6"
5+
var yutcVersion = "0.1.1"
66

77
func PrintVersion() {
88
fmt.Println(GetVersion())

pkg/customFunctions.go

+107-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"github.com/isbm/textwrap"
77
"github.com/pelletier/go-toml/v2"
88
"gopkg.in/yaml.v3"
9+
"os"
10+
"path/filepath"
911
"strings"
1012
)
1113

@@ -69,11 +71,6 @@ func FromToml(s string) interface{} {
6971

7072
}
7173

72-
func stringMap(v interface{}) (map[string]interface{}, error) {
73-
// i don't feel like writing a recursive function right now
74-
return nil, errors.New("not implemented")
75-
}
76-
7774
// WrapText wraps text to a given width
7875
func WrapText(width int, text string) []string {
7976
wrapper := textwrap.NewTextWrap()
@@ -89,3 +86,108 @@ func WrapComment(prefix string, width int, comment string) string {
8986
}
9087
return strings.Join(wrapped, "\n")
9188
}
89+
90+
func PathAbsolute(path string) string {
91+
path = pathCommonClean(path)
92+
path, err := filepath.Abs(path)
93+
if err != nil {
94+
panic(err)
95+
}
96+
return path
97+
}
98+
99+
func PathGlob(path string) []string {
100+
path = pathCommonClean(path)
101+
files, err := filepath.Glob(path)
102+
if err != nil {
103+
panic(err)
104+
}
105+
return files
106+
}
107+
108+
func PathStat(path string) map[string]interface{} {
109+
path = pathCommonClean(path)
110+
stat, err := os.Stat(path)
111+
if err != nil {
112+
if os.IsNotExist(err) {
113+
panic(errors.Join(fmt.Errorf("file not found: %s", path)))
114+
}
115+
if os.IsPermission(err) {
116+
panic(errors.Join(fmt.Errorf("permission denied: %s", path)))
117+
}
118+
panic(errors.Join(fmt.Errorf("unknown error %v: %s", err, path)))
119+
120+
}
121+
return map[string]interface{}{
122+
"Name": stat.Name(),
123+
"Size": stat.Size(),
124+
"Mode": stat.Mode().String(),
125+
"ModTime": stat.ModTime(),
126+
"IsDir": stat.IsDir(),
127+
"Sys": stat.Sys(),
128+
}
129+
}
130+
131+
func pathCommonClean(path string) string {
132+
return filepath.Clean(os.ExpandEnv(path))
133+
}
134+
135+
func PathIsDir(path string) bool {
136+
path = pathCommonClean(path)
137+
stat, err := os.Stat(path)
138+
if err != nil {
139+
return false
140+
}
141+
return stat.IsDir()
142+
}
143+
144+
func PathIsFile(path string) bool {
145+
path = pathCommonClean(path)
146+
stat, err := os.Stat(path)
147+
if err != nil {
148+
return false
149+
}
150+
return !stat.IsDir()
151+
}
152+
153+
func PathExists(path string) bool {
154+
path = pathCommonClean(path)
155+
_, err := os.Stat(path)
156+
return !os.IsNotExist(err)
157+
}
158+
159+
func FileRead(path string) string {
160+
path = pathCommonClean(path)
161+
info, err := os.Stat(path)
162+
if err != nil {
163+
if os.IsNotExist(err) {
164+
return ""
165+
} else {
166+
panic(fmt.Errorf("file not found: %s", path))
167+
}
168+
}
169+
if info.IsDir() {
170+
panic(fmt.Errorf("cannot read a directory: %s", path))
171+
}
172+
nBytes := int(info.Size())
173+
return FileReadN(nBytes, path)
174+
}
175+
176+
func FileReadN(nBytes int, path string) string {
177+
path = pathCommonClean(path)
178+
f, err := os.Open(path)
179+
if err != nil {
180+
panic(err)
181+
}
182+
defer f.Close()
183+
data := make([]byte, nBytes)
184+
n, err := f.Read(data)
185+
if err != nil {
186+
panic(err)
187+
}
188+
return string(data[:n])
189+
}
190+
191+
func TypeOf(v interface{}) string {
192+
return fmt.Sprintf("%T", v)
193+
}

testFiles/ls-like.tmpl

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{{- $files := fileGlob "./*/*" -}}
2+
{{- range $path := $files }}
3+
{{- $stat := fileStat $path }}
4+
{{- $username := (env "USERNAME" | default (env "USER") )}}
5+
{{- $usernameFString := printf "%s%d%s " "%-" (len $username) "s"}}
6+
{{ printf "%-12s" $stat.Mode }}{{ printf $usernameFString $username }}{{ pathAbsolute $path}}
7+
{{- end }}

0 commit comments

Comments
 (0)