]> Cypherpunks.ru repositories - goredo.git/blob - path.go
Refactor target paths, less CPU, less memory, more clarity
[goredo.git] / path.go
1 package main
2
3 import (
4         "path"
5         "path/filepath"
6 )
7
8 func mustAbs(pth string) string {
9         pth, err := filepath.Abs(pth)
10         if err != nil {
11                 panic(err)
12         }
13         return pth
14 }
15
16 func mustRel(basepath, targpath string) string {
17         pth, err := filepath.Rel(basepath, targpath)
18         if err != nil {
19                 panic(err)
20         }
21         return pth
22 }
23
24 func cwdMustRel(paths ...string) string {
25         return mustRel(Cwd, path.Join(paths...))
26 }
27
28 func cwdAndTgt(tgt string) (string, string) {
29         cwd, tgt := path.Split(tgt)
30         return mustAbs(cwd), tgt
31 }
32
33 type Tgt struct {
34         // a/h/t resemble zsh'es :a, :h, :t modifiers
35         a   string // absolute path
36         h   string // head of the path, directory
37         t   string // tail of the path, only name
38         rel string // relative to Cwd
39         dep string // path to dependency file
40 }
41
42 func NewTgt(tgt string) *Tgt {
43         t := Tgt{a: mustAbs(tgt)}
44         t.h, t.t = path.Split(t.a)
45         if len(t.h) > 1 {
46                 t.h = t.h[:len(t.h)-1]
47         }
48         t.rel = mustRel(Cwd, t.a)
49         return &t
50 }
51
52 func (tgt *Tgt) String() string {
53         return tgt.rel
54 }
55
56 func (tgt *Tgt) Dep() string {
57         if tgt.dep == "" {
58                 tgt.dep = path.Join(tgt.h, RedoDir, tgt.t+DepSuffix)
59         }
60         return tgt.dep
61 }
62
63 func (tgt *Tgt) RelTo(cwd string) string {
64         return mustRel(cwd, tgt.a)
65 }