Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ Unix 后端(`localshell/backend_unix.go`)在 `args == nil`、令牌有效、

脚本内容是 Motty 的 `integration.go`(0ae3ba59),去掉了 Lithe 不读的输出编码、主目录和当前目录(OSC 7)上报,保留 `;motty=` 后缀和 `MOTTY_*` 变量名,方便以后同步时直接对比差异。本地启动与 Motty 的差别只在开头和结尾:目录由调用方给出(`$3`),不用 `mktemp` 和 `trap`;最后一行用 `exec` 变成 Shell,不等待它(`startScript` 的 `owned` 参数)。

bash 部分另有两处与 Motty 不同,同步时不要改回:

- PS0 用提示符转义写命令开始标记(`PS0='\e]133;C…\a'${PS0-}`),不用 `$'…'`。`$'…'` 在赋值语句的文本里就展开成 ESC 和 BEL,用户的 DEBUG trap 回显 `BASH_COMMAND` 时会把一个带本会话令牌的 C 标记原样打到终端,终端把它当成一次命令开始。PS0 显示时和 PS1 一样解码 `\e`、`\a`。
- DEBUG trap 路径(Bash 4.4 之前没有 PS0)遇到数组形式的 `PROMPT_COMMAND`,同样在首尾加入 `__motty_disarm` 和 `__motty_arm`,和 PS0 路径对数组的处理一致。原来遇到数组就整段跳过,一次命令开始都不报。systemd 257 起的 `/etc/profile.d/80-systemd-osc-context.sh`(Ubuntu 26.04 默认带)会把 `PROMPT_COMMAND` 改成数组,并在 PS0 前放命令替换;集成先读 `/etc/profile`,所以用户和 CI 都会遇到。Bash 5.1 之前只执行数组的第 0 项,这种组合下仍不上报,和原来一样。
- 回归测试:`TestIntegratedBashReportsEachCommandLineOnce`、`TestIntegratedBashDebugTrapReportsEachCommandLineOnce` 的 `array prompt command` 用例在测试自己的 `.bash_profile` 里照 systemd 的写法设置,不依赖宿主的 `/etc/profile`。

### 临时目录归 Lithe 所有,sh 变成 Shell

- Lithe 在 `wait` 里、`cmd.Wait()` 返回后删除目录(`removeRuntime`),启动失败时也删除。无论 Shell 怎么结束,包括启动文件还没跑完就被关闭、忽略挂断后被强制结束,目录都不会留下。`Done()` 关闭前目录已经删除。
Expand Down
61 changes: 31 additions & 30 deletions desktop/internal/localshell/integration_scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,44 +246,45 @@ case $(declare -p PROMPT_COMMAND 2>/dev/null) in
*) PROMPT_COMMAND=__motty_command_finished$'\n'${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}__motty_report ;;
esac
if (( __MOTTY_FORCE__ == 0 && (BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4)) )); then
PS0=$'\e]133;C__MOTTY_SUFFIX__\a'${PS0-}
# Prompt escapes, not $'...': the assignment's own text, which a user's
# DEBUG trap sees in BASH_COMMAND, must not carry the marker itself.
PS0='\e]133;C__MOTTY_SUFFIX__\a'${PS0-}
printf '\033]133;C__MOTTY_SUFFIX__\007'
else
# No PS0 before Bash 4.4: report the start of a command line from a DEBUG
# trap, which runs before every simple command. PROMPT_COMMAND ends by
# arming it, and the first command after that reports once and disarms.
# An empty Enter reruns PROMPT_COMMAND, whose first entry disarms again so
# that its own commands never count. An array PROMPT_COMMAND (Bash 5.1+) is
# not taken here; those versions have PS0.
# that its own commands never count. An array PROMPT_COMMAND, which a
# profile such as systemd's 80-systemd-osc-context.sh makes, gets the same
# first and last entries.
__motty_disarm() { local _motty_status=$?; _motty_armed=0; return "$_motty_status"; }
__motty_arm() { _motty_armed=1; }
__motty_debug() {
[[ ${_motty_armed-} == 1 && $BASH_COMMAND != __motty_disarm && -z ${COMP_POINT-} ]] || return 0
_motty_armed=0
printf '\033]133;C__MOTTY_SUFFIX__\007'
}
_motty_armed=0
case $(declare -p PROMPT_COMMAND 2>/dev/null) in
'declare -a '*) ;;
*)
__motty_disarm() { local _motty_status=$?; _motty_armed=0; return "$_motty_status"; }
__motty_arm() { _motty_armed=1; }
__motty_debug() {
[[ ${_motty_armed-} == 1 && $BASH_COMMAND != __motty_disarm && -z ${COMP_POINT-} ]] || return 0
_motty_armed=0
printf '\033]133;C__MOTTY_SUFFIX__\007'
}
_motty_armed=0
PROMPT_COMMAND=__motty_disarm$'\n'${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}__motty_arm
# Keep the user's own DEBUG trap and run it first, so that it sees
# the same $?, $_ and BASH_COMMAND as without us. trap -p is read
# through a file because a command substitution is a subshell.
trap -p DEBUG > "$_motty_runtime/debug-trap"
_motty_trap=$(<"$_motty_runtime/debug-trap")
__motty_unquote() { eval "set -- ${1#trap -- }"; _motty_trap=$1; }
if [[ -n $_motty_trap ]]; then
__motty_unquote "$_motty_trap"
trap -- "$_motty_trap"$'\n''__motty_debug' DEBUG
else
trap -- '__motty_debug' DEBUG
fi
unset -f __motty_unquote
unset _motty_trap
printf '\033]133;C__MOTTY_SUFFIX__\007'
;;
'declare -a '*) PROMPT_COMMAND=(__motty_disarm "${PROMPT_COMMAND[@]}" __motty_arm) ;;
*) PROMPT_COMMAND=__motty_disarm$'\n'${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}__motty_arm ;;
esac
# Keep the user's own DEBUG trap and run it first, so that it sees
# the same $?, $_ and BASH_COMMAND as without us. trap -p is read
# through a file because a command substitution is a subshell.
trap -p DEBUG > "$_motty_runtime/debug-trap"
_motty_trap=$(<"$_motty_runtime/debug-trap")
__motty_unquote() { eval "set -- ${1#trap -- }"; _motty_trap=$1; }
if [[ -n $_motty_trap ]]; then
__motty_unquote "$_motty_trap"
trap -- "$_motty_trap"$'\n''__motty_debug' DEBUG
else
trap -- '__motty_debug' DEBUG
fi
unset -f __motty_unquote
unset _motty_trap
printf '\033]133;C__MOTTY_SUFFIX__\007'
fi
rm -rf -- "$_motty_runtime"
unset _motty_runtime _motty_profile`
Expand Down
95 changes: 85 additions & 10 deletions desktop/internal/localshell/integration_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package localshell

import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -406,13 +408,39 @@ func TestIntegratedBashDebugTrapReportsEachCommandLineOnce(t *testing.T) {
if err != nil {
t.Skip("bash unavailable")
}
checkCommandStartReports(t, func(env []string, runtimeDir string) Config {
dir, err := os.MkdirTemp(runtimeDir, "motty-shell.")
if err != nil {
t.Fatal(err)
}
return Config{Shell: "/bin/sh", Args: integrationArgsWith(program, true, "debug-trap-token", dir), Env: env}
}, program)
for _, profile := range commandStartProfiles {
t.Run(profile.name, func(t *testing.T) {
profile.require(t, program)
checkCommandStartReports(t, func(env []string, runtimeDir string) Config {
dir, err := os.MkdirTemp(runtimeDir, "motty-shell.")
if err != nil {
t.Fatal(err)
}
return Config{Shell: "/bin/sh", Args: integrationArgsWith(program, true, "debug-trap-token", dir), Env: env}
}, program, profile.text)
})
}
}

// Bash 4.4 and later report the start of a command line from PS0. The user's
// DEBUG trap prints BASH_COMMAND, so a marker spelled out in the text of a
// startup command would be counted as a report.
func TestIntegratedBashReportsEachCommandLineOnce(t *testing.T) {
program, err := exec.LookPath("bash")
if err != nil {
t.Skip("bash unavailable")
}
if !bashAtLeast(t, program, 4, 4) {
t.Skipf("%s has no PS0", program)
}
for _, profile := range commandStartProfiles {
t.Run(profile.name, func(t *testing.T) {
profile.require(t, program)
checkCommandStartReports(t, func(env []string, _ string) Config {
return Config{Shell: program, PromptToken: "debug-trap-token", Env: env}
}, program, profile.text)
})
}
}

// The Bash at /bin/bash is the one a user who chose Bash most often gets: 3.2
Expand All @@ -424,13 +452,53 @@ func TestIntegratedSystemBashReportsEachCommandLineOnce(t *testing.T) {
}
checkCommandStartReports(t, func(env []string, _ string) Config {
return Config{Shell: "/bin/bash", PromptToken: "debug-trap-token", Env: env}
}, "/bin/bash")
}, "/bin/bash", commandStartProfiles[0].text)
}

// commandStartProfiles are the user's login profiles the command-start tests
// run under. Each sets a prompt, a prompt command and a DEBUG trap of the
// user's own.
var commandStartProfiles = []struct {
name, text string
// require skips a profile the Bash at program cannot run as written.
require func(t *testing.T, program string)
}{
{"string prompt command", commandStartProfile, func(*testing.T, string) {}},
// systemd's /etc/profile.d/80-systemd-osc-context.sh (systemd 257 and
// later, as on Ubuntu 26.04) turns PROMPT_COMMAND into an array, leaving
// element 0 for a profile that assigns a string, and puts a command
// substitution in front of PS0. Bash runs an array PROMPT_COMMAND from 5.1.
{"array prompt command", "[ -n \"$(declare -p PROMPT_COMMAND 2>/dev/null)\" ] || PROMPT_COMMAND+=('')\n" +
"__system_hook() { printf 'system-%s\\n' hook; }\nPROMPT_COMMAND+=(__system_hook)\n" +
"__system_ps0() { printf 'system-%s' ps0; }\nPS0='$(__system_ps0)'\"${PS0:-}\"\n" + commandStartProfile,
func(t *testing.T, program string) {
if !bashAtLeast(t, program, 5, 1) {
t.Skipf("%s runs only the first element of an array PROMPT_COMMAND", program)
}
}},
}

const commandStartProfile = "PS1='user-prompt> '\nPROMPT_COMMAND='printf \"user-hook\\n\"'\ntrap 'printf \"user-debug:%s\\n\" \"$BASH_COMMAND\"' DEBUG\n"

// bashAtLeast reports whether the Bash at program is at least major.minor.
func bashAtLeast(t *testing.T, program string, major, minor int) bool {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, program, "-c", `echo "${BASH_VERSINFO[0]} ${BASH_VERSINFO[1]}"`).Output()
if err != nil {
t.Fatalf("read the version of %s: %v", program, err)
}
var gotMajor, gotMinor int
if _, err := fmt.Sscan(string(out), &gotMajor, &gotMinor); err != nil {
t.Fatalf("the version of %s, %q: %v", program, out, err)
}
return gotMajor > major || gotMajor == major && gotMinor >= minor
}

func checkCommandStartReports(t *testing.T, config func(env []string, runtimeDir string) Config, program string) {
func checkCommandStartReports(t *testing.T, config func(env []string, runtimeDir string) Config, program, profile string) {
t.Helper()
home, runtimeDir := t.TempDir(), t.TempDir()
profile := "PS1='user-prompt> '\nPROMPT_COMMAND='printf \"user-hook\\n\"'\ntrap 'printf \"user-debug:%s\\n\" \"$BASH_COMMAND\"' DEBUG\n"
if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte(profile), 0o600); err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -468,6 +536,13 @@ func checkCommandStartReports(t *testing.T, config func(env []string, runtimeDir
if !strings.Contains(s.output, "user-hook\r\n") {
t.Fatalf("the user's PROMPT_COMMAND was lost: %q", s.output)
}
// The profile prints these through a format, so that its own text, which
// the user's DEBUG trap echoes, does not contain them.
for _, hook := range []string{"system-hook\r\n", "system-ps0"} {
if strings.Contains(profile, "__system_") && !strings.Contains(s.output, hook) {
t.Fatalf("the profile's %q did not run: %q", hook, s.output)
}
}
s.exit("exit 5\r", 5)
emptyDirectory(t, runtimeDir)
}
Expand Down
Loading
Loading