Home

tmpl @07ccb515849ca1a50462bf2e5059af23c14a516a - refs - log -
-
https://git.jolheiser.com/tmpl.git
Template automation
tmpl / cmd / test.go
- raw
 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
package cmd

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"go.jolheiser.com/tmpl/schema"

	"github.com/rs/zerolog/log"
	"github.com/urfave/cli/v2"
)

var Test = &cli.Command{
	Name:        "test",
	Usage:       "Test if a directory is a valid template",
	Description: "Test whether a directory is valid for use with tmpl",
	ArgsUsage:   "[path (default: \".\")]",
	Action:      runTest,
}

func runTest(ctx *cli.Context) error {
	testPath := "."
	if ctx.NArg() > 0 {
		testPath = ctx.Args().First()
	}

	var errs []string

	fi, err := os.Open(filepath.Join(testPath, "tmpl.yaml"))
	if err != nil {
		errs = append(errs, fmt.Sprintf("could not open tmpl.yaml: %v", err))
	}
	defer fi.Close()
	if err := schema.Lint(fi); err != nil {
		var rerr schema.ResultErrors
		if errors.As(err, &rerr) {
			for _, re := range rerr {
				errs = append(errs, fmt.Sprintf("%s: %s", re.Field(), re.Description()))
			}
		} else {
			errs = append(errs, fmt.Sprintf("could not lint tmpl.yaml: %v", err))
		}
	}

	fstat, err := os.Lstat(filepath.Join(testPath, "template"))
	if err != nil {
		errs = append(errs, "no template directory found")
	}
	if err == nil && !fstat.IsDir() {
		errs = append(errs, "template path is a file, not a directory")
	}

	if len(errs) > 0 {
		for _, err := range errs {
			log.Error().Msg(err)
		}
		return nil
	}

	log.Info().Msg("This is a valid tmpl template!")
	return nil
}