1
2
3
4
5 package objabi
6
7 import (
8 "os"
9 "path/filepath"
10 "strings"
11 )
12
13
14
15
16 func WorkingDir() string {
17 var path string
18 path, _ = os.Getwd()
19 if path == "" {
20 path = "/???"
21 }
22 return filepath.ToSlash(path)
23 }
24
25
26
27
28
29
30
31
32
33
34 func AbsFile(dir, file, rewrites string) string {
35 abs := file
36 if dir != "" && !filepath.IsAbs(file) {
37 abs = filepath.Join(dir, file)
38 }
39
40 abs, rewritten := ApplyRewrites(abs, rewrites)
41 if !rewritten && hasPathPrefix(abs, GOROOT) {
42 abs = "$GOROOT" + abs[len(GOROOT):]
43 }
44
45 if abs == "" {
46 abs = "??"
47 }
48 return abs
49 }
50
51
52
53
54
55
56
57
58 func ApplyRewrites(file, rewrites string) (string, bool) {
59 start := 0
60 for i := 0; i <= len(rewrites); i++ {
61 if i == len(rewrites) || rewrites[i] == ';' {
62 if new, ok := applyRewrite(file, rewrites[start:i]); ok {
63 return new, true
64 }
65 start = i + 1
66 }
67 }
68
69 return file, false
70 }
71
72
73
74
75 func applyRewrite(path, rewrite string) (string, bool) {
76 prefix, replace := rewrite, ""
77 if j := strings.LastIndex(rewrite, "=>"); j >= 0 {
78 prefix, replace = rewrite[:j], rewrite[j+len("=>"):]
79 }
80
81 if prefix == "" || !hasPathPrefix(path, prefix) {
82 return path, false
83 }
84 if len(path) == len(prefix) {
85 return replace, true
86 }
87 if replace == "" {
88 return path[len(prefix)+1:], true
89 }
90 return replace + path[len(prefix):], true
91 }
92
93
94
95
96
97
98
99
100 func hasPathPrefix(s string, t string) bool {
101 if len(t) > len(s) {
102 return false
103 }
104 var i int
105 for i = 0; i < len(t); i++ {
106 cs := int(s[i])
107 ct := int(t[i])
108 if 'A' <= cs && cs <= 'Z' {
109 cs += 'a' - 'A'
110 }
111 if 'A' <= ct && ct <= 'Z' {
112 ct += 'a' - 'A'
113 }
114 if cs == '\\' {
115 cs = '/'
116 }
117 if ct == '\\' {
118 ct = '/'
119 }
120 if cs != ct {
121 return false
122 }
123 }
124 return i >= len(s) || s[i] == '/' || s[i] == '\\'
125 }
126
View as plain text