Add Zk.RelPath()

pull/6/head
Mickaël Menu 3 years ago
parent a7b85eeb1e
commit 91118a21ce
No known key found for this signature in database
GPG Key ID: 53D73664CD359895

@ -35,9 +35,9 @@ func (cmd *List) Run(container *Container) error {
paths := make([]string, 0)
for _, p := range cmd.Paths {
dir, err := zk.DirAt(p)
path, err := zk.RelPath(p)
if err == nil {
paths = append(paths, dir.Name)
paths = append(paths, path)
}
}
if len(paths) > 0 {

@ -126,21 +126,34 @@ func (zk *Zk) DBPath() string {
return filepath.Join(zk.Path, ".zk/data.db")
}
// DirAt returns a Dir representation of the slip box directory at the given path.
func (zk *Zk) DirAt(path string, overrides ...ConfigOverrides) (*Dir, error) {
wrap := errors.Wrapperf("%v: not a valid slip box directory", path)
// RelPath returns the path relative to the slip box root to the given path.
func (zk *Zk) RelPath(path string) (string, error) {
wrap := errors.Wrapperf("%v: not a valid slip box path", path)
path, err := filepath.Abs(path)
if err != nil {
return nil, wrap(err)
return path, wrap(err)
}
path, err = filepath.Rel(zk.Path, path)
if err != nil {
return path, wrap(err)
}
if path == "." {
path = ""
}
return path, nil
}
name, err := filepath.Rel(zk.Path, path)
// DirAt returns a Dir representation of the slip box directory at the given path.
func (zk *Zk) DirAt(path string, overrides ...ConfigOverrides) (*Dir, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, wrap(err)
return nil, errors.Wrapf(err, "%v: not a valid slip box directory", path)
}
if name == "." {
name = ""
name, err := zk.RelPath(path)
if err != nil {
return nil, err
}
config, ok := zk.Config.Dirs[name]

@ -5,8 +5,8 @@ import (
"path/filepath"
"testing"
"github.com/mickael-menu/zk/util/test/assert"
"github.com/mickael-menu/zk/util/opt"
"github.com/mickael-menu/zk/util/test/assert"
)
func TestDBPath(t *testing.T) {
@ -16,6 +16,26 @@ func TestDBPath(t *testing.T) {
assert.Equal(t, zk.DBPath(), filepath.Join(wd, ".zk/data.db"))
}
func TestRelativePathFromGivenPath(t *testing.T) {
// The tests are relative to the working directory, for convenience.
wd, _ := os.Getwd()
zk := &Zk{Path: wd}
for path, expected := range map[string]string{
"log": "log",
"log/sub": "log/sub",
"log/sub/..": "log",
"log/sub/../sub": "log/sub",
filepath.Join(wd, "log"): "log",
filepath.Join(wd, "log/sub"): "log/sub",
} {
actual, err := zk.RelPath(path)
assert.Nil(t, err)
assert.Equal(t, actual, expected)
}
}
func TestDirAtGivenPath(t *testing.T) {
// The tests are relative to the working directory, for convenience.
wd, _ := os.Getwd()

Loading…
Cancel
Save