Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PkgImporter to vm.Options for handling import statement #362

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ipsusila
Copy link
Contributor

@ipsusila ipsusila commented Apr 3, 2025

If specified, it will handle import statement through vm.Importer interface. This patch adds capability to specify only certains std packages are available to the script. For backward compatibility, if Options or Options.PkgImporter is not specified, vm will looking for package/types from env.Packages and env.PackageTypes.

Use cases example:

// 1. "github.com/mattn/anko/packages" is not imported
// No packages will be available for import
_, err := vm.ExecuteContext(ctx, en, nil, src)
_, err := vm.ExecuteContext(ctx, en, &vm.Options{Debug: true}, src)

// 2. "github.com/mattn/anko/packages" is imported explicitly
// All packages will be available for import statement
_, err := vm.ExecuteContext(ctx, en, nil, src)
_, err := vm.ExecuteContext(ctx, en, &vm.Options{Debug: true}, src)

// 3. "github.com/mattn/anko/packages" is imported explicitly
// All packages will be available for import statement. 
// Access are safe for concurrent usage.
_, err := vm.ExecuteContext(ctx, en, &vm.Options{PkgImporter: vm.NewStdPackagesImporter()}, src)

// 4. "github.com/mattn/anko/packages" is imported explicitly
// Only package `fmt` and `time` will be available for import
_, err := vm.ExecuteContext(ctx, en, &vm.Options{PkgImporter: vm.NewStdPackagesImporter("fmt", "time")}, src)

// 5. Import custom package, no std packages
_, err := vm.ExecuteContext(ctx, en, &vm.Options{PkgImporter: vm.NewPackagesImporter(pkg, pkgTypes)}, src)

// 6. "github.com/mattn/anko/packages" is imported explicitly
// Import custom package AND std packages
_, err := vm.ExecuteContext(ctx, en, &vm.Options{PkgImporter: vm.NewPackagesWithStdImporter(pkg, pkgTypes, "fmt", "io", "time")}, src)

Probably related to issue #358

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant