Skip to content

Commit

Permalink
cue/load: avoid one stat call when loading a valid module
Browse files Browse the repository at this point in the history
We would first stat cue.mod to see whether it is a regular file,
to give a clear human-friendly error, and then open cue.mod/module.cue
to actually parse the module file declaring the module to be loaded.

In most cases, cue.mod is a directory, so we can open cue.mod/module.cue
directly and a nil error already tells us that cue.mod is a directory.
Only stat cue.mod if the cue.mod/module.cue file open fails.

This reduces one syscall when loading a valid module, which isn't much,
but still an easy improvement to make.

Finally, as Matthew suggests, add a godoc line about our behavior
when a cue.mod/module.cue file is not present.

Signed-off-by: Daniel Martí <[email protected]>
Change-Id: If387adcc860c13bd80d04c4b5cde69385934cf2d
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1198065
Unity-Result: CUE porcuepine <[email protected]>
Reviewed-by: Matthew Sackman <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
mvdan committed Jul 19, 2024
1 parent 28c6219 commit efdb072
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions cue/load/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,19 +400,21 @@ func (c Config) complete() (cfg *Config, err error) {
// loadModule loads the module file, resolves and downloads module
// dependencies. It sets c.Module if it's empty or checks it for
// consistency with the module file otherwise.
//
// Note that this function is a no-op if a module file does not exist,
// as it is still possible to load CUE without a module.
func (c *Config) loadModule() error {
// TODO: also make this work if run from outside the module?
mod := filepath.Join(c.ModuleRoot, modDir)
info, cerr := c.fileSystem.stat(mod)
if cerr != nil {
return nil
}
if !info.IsDir() {
return fmt.Errorf("cue.mod files are no longer supported; use cue.mod/module.cue")
}
mod = filepath.Join(mod, moduleFile)
f, cerr := c.fileSystem.openFile(mod)
modDir := filepath.Join(c.ModuleRoot, modDir)
modFile := filepath.Join(modDir, moduleFile)
f, cerr := c.fileSystem.openFile(modFile)
if cerr != nil {
// If we could not load cue.mod/module.cue, check whether the reason was
// a legacy cue.mod file and give the user a clear error message.
info, cerr2 := c.fileSystem.stat(modDir)
if cerr2 == nil && !info.IsDir() {
return fmt.Errorf("cue.mod files are no longer supported; use cue.mod/module.cue")
}
return nil
}
defer f.Close()
Expand All @@ -431,7 +433,7 @@ func (c *Config) loadModule() error {
// module files have been discovered in the wild.
parseModFile = modfile.FixLegacy
}
mf, err := parseModFile(data, mod)
mf, err := parseModFile(data, modFile)
if err != nil {
return err
}
Expand Down

0 comments on commit efdb072

Please sign in to comment.