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