-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
describe.go
79 lines (66 loc) 路 2.11 KB
/
describe.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
// Copyright 2022 Outreach Corporation. All Rights Reserved.
// Description: This file contains code for the describe command
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/rgst-io/stencil/pkg/stencil"
"github.com/urfave/cli/v2"
)
// NewDescribeCmd returns a new urfave/cli.Command for the
// describe command
func NewDescribeCmd() *cli.Command {
return &cli.Command{
Name: "describe",
Description: "Print information about a known file rendered by a template",
Action: func(c *cli.Context) error {
if c.NArg() != 1 {
return errors.New("expected exactly one argument, path to file")
}
return describeFile(c.Args().First())
},
}
}
// cleanPath ensures that a path is always relative to the current working directory
// with no .., . or other path elements.
func cleanPath(path string) (string, error) {
// make absolute so we can handle .. and other weird path things
// defaults to nothing if already absolute
path, err := filepath.Abs(path)
if err != nil {
return "", errors.Wrap(err, "failed to get absolute path")
}
// convert absolute -> relative
cwd, err := os.Getwd()
if err != nil {
return "", errors.Wrap(err, "failed to get current working directory")
}
path = "." + strings.TrimPrefix(path, cwd)
return filepath.Clean(path), nil
}
// describeFile prints information about a file rendered by a template
func describeFile(filePath string) error {
l, err := stencil.LoadLockfile("")
if err != nil {
return errors.Wrap(err, "failed to load lockfile")
}
// check if the file exists on disk before we try to find
// it in the lockfile
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return fmt.Errorf("file %q does not exist", filePath)
}
relativeFilePath, err := cleanPath(filePath)
if err != nil {
return errors.Wrap(err, "failed to clean path for searching lockfile")
}
for _, f := range l.Files {
if f.Name == relativeFilePath {
fmt.Printf("%s was created by module https://%s (template: %s)\n", f.Name, f.Module, f.Template)
return nil
}
}
return fmt.Errorf("file %q isn't created by stencil", filePath)
}