diff --git a/changelog.d/init-standard-library-module-collision.md b/changelog.d/init-standard-library-module-collision.md new file mode 100644 index 000000000..92cb3398d --- /dev/null +++ b/changelog.d/init-standard-library-module-collision.md @@ -0,0 +1,3 @@ +### Fixed + +- Prevent `nsgo init` module paths from colliding with the Go standard library (#2270 by @J4ck1e2000). diff --git a/cmd/nsgo/init.go b/cmd/nsgo/init.go index 85ac11cbf..d53cf269d 100644 --- a/cmd/nsgo/init.go +++ b/cmd/nsgo/init.go @@ -34,6 +34,15 @@ func initApp(ctx context.Context, dir, name, module, kind string) error { if _, err := os.Stat(filepath.Join(dir, "nsgo.yaml")); err == nil { return fmt.Errorf("init: %s already has an nsgo.yaml", rel(dir)) } + if module != "" { + standard, err := initModuleCollision(ctx, module) + if err != nil { + return err + } + if standard != "" { + return fmt.Errorf("init: -module %q conflicts with Go standard library package %q; choose a different -module, such as %q", module, standard, "example.com/"+module) + } + } id := "dev.nsgo." + strings.ToLower(regexp.MustCompile(`[^A-Za-z0-9]+`).ReplaceAllString(name, "")) slug := strings.Trim(strings.ToLower(regexp.MustCompile(`[^A-Za-z0-9]+`).ReplaceAllString(name, "-")), "-") data := initData{name, id, module, slug} diff --git a/cmd/nsgo/init_module.go b/cmd/nsgo/init_module.go index 0e912eb51..cd094e04b 100644 --- a/cmd/nsgo/init_module.go +++ b/cmd/nsgo/init_module.go @@ -15,6 +15,38 @@ import ( "text/template" ) +// A module can shadow a standard-library package at its root or beneath it. +func initModuleCollision(ctx context.Context, module string) (string, error) { + first, _, _ := strings.Cut(module, "/") + if strings.Contains(first, ".") { + return "", nil + } + args := []string{"list", "-find", "-e", "-f", "{{if .Standard}}{{.ImportPath}}{{end}}", "--", "std"} + // Listing a literal candidate too detects packages that std omits on this + // host (such as syscall/js). -e allows an absent candidate. + if module != "all" && module != "cmd" && module != "std" && + fs.ValidPath(module) && !strings.ContainsAny(module, `\:`) && !strings.Contains(module, "...") { + args = append(args, module) + } + cmd := exec.CommandContext(ctx, "go", args...) + // The caller's module, workspace and build flags must not affect the list. + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOENV=off", "GOFLAGS=", "GOTOOLCHAIN=local", "GOWORK=off") + out, err := cmd.Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && len(exitErr.Stderr) != 0 { + return "", fmt.Errorf("init: list Go standard library packages: %w: %s", err, strings.TrimSpace(string(exitErr.Stderr))) + } + return "", fmt.Errorf("init: list Go standard library packages: %w", err) + } + for path := range strings.FieldsSeq(string(out)) { + if suffix, ok := strings.CutPrefix(path, module); ok && (suffix == "" || suffix[0] == '/') { + return path, nil + } + } + return "", nil +} + func initModuleTemplate(ctx context.Context, dir, kind string, data initData) error { module, version, hasVersion := strings.Cut(kind, "@") domain, _, _ := strings.Cut(module, "/") @@ -24,6 +56,17 @@ func initModuleTemplate(ctx context.Context, dir, kind string, data initData) er if !hasVersion { version = "latest" } + explicitModule := data.Module != "" + if !explicitModule { + data.Module = data.Slug + standard, err := initModuleCollision(ctx, data.Module) + if err != nil { + return err + } + if standard != "" { + data.Module = "example.com/" + data.Slug + } + } moduleDir, err := downloadInitModule(ctx, module+"@"+version) if err != nil { return err @@ -34,7 +77,7 @@ func initModuleTemplate(ctx context.Context, dir, kind string, data initData) er } defer src.Close() - files, err := moduleTemplateFiles(src.FS(), data) + files, err := moduleTemplateFiles(src.FS(), data, explicitModule) if err != nil { return fmt.Errorf("init: template %s: %w", kind, err) } @@ -113,11 +156,7 @@ type moduleTemplateFile struct { } // Read and render every template before opening any destination file. -func moduleTemplateFiles(src fs.FS, data initData) ([]moduleTemplateFile, error) { - moduleFlag := data.Module != "" - if !moduleFlag { - data.Module = data.Slug - } +func moduleTemplateFiles(src fs.FS, data initData, explicitModule bool) ([]moduleTemplateFile, error) { var files []moduleTemplateFile seen := make(map[string]bool) err := fs.WalkDir(src, ".", func(name string, entry fs.DirEntry, err error) error { @@ -164,7 +203,7 @@ func moduleTemplateFiles(src fs.FS, data initData) ([]moduleTemplateFile, error) if hasModuleEntry && !hasModuleFile { return nil, fmt.Errorf("go.mod is a directory") } - if moduleFlag && !hasModuleEntry { + if explicitModule && !hasModuleEntry { var content bytes.Buffer if err := initMod.Execute(&content, data); err != nil { return nil, err diff --git a/cmd/nsgo/init_module_test.go b/cmd/nsgo/init_module_test.go index 3aca6e2dd..30139c00f 100644 --- a/cmd/nsgo/init_module_test.go +++ b/cmd/nsgo/init_module_test.go @@ -53,6 +53,38 @@ func TestInitModuleTemplate(t *testing.T) { t.Errorf("go.mod.tmpl was copied: %v", err) } + for _, app := range []struct{ name, slug, id, module string }{ + {"Time", "time", "dev.nsgo.time", "example.com/time"}, + {"My Game", "my-game", "dev.nsgo.mygame", "my-game"}, + } { + t.Run(app.name, func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "app") + if err := initApp(t.Context(), dir, app.name, "", module+"@v1.0.0"); err != nil { + t.Fatal(err) + } + for name, want := range map[string]string{ + "go.mod": "module " + app.module + "\n\ngo 1.27.3\n", + "main.go": fmt.Sprintf("package main\nfunc main() { println(%q) }\n", app.slug), + "nsgo.yaml": fmt.Sprintf("name: %q\nid: %s\nversion: 0.1.0\n", app.name, app.id), + } { + got, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil || string(got) != want { + t.Errorf("%s = %q, %v; want %q", name, got, err, want) + } + } + }) + } + + t.Run("inferred module without go.mod.tmpl", func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "app") + if err := initApp(t.Context(), dir, "Time", "", module+"@v1.1.0"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "go.mod")); !os.IsNotExist(err) { + t.Errorf("inferred module wrote go.mod: %v", err) + } + }) + dir = filepath.Join(t.TempDir(), "mygame") if err := initApp(t.Context(), dir, "", "example.com/latestgame", module); err != nil { t.Fatal(err) @@ -88,6 +120,20 @@ func TestInitModuleTemplate(t *testing.T) { } } +func TestInitModuleTemplateRejectsStandardLibraryModule(t *testing.T) { + t.Setenv("GOPROXY", "off") + t.Setenv("GOMODCACHE", t.TempDir()) + dir := filepath.Join(t.TempDir(), "app") + err := initApp(t.Context(), dir, "My Game", "time", "example.com/template@v1.0.0") + if err == nil || !strings.Contains(err.Error(), `-module "time" conflicts with Go standard library package "time"`) || + !strings.Contains(err.Error(), "choose a different -module") { + t.Errorf("init with -module time and an unavailable template: %v", err) + } + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Errorf("init created the destination: %v", err) + } +} + func addTemplateVersion(t *testing.T, proxy, module, version string, files map[string][]byte) { t.Helper() dir := filepath.Join(proxy, filepath.FromSlash(module), "@v") diff --git a/cmd/nsgo/init_test.go b/cmd/nsgo/init_test.go index 77af3b79d..79310c933 100644 --- a/cmd/nsgo/init_test.go +++ b/cmd/nsgo/init_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" ) @@ -59,6 +60,35 @@ func TestInitTemplates(t *testing.T) { } } +func TestInitBuiltinRejectsStandardLibraryModule(t *testing.T) { + t.Setenv("GOFLAGS", "-mod=vendor") + for _, module := range []string{"time", "archive", "syscall/js"} { + t.Run(module, func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "app") + err := initApp(t.Context(), dir, "My App", module, "go") + if err == nil || !strings.Contains(err.Error(), `-module "`+module+`" conflicts with Go standard library package`) || + !strings.Contains(err.Error(), "choose a different -module") { + t.Errorf("init with -module %s: %v", module, err) + } + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Errorf("init created the destination: %v", err) + } + }) + } +} + +func TestInitBuiltinAllowsNonconflictingModule(t *testing.T) { + dir := filepath.Join(t.TempDir(), "app") + const module = "time/clock" + if err := initApp(t.Context(), dir, "My App", module, "go"); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil || !strings.HasPrefix(string(got), "module "+module+"\n") { + t.Errorf("go.mod = %q, %v; want module %s", got, err, module) + } +} + func TestDirAppName(t *testing.T) { t.Chdir(t.TempDir()) if err := os.Mkdir("my.app", 0o755); err != nil { diff --git a/docs/public/en/getting-started.md b/docs/public/en/getting-started.md index 6e7b2c24b..6f82b3877 100644 --- a/docs/public/en/getting-started.md +++ b/docs/public/en/getting-started.md @@ -36,6 +36,8 @@ go tool nsgo init `go tool nsgo init -template tsx` writes a TSX app instead, and `-template mixed` a Go app whose TSX entry uses Go components of its own. +With any template, `init` rejects a `-module` path that matches a Go standard library import path or is a slash-separated prefix of one, such as `archive` for `archive/tar`. Choose a different path, such as `example.com/hello`. + ### Templates from Go modules Pass the template's module path with an optional version. An omitted version resolves to the latest version Go's module proxy can find. @@ -46,7 +48,9 @@ go tool nsgo init -template example.com/my-template@v1.2.0 -module example.com/h Publish the starter inside the module's `template/` directory. Include `nsgo.yaml` and `main.go`. The tool renders both, plus any file ending in `.tmpl`, with Go's `text/template`, and strips `.tmpl` from output names. It copies other files, including binary assets, unchanged. -Templates receive `.Name` (the app's display name), `.ID` (the generated app ID), `.Slug` (the lower-case, hyphenated name) and `.Module` (the value of `-module`, or the slug). Ship a `go.mod.tmpl` to declare the generated app's module and dependencies, since Go excludes nested `go.mod` files from module downloads. Without one, `-module` writes the same minimal `go.mod` as it does for a built-in template. +Templates receive `.Name` (the app's display name), `.ID` (the generated app ID), `.Slug` (the lower-case, hyphenated name) and `.Module`. `.Module` is the value of `-module` if given; otherwise it is the slug, prefixed with `example.com/` if the slug conflicts with the standard library. For example, an app named `Time` gets `example.com/time` without changing its slug or app ID. + +Ship a `go.mod.tmpl` to declare the generated app's module and dependencies, since Go excludes nested `go.mod` files from module downloads. Without one, `-module` writes the same minimal `go.mod` as it does for a built-in template. ## Run it diff --git a/docs/public/zh/getting-started.md b/docs/public/zh/getting-started.md index 68218fa1f..ee6849d44 100644 --- a/docs/public/zh/getting-started.md +++ b/docs/public/zh/getting-started.md @@ -36,6 +36,8 @@ go tool nsgo init `go tool nsgo init -template tsx` 会生成 TSX 应用,`-template mixed` 则生成一个入口用 TSX、内部使用 Go 组件的应用。 +无论使用哪种模板,如果 `-module` 与 Go 标准库的导入路径相同,或是以 `/` 为分隔符的路径前缀(如 `archive/tar` 的 `archive`),`init` 都会拒绝该值。请选择其他路径,例如 `example.com/hello`。 + ### 来自 Go 模块的模板 传入模板的模块路径,可以附带版本。省略版本时,使用 Go 模块代理能找到的最新版本。 @@ -46,7 +48,9 @@ go tool nsgo init -template example.com/my-template@v1.2.0 -module example.com/h 把起始项目放在模块的 `template/` 目录里发布,其中要有 `nsgo.yaml` 和 `main.go`。工具用 Go 的 `text/template` 渲染这两个文件以及所有以 `.tmpl` 结尾的文件,并去掉输出文件名里的 `.tmpl`;其他文件(包括二进制资源)原样复制。 -模板可以使用 `.Name`(应用的显示名称)、`.ID`(生成的应用 id)、`.Slug`(小写、以连字符连接的名称)和 `.Module`(`-module` 的值,未指定时为 slug)。Go 下载模块时会排除含有 `go.mod` 的子目录,所以要用 `go.mod.tmpl` 声明生成的应用的模块和依赖。没有它时,`-module` 会像内置模板一样写出一个最简的 `go.mod`。 +模板可以使用 `.Name`(应用的显示名称)、`.ID`(生成的应用 id)、`.Slug`(小写、以连字符连接的名称)和 `.Module`。指定 `-module` 时,`.Module` 使用该值;否则使用 slug。如果 slug 与标准库冲突,就在前面加上 `example.com/`。例如,名为 `Time` 的应用会得到 `example.com/time`,但 slug 和应用 id 不变。 + +Go 下载模块时会排除含有 `go.mod` 的子目录,所以要用 `go.mod.tmpl` 声明生成的应用的模块和依赖。没有它时,`-module` 会像内置模板一样写出一个最简的 `go.mod`。 ## 运行应用 diff --git a/skills/nsgo/SKILL.md b/skills/nsgo/SKILL.md index aa8a52926..e499f9cb5 100644 --- a/skills/nsgo/SKILL.md +++ b/skills/nsgo/SKILL.md @@ -31,6 +31,7 @@ go tool nsgo doctor # which targets this machine builds and runs, and wha ``` Use `-template [@version]` to scaffold from a module's published [template directory](https://nsgo.dev/docs/getting-started.md#templates-from-go-modules). +For module templates, `.Module` defaults to the app slug, prefixed with `example.com/` if it conflicts with the Go standard library. With any template, choose a `-module` that neither matches a standard library import path nor is a slash-separated prefix of one. With hot reload, saving a file embedded in a Go-only app rebuilds and restarts it; saving only TSX bundle inputs updates the running app in place. [Running and debugging](https://nsgo.dev/docs/debugging.md#run)