Skip to content

Commit

Permalink
cmd/cue: get the working directory once at init time
Browse files Browse the repository at this point in the history
This way we don't have to get it separately in multiple places,
particularly each time that we print an error.

Signed-off-by: Daniel Martí <mvdan@mvdan.cc>
Change-Id: I305744a3984a832566a6c70a47dfd24152f3759e
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1195084
Reviewed-by: Roger Peppe <rogpeppe@gmail.com>
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
  • Loading branch information
mvdan committed May 23, 2024
1 parent fca1bcc commit 9394167
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 29 deletions.
4 changes: 1 addition & 3 deletions cmd/cue/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package cmd

import (
"fmt"
"os"

"cuelang.org/go/cue/errors"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -164,8 +163,7 @@ Run "cue help commands" for more details on tasks and workflow commands.
if !isRootCmd {
cmdline += " cmd"
}
cwd, _ := os.Getwd()
fmt.Fprint(w, errors.Details(err, &errors.Config{Cwd: cwd}))
fmt.Fprint(w, errors.Details(err, &errors.Config{Cwd: rootWorkingDir}))
fmt.Fprintln(w, `Ensure custom commands are defined in a "_tool.cue" file.`)
fmt.Fprintln(w, "Run 'cue help cmd' to list available custom commands.")
if isRootCmd {
Expand Down
6 changes: 1 addition & 5 deletions cmd/cue/cmd/fix.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,6 @@ Without any packages, fix applies to all files within a module.
}

func runFixAll(cmd *Command, args []string) error {
dir, err := os.Getwd()
if err != nil {
return err
}

var opts []fix.Option
if flagSimplify.Bool(cmd) {
opts = append(opts, fix.Simplify())
Expand All @@ -62,6 +57,7 @@ func runFixAll(cmd *Command, args []string) error {
if len(args) == 0 {
args = []string{"./..."}

dir := rootWorkingDir
for {
if _, err := os.Stat(filepath.Join(dir, "cue.mod")); err == nil {
args = appendDirs(args, filepath.Join(dir, "cue.mod", "gen"))
Expand Down
9 changes: 4 additions & 5 deletions cmd/cue/cmd/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ Directories named "cue.mod" and those beginning with "." and "_" are skipped unl
given as explicit arguments.
`,
RunE: mkRunE(c, func(cmd *Command, args []string) error {
cwd, _ := os.Getwd()
check := flagCheck.Bool(cmd)
doDiff := flagDiff.Bool(cmd)

Expand Down Expand Up @@ -86,7 +85,7 @@ given as explicit arguments.
continue
}

wasModified, err := formatFile(file, formatOpts, cwd, doDiff, check, cmd)
wasModified, err := formatFile(file, formatOpts, doDiff, check, cmd)
if err != nil {
return err
}
Expand Down Expand Up @@ -121,7 +120,7 @@ given as explicit arguments.
file.Source = contents
}

wasModified, err := formatFile(file, formatOpts, cwd, doDiff, check, cmd)
wasModified, err := formatFile(file, formatOpts, doDiff, check, cmd)
if err != nil {
return err
}
Expand Down Expand Up @@ -182,7 +181,7 @@ given as explicit arguments.

// formatFile formats a single file.
// It returns true if the file was not well formatted.
func formatFile(file *build.File, opts []format.Option, cwd string, doDiff, check bool, cmd *Command) (bool, error) {
func formatFile(file *build.File, opts []format.Option, doDiff, check bool, cmd *Command) (bool, error) {
// We buffer the input and output bytes to compare them.
// This allows us to determine whether a file is already
// formatted, without modifying the file.
Expand Down Expand Up @@ -216,7 +215,7 @@ func formatFile(file *build.File, opts []format.Option, cwd string, doDiff, chec
return false, nil
}

path, err := filepath.Rel(cwd, file.Filename)
path, err := filepath.Rel(rootWorkingDir, file.Filename)
if err != nil {
path = file.Filename
}
Expand Down
5 changes: 1 addition & 4 deletions cmd/cue/cmd/modget.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ func runModGet(cmd *Command, args []string) error {
func findModuleRoot() (string, error) {
// TODO this logic is duplicated in multiple places. We should
// consider deduplicating it.
dir, err := os.Getwd()
if err != nil {
return "", err
}
dir := rootWorkingDir
for {
if _, err := os.Stat(filepath.Join(dir, "cue.mod")); err == nil {
return dir, nil
Expand Down
7 changes: 1 addition & 6 deletions cmd/cue/cmd/modinit.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,7 @@ func runModInit(cmd *Command, args []string) (err error) {
}
}

cwd, err := os.Getwd()
if err != nil {
return err
}

mod := filepath.Join(cwd, "cue.mod")
mod := filepath.Join(rootWorkingDir, "cue.mod")
if info, err := os.Stat(mod); err == nil {
if !info.IsDir() {
return fmt.Errorf("cue.mod files are no longer supported; use cue.mod/module.cue")
Expand Down
20 changes: 14 additions & 6 deletions cmd/cue/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,14 +267,25 @@ For more information on writing CUE configuration files see cuelang.org.`,

var rootContextOptions []cuecontext.Option

// rootWorkingDir avoids repeated calls to [os.Getwd] in cmd/cue.
// If we can't figure out the current directory, something is very wrong,
// and there's no point in continuing to run a command.
var rootWorkingDir = func() string {
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "cannot get current directory: %v\n", err)
os.Exit(1)
}
return wd
}()

// Main runs the cue tool and returns the code for passing to os.Exit.
func Main() int {
cmd, _ := New(os.Args[1:])
if err := cmd.Run(backgroundContext()); err != nil {
if err != ErrPrintedError {
cwd, _ := os.Getwd()
errors.Print(os.Stderr, err, &errors.Config{
Cwd: cwd,
Cwd: rootWorkingDir,
ToSlash: testing.Testing(),
})
}
Expand Down Expand Up @@ -350,12 +361,9 @@ func printError(cmd *Command, err error) {
format := func(w io.Writer, format string, args ...interface{}) {
p.Fprintf(w, format, args...)
}

// TODO(mvdan): call os.Getwd only once at the start of the process.
cwd, _ := os.Getwd()
errors.Print(cmd.Stderr(), err, &errors.Config{
Format: format,
Cwd: cwd,
Cwd: rootWorkingDir,
ToSlash: testing.Testing(),
})
}
Expand Down

0 comments on commit 9394167

Please sign in to comment.