Skip to content

Commit

Permalink
Get current module location using runtime.CaptureCallStack(). Code cl…
Browse files Browse the repository at this point in the history
…eanups and optimisations. See #18.
  • Loading branch information
dop251 committed Jul 27, 2020
1 parent 8b60149 commit f195c6d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
11 changes: 10 additions & 1 deletion require/module_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ func TestResolve(t *testing.T) {
"/node_modules/a/file.js": `exports.name = "app12"`,
"/app13/app13.js": `exports.name = require('b/file.js').name`,
"/node_modules/b/file.js": `exports.name = "app13"`,
"node_modules/app14/index.js": `exports.name = "app14"`,
"../node_modules/app15/index.js": `exports.name = "app15"`,
}

for i, tc := range []struct {
Expand Down Expand Up @@ -268,13 +270,20 @@ func TestResolve(t *testing.T) {
{"/home/src", "./app11/a/b/c/app11.js", true, "name", "app11"},
{"/", "./app12", true, "name", "app12"},
{"/", "./app13/app13", true, "name", "app13"},
{".", "app14", true, "name", "app14"},
{"..", "nonexistent", false, "", ""},
} {
vm, mod, err := testRequire(tc.src, tc.path, globalFolders, fs)
if err != nil {
if tc.ok {
t.Errorf("%v: require() failed: %v", i, err)
t.Errorf("%d: require() failed: %v", i, err)
}
continue
} else {
if !tc.ok {
t.Errorf("%d: expected to fail, but did not", i)
continue
}
}
f := mod.ToObject(vm).Get(tc.field)
if f == nil {
Expand Down
13 changes: 10 additions & 3 deletions require/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ func (r *RequireModule) resolve(path string) (module *js.Object, err error) {
start = r.getCurrentModulePath()
}

p := filepath.Join(start, path)
if strings.HasPrefix(origPath, "./") ||
strings.HasPrefix(origPath, "/") || strings.HasPrefix(origPath, "../") ||
origPath == "." || origPath == ".." {
p := filepath.Join(start, path)
if module = r.modules[p]; module != nil {
return
}
Expand All @@ -41,7 +41,6 @@ func (r *RequireModule) resolve(path string) (module *js.Object, err error) {
r.modules[p] = module
}
} else {
p := filepath.Join(start, path)
if module = r.nodeModules[p]; module != nil {
return
}
Expand Down Expand Up @@ -140,7 +139,7 @@ func (r *RequireModule) loadNodeModules(path, start string) (module *js.Object,
return
}
}
for ; start != ""; start = filepath.Dir(start) {
for {
var p string
if filepath.Base(start) != "node_modules" {
p = filepath.Join(start, "node_modules")
Expand All @@ -150,6 +149,14 @@ func (r *RequireModule) loadNodeModules(path, start string) (module *js.Object,
if module, err = r.loadNodeModule(path, p); err == nil {
return
}
if start == ".." { // Dir('..') is '.'
break
}
parent := filepath.Dir(start)
if parent == start {
break
}
start = parent
}

return nil, InvalidModuleError
Expand Down

0 comments on commit f195c6d

Please sign in to comment.