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