]> Cypherpunks.ru repositories - goredo.git/blob - tgt.go
Hash explicit type
[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 func cwdAndTgt(tgt string) (string, string) {
31         cwd, tgt := path.Split(tgt)
32         return mustAbs(cwd), tgt
33 }
34
35 type Tgt struct {
36         // a/h/t resemble zsh'es :a, :h, :t modifiers
37         a   string // absolute path
38         h   string // head of the path, directory
39         t   string // tail of the path, only name
40         rel string // relative to Cwd
41         dep string // path to dependency file
42 }
43
44 func NewTgt(tgt string) *Tgt {
45         a := mustAbs(tgt)
46         if TgtCache != nil {
47                 if t := TgtCache[a]; t != nil {
48                         return t
49                 }
50         }
51         t := Tgt{a: a}
52         t.h, t.t = path.Split(t.a)
53         if len(t.h) > 1 {
54                 t.h = t.h[:len(t.h)-1]
55         }
56         t.rel = mustRel(Cwd, t.a)
57         if TgtCache != nil {
58                 TgtCache[a] = &t
59         }
60         return &t
61 }
62
63 func (tgt *Tgt) String() string {
64         return tgt.rel
65 }
66
67 func (tgt *Tgt) Dep() string {
68         if tgt.dep == "" {
69                 tgt.dep = path.Join(tgt.h, RedoDir, tgt.t+DepSuffix)
70         }
71         return tgt.dep
72 }
73
74 func (tgt *Tgt) RelTo(cwd string) string {
75         return mustRel(cwd, tgt.a)
76 }