diff --git a/cmd/init.go b/cmd/init.go new file mode 100644 index 0000000..3ac40b4 --- /dev/null +++ b/cmd/init.go @@ -0,0 +1,61 @@ +package cmd + +import ( + "errors" + "fmt" + "os" + "path/filepath" +) + +type Init struct { + Directory string `arg optional name:"directory" default:"."` +} + +func (cmd *Init) Run() error { + path, err := filepath.Abs(cmd.Directory) + if err != nil { + return err + } + + if existingPath, err := locateZk(path); err == nil { + return fmt.Errorf("a slip box already exists in %v", existingPath) + } + + // Create .zk and .zk/templates directories. + err = os.MkdirAll(filepath.Join(path, ".zk/templates"), os.ModePerm) + if err != nil { + return err + } + + return nil +} + +var ErrNotFound = errors.New("slip box not found") + +// locate finds the root of the slip box containing the given path. +func locateZk(path string) (string, error) { + if path == "/" || path == "." { + return "", ErrNotFound + } + if !filepath.IsAbs(path) { + panic("locateZk expects an absolute path") + } + if dotPath := filepath.Join(path, ".zk"); dirExists(dotPath) { + return path, nil + } + + return locateZk(filepath.Dir(path)) +} + +func dirExists(path string) bool { + fi, err := os.Stat(path) + if err != nil { + return false + } + switch mode := fi.Mode(); { + case mode.IsDir(): + return true + default: + return false + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..710254c --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/mickael-menu/zk + +go 1.15 + +require github.com/alecthomas/kong v0.2.12 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8102a3a --- /dev/null +++ b/go.sum @@ -0,0 +1,7 @@ +github.com/alecthomas/kong v0.2.12 h1:X3kkCOXGUNzLmiu+nQtoxWqj4U2a39MpSJR3QdQXOwI= +github.com/alecthomas/kong v0.2.12/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= diff --git a/main.go b/main.go new file mode 100644 index 0000000..e3987c7 --- /dev/null +++ b/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "github.com/alecthomas/kong" + "github.com/mickael-menu/zk/cmd" +) + +var cli struct { + Init cmd.Init `cmd help:"Create a slip box in the given directory"` +} + +func main() { + ctx := kong.Parse(&cli, + kong.Name("zk"), + ) + err := ctx.Run() + ctx.FatalIfErrorf(err) +}