@@ -4,39 +4,63 @@ import (
44 "os"
55 "path/filepath"
66 "runtime"
7+ "strings"
78 "sync"
89)
910
10- var (
11- RootPath string
12- TypeScriptSubmodulePath string
13- TestDataPath string
14- )
15-
16- func init () {
11+ var rootPath = sync .OnceValue (func () string {
1712 _ , filename , _ , ok := runtime .Caller (0 )
1813 if ! ok {
1914 panic ("could not get current filename" )
2015 }
2116 filename = filepath .FromSlash (filename ) // runtime.Caller always returns forward slashes; https://go.dev/issues/3335, https://go.dev/cl/603275
22- RootPath = findGoMod (filepath .Dir (filename ))
23- TypeScriptSubmodulePath = filepath .Join (RootPath , "_submodules" , "TypeScript" )
24- TestDataPath = filepath .Join (RootPath , "testdata" )
25- }
2617
27- func findGoMod (dir string ) string {
28- root := filepath .VolumeName (dir )
29- for dir != root {
18+ if strings .HasPrefix (filename , "github.com/" ) {
19+ panic ("repo root cannot be found when built with -trimpath" )
20+ }
21+
22+ if ! filepath .IsAbs (filename ) {
23+ panic (filename + " is not an absolute path" )
24+ }
25+
26+ root := filepath .VolumeName (filename ) + string (filepath .Separator )
27+
28+ dir := filepath .Dir (filename )
29+ for {
3030 if _ , err := os .Stat (filepath .Join (dir , "go.mod" )); err == nil {
3131 return dir
3232 }
33+ if dir == root {
34+ break
35+ }
3336 dir = filepath .Dir (dir )
3437 }
35- panic ("could not find go.mod" )
38+
39+ panic ("could not find go.mod above " + filename )
40+ })
41+
42+ func RootPath () string {
43+ return rootPath ()
44+ }
45+
46+ var typeScriptSubmodulePath = sync .OnceValue (func () string {
47+ return filepath .Join (rootPath (), "_submodules" , "TypeScript" )
48+ })
49+
50+ func TypeScriptSubmodulePath () string {
51+ return typeScriptSubmodulePath ()
52+ }
53+
54+ var testDataPath = sync .OnceValue (func () string {
55+ return filepath .Join (rootPath (), "testdata" )
56+ })
57+
58+ func TestDataPath () string {
59+ return testDataPath ()
3660}
3761
3862var typeScriptSubmoduleExists = sync .OnceValue (func () bool {
39- p := filepath .Join (TypeScriptSubmodulePath , "package.json" )
63+ p := filepath .Join (typeScriptSubmodulePath () , "package.json" )
4064 if _ , err := os .Stat (p ); err != nil {
4165 if os .IsNotExist (err ) {
4266 return false
0 commit comments