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