Add init command

This commit is contained in:
Mickaël Menu 2020-12-24 16:02:19 +01:00
parent 5e31368e37
commit bdda74362f
No known key found for this signature in database
GPG Key ID: 53D73664CD359895
4 changed files with 91 additions and 0 deletions

61
cmd/init.go Normal file
View File

@ -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
}
}

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module github.com/mickael-menu/zk
go 1.15
require github.com/alecthomas/kong v0.2.12

7
go.sum Normal file
View File

@ -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=

18
main.go Normal file
View File

@ -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)
}