diff --git a/desktop/internal/buildprocess/process.go b/desktop/internal/buildprocess/process.go index 18d836b157..d6774d8f87 100644 --- a/desktop/internal/buildprocess/process.go +++ b/desktop/internal/buildprocess/process.go @@ -12,6 +12,8 @@ import ( "io" "os" "os/exec" + "path/filepath" + "runtime" "sync" "sync/atomic" "time" @@ -101,7 +103,7 @@ func Start(ctx context.Context, spec Spec, observe func(Stream, string)) (*Proce } command := exec.Command(spec.Executable, spec.Arguments...) command.Dir = spec.WorkingDirectory - command.Env = mergedEnvironment(spec.Environment) + command.Env = mergedEnvironment(spec.Environment, spec.WorkingDirectory) command.Stdin = spec.Stdin command.Stdout = stdoutWrite command.Stderr = stderrWrite @@ -258,19 +260,25 @@ func stream(reader io.Reader, kind Stream, observe func(Stream, string)) { } } -func mergedEnvironment(extra map[string]string) []string { +// mergedEnvironment is the started process's environment: the login shell's +// variables, then PWD for directory, then the spec's own variables, which win. +func mergedEnvironment(extra map[string]string, directory string) []string { // The login shell's variables fill what the process lacks (loginenv). base := loginenv.Environ() - if len(extra) == 0 { + pwd := workingDirectoryVariable(directory) + if len(extra) == 0 && pwd == "" { return base } - merged := make(map[string]string, len(extra)+len(base)) + merged := make(map[string]string, len(extra)+len(base)+1) for _, entry := range base { key, value, ok := splitEnvironment(entry) if ok { merged[key] = value } } + if pwd != "" { + merged["PWD"] = pwd + } for key, value := range extra { merged[key] = value } @@ -281,6 +289,26 @@ func mergedEnvironment(extra map[string]string) []string { return environment } +// workingDirectoryVariable is the PWD a process started in directory needs, or +// "" when it needs none. On POSIX systems a process finds its directory through +// PWD when PWD names it, and through the kernel's spelling otherwise. Without +// this the process would see the host's PWD, which names another directory, and +// a tool in it would spell a directory reached through a symbolic link (macOS's +// /var is /private/var) differently from the paths the host passed it: Go, for +// one, then finds the package /var/x outside the module it found in +// /private/var/x. os/exec sets PWD the same way, but only when the command has +// no environment of its own. Windows has no PWD. +func workingDirectoryVariable(directory string) string { + if directory == "" || runtime.GOOS == "windows" { + return "" + } + absolute, err := filepath.Abs(directory) + if err != nil { + return "" + } + return absolute +} + func splitEnvironment(entry string) (string, string, bool) { for index := 0; index < len(entry); index++ { if entry[index] == '=' { diff --git a/desktop/internal/buildprocess/process_test.go b/desktop/internal/buildprocess/process_test.go index 098218779b..2f6d7e2d47 100644 --- a/desktop/internal/buildprocess/process_test.go +++ b/desktop/internal/buildprocess/process_test.go @@ -7,6 +7,8 @@ import ( "os" "os/exec" "os/signal" + "path/filepath" + "runtime" "strings" "sync" "syscall" @@ -70,6 +72,13 @@ func TestBuildProcessHelper(t *testing.T) { } fmt.Fprintf(os.Stdout, "got:%s\n", data) os.Exit(0) + case "pwd": + directory, err := os.Getwd() + if err != nil { + os.Exit(7) + } + fmt.Fprintf(os.Stdout, "PWD=%s\ngetwd=%s\n", os.Getenv("PWD"), directory) + os.Exit(0) case "bulk": chunk := strings.Repeat("x", 4096) + "\n" for i := 0; i < 128; i++ { @@ -282,3 +291,55 @@ func TestProcessReadsInjectedStdin(t *testing.T) { t.Fatalf("output = %q, want the bytes written to stdin", combined.String()) } } + +// TestProcessSeesItsDirectoryAsTheHostSpelledIt starts a process in a directory +// reached through a symbolic link. The process must find that spelling, not the +// link's target, or a tool it runs on a path under the directory would treat +// the path as outside it. +func TestProcessSeesItsDirectoryAsTheHostSpelledIt(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows has no PWD") + } + target := t.TempDir() + link := filepath.Join(t.TempDir(), "project") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + output := make(chan string, 8) + spec := processSpec(t, "pwd") + spec.WorkingDirectory = link + process, err := Start(ctx, spec, func(_ Stream, text string) { + output <- text + }) + if err != nil { + t.Fatal(err) + } + if err := process.Wait(); err != nil { + t.Fatalf("wait: %v", err) + } + close(output) + var combined strings.Builder + for text := range output { + combined.WriteString(text) + } + want := "PWD=" + link + "\ngetwd=" + link + "\n" + if combined.String() != want { + t.Fatalf("output = %q, want %q", combined.String(), want) + } +} + +// TestSpecEnvironmentKeepsItsOwnPWD keeps a PWD the provider set on purpose. +func TestSpecEnvironmentKeepsItsOwnPWD(t *testing.T) { + environment := mergedEnvironment(map[string]string{"PWD": "/chosen"}, t.TempDir()) + var values []string + for _, entry := range environment { + if key, value, ok := splitEnvironment(entry); ok && key == "PWD" { + values = append(values, value) + } + } + if len(values) != 1 || values[0] != "/chosen" { + t.Fatalf("PWD = %q, want the spec's /chosen", values) + } +} diff --git a/desktop/internal/localshell/backend_unix.go b/desktop/internal/localshell/backend_unix.go index 7cd8118e20..56e63c9244 100644 --- a/desktop/internal/localshell/backend_unix.go +++ b/desktop/internal/localshell/backend_unix.go @@ -7,6 +7,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" "os" "os/exec" + "path/filepath" "slices" "strings" "syscall" @@ -39,7 +40,11 @@ func startBackend(config Config) (backend, error) { cmd.Dir = home } } - cmd.Env = append(withoutVariables(os.Environ(), config.Unset), "TERM=xterm-256color", "COLORTERM=truecolor") + inherited := os.Environ() + if pwd := workingDirectoryVariable(cmd.Dir); pwd != "" { + inherited = append(withoutVariables(inherited, []string{"PWD"}), "PWD="+pwd) + } + cmd.Env = append(withoutVariables(inherited, config.Unset), "TERM=xterm-256color", "COLORTERM=truecolor") cmd.Env = append(cmd.Env, config.Env...) cmd.Env = withUTF8Locale(cmd.Env) size := &pty.Winsize{Cols: uint16(max(config.Cols, 1)), Rows: uint16(max(config.Rows, 1))} @@ -93,6 +98,23 @@ func startBackend(config Config) (backend, error) { }, nil } +// workingDirectoryVariable is the PWD of a shell started in directory, or "" when +// directory is unknown. A shell takes its directory from PWD when PWD names it and +// from the kernel's spelling otherwise, so without this a shell in a directory +// reached through a symbolic link (macOS's /var is /private/var) would print a +// path other than the one the user opened. The inherited PWD is the host's own +// directory, and os/exec sets PWD only for a command without an environment. +func workingDirectoryVariable(directory string) string { + if directory == "" { + return "" + } + absolute, err := filepath.Abs(directory) + if err != nil { + return "" + } + return absolute +} + // withoutVariables is environment without the named variables. func withoutVariables(environment, names []string) []string { if len(names) == 0 { diff --git a/desktop/internal/localshell/shell_unix_test.go b/desktop/internal/localshell/shell_unix_test.go index 81072f3b06..4d152f47e8 100644 --- a/desktop/internal/localshell/shell_unix_test.go +++ b/desktop/internal/localshell/shell_unix_test.go @@ -5,6 +5,7 @@ package localshell import ( "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -68,6 +69,53 @@ func TestShellStartsInTheRequestedDirectoryWithTheTerminalType(t *testing.T) { } } +// A project opened through a symbolic link is the directory the user named: the +// shell's pwd keeps the link instead of the kernel's spelling of the target. +func TestShellSeesItsDirectoryAsTheHostSpelledIt(t *testing.T) { + link := filepath.Join(t.TempDir(), "project") + if err := os.Symlink(t.TempDir(), link); err != nil { + t.Fatal(err) + } + shell, wakes := start(t, Config{Dir: link}) + shell.Write([]byte("echo dir=$(pwd)\n")) + output := until(t, shell, wakes, "dir=/") + if !strings.Contains(output, "dir="+link+"\r\n") { + t.Fatalf("pwd = %q, want %s", output, link) + } +} + +// A plugin terminal's own PWD replaces the directory's, and one it unsets is not +// passed at all. env prints what the program received, which a shell would rewrite. +func TestPluginTerminalKeepsItsOwnPWD(t *testing.T) { + for _, test := range []struct { + name string + config Config + want []string + }{ + {"set", Config{Env: []string{"PWD=/chosen"}}, []string{"PWD=/chosen"}}, + {"unset", Config{Unset: []string{"PWD"}}, nil}, + } { + t.Run(test.name, func(t *testing.T) { + config := test.config + config.Shell, config.Args, config.Dir, config.Cols, config.Rows = "/usr/bin/env", []string{}, t.TempDir(), 80, 24 + shell, err := Start(config) + if err != nil { + t.Fatal(err) + } + defer shell.Close() + var got []string + for _, line := range strings.Split(waitForExit(t, shell, 5*time.Second), "\n") { + if line = strings.TrimSpace(line); strings.HasPrefix(line, "PWD=") { + got = append(got, line) + } + } + if !slices.Equal(got, test.want) { + t.Fatalf("PWD entries = %q, want %q", got, test.want) + } + }) + } +} + // An application opened from Finder inherits no locale, and the C locale it // would otherwise see makes macOS ls print "?" for every character of a // non-ASCII file name.