-
Notifications
You must be signed in to change notification settings - Fork 6.6k
feat: shell snapshotting #7641
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
Open
jif-oai
wants to merge
20
commits into
main
Choose a base branch
from
jif/shell-snapshot
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+729
−47
Open
feat: shell snapshotting #7641
Changes from 1 commit
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
4d119f8
test tests
jif-oai 25e0e49
Integrate it
jif-oai 888391a
More tests
jif-oai 08dbdd0
Default to false
jif-oai 356452f
fmt
jif-oai 88851e8
More work
jif-oai dc95944
Fixes
jif-oai 04f69e5
clippy
jif-oai 1267159
Fmt
jif-oai 9fb7c94
Fix one test
jif-oai 05587ed
Comments
jif-oai 7b9cbd9
Process a bunch of comments
jif-oai c05ee25
fmt
jif-oai 083f2d2
Clean
jif-oai b02847f
Clippy
jif-oai c0b2fe4
Better snapshotting
jif-oai aa3537b
Merge remote-tracking branch 'origin/main' into jif/shell-snapshot
jif-oai 7ca2071
NIT
jif-oai acb92d2
More fixes
jif-oai c12891f
More time for powershell
jif-oai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| use std::path::Path; | ||
| use std::path::PathBuf; | ||
| use std::time::Duration; | ||
|
|
||
| use anyhow::Context; | ||
| use anyhow::Result; | ||
| use anyhow::anyhow; | ||
| use anyhow::bail; | ||
| use tokio::fs; | ||
| use tokio::process::Command; | ||
| use tokio::time::timeout; | ||
|
|
||
| use crate::shell::Shell; | ||
| use crate::shell::ShellType; | ||
| use crate::shell::get_shell; | ||
|
|
||
| pub async fn write_shell_snapshot(shell_type: ShellType, output_path: &Path) -> Result<PathBuf> { | ||
| let shell = get_shell(shell_type.clone(), None) | ||
| .with_context(|| format!("No available shell for {shell_type:?}"))?; | ||
|
|
||
| let snapshot = capture_snapshot(&shell).await?; | ||
|
|
||
| if let Some(parent) = output_path.parent() { | ||
| let parent_display = parent.display(); | ||
| fs::create_dir_all(parent) | ||
| .await | ||
| .with_context(|| format!("Failed to create snapshot parent {parent_display}"))?; | ||
| } | ||
|
|
||
| let snapshot_path = output_path.display(); | ||
| fs::write(output_path, snapshot) | ||
| .await | ||
| .with_context(|| format!("Failed to write snapshot to {snapshot_path}"))?; | ||
|
|
||
| Ok(output_path.to_path_buf()) | ||
| } | ||
|
|
||
| async fn capture_snapshot(shell: &Shell) -> Result<String> { | ||
| let shell_type = shell.shell_type.clone(); | ||
| match shell_type { | ||
| ShellType::Zsh => run_shell_script(shell, zsh_snapshot_script()).await, | ||
| ShellType::Bash => run_shell_script(shell, bash_snapshot_script()).await, | ||
| ShellType::Sh => run_shell_script(shell, sh_snapshot_script()).await, | ||
| ShellType::PowerShell => run_shell_script(shell, powershell_snapshot_script()).await, | ||
| ShellType::Cmd => bail!("Shell snapshotting is not yet supported for {shell_type:?}"), | ||
| } | ||
| } | ||
|
|
||
| async fn run_shell_script(shell: &Shell, script: &str) -> Result<String> { | ||
| let args = shell.derive_exec_args(script, true); | ||
| let shell_name = shell.name(); | ||
| let output = timeout( | ||
| Duration::from_secs(10), | ||
| Command::new(&args[0]).args(&args[1..]).output(), | ||
| ) | ||
| .await | ||
| .map_err(|_| anyhow!("Snapshot command timed out for {shell_name}"))? | ||
| .with_context(|| format!("Failed to execute {shell_name}"))?; | ||
|
|
||
| if !output.status.success() { | ||
| let status = output.status; | ||
| let stderr = String::from_utf8_lossy(&output.stderr); | ||
| bail!("Snapshot command exited with status {status}: {stderr}"); | ||
| } | ||
|
|
||
| Ok(String::from_utf8_lossy(&output.stdout).into_owned()) | ||
| } | ||
|
|
||
| fn zsh_snapshot_script() -> &'static str { | ||
| r#"print '# Snapshot file' | ||
| print '# Unset all aliases to avoid conflicts with functions' | ||
| print 'unalias -a 2>/dev/null || true' | ||
| print '# Functions' | ||
| functions | ||
| print '' | ||
| setopt_count=$(setopt | wc -l | tr -d ' ') | ||
| print "setopts $setopt_count" | ||
| setopt | sed 's/^/setopt /' | ||
| print '' | ||
| alias_count=$(alias -L | wc -l | tr -d ' ') | ||
| print "aliases $alias_count" | ||
| alias -L | ||
| print '' | ||
| export_count=$(export -p | wc -l | tr -d ' ') | ||
| print "exports $export_count" | ||
| export -p | ||
| "# | ||
| } | ||
|
|
||
| fn bash_snapshot_script() -> &'static str { | ||
| r#"echo '# Snapshot file' | ||
| echo '# Unset all aliases to avoid conflicts with functions' | ||
| unalias -a 2>/dev/null || true | ||
| echo '# Functions' | ||
| declare -f | ||
| echo '' | ||
| bash_opts=$(set -o | awk '$2=="on"{print $1}') | ||
| bash_opt_count=$(printf '%s\n' "$bash_opts" | sed '/^$/d' | wc -l | tr -d ' ') | ||
| echo "setopts $bash_opt_count" | ||
| if [ -n "$bash_opts" ]; then | ||
| printf 'set -o %s\n' $bash_opts | ||
| fi | ||
| echo '' | ||
| alias_count=$(alias -p | wc -l | tr -d ' ') | ||
| echo "aliases $alias_count" | ||
| alias -p | ||
| echo '' | ||
| export_count=$(export -p | wc -l | tr -d ' ') | ||
| echo "exports $export_count" | ||
| export -p | ||
| "# | ||
| } | ||
|
|
||
| fn sh_snapshot_script() -> &'static str { | ||
| r#"echo '# Snapshot file' | ||
| echo '# Unset all aliases to avoid conflicts with functions' | ||
| unalias -a 2>/dev/null || true | ||
| echo '# Functions' | ||
| if command -v typeset >/dev/null 2>&1; then | ||
| typeset -f | ||
| elif command -v declare >/dev/null 2>&1; then | ||
| declare -f | ||
| fi | ||
| echo '' | ||
| if set -o >/dev/null 2>&1; then | ||
| sh_opts=$(set -o | awk '$2=="on"{print $1}') | ||
| sh_opt_count=$(printf '%s\n' "$sh_opts" | sed '/^$/d' | wc -l | tr -d ' ') | ||
| echo "setopts $sh_opt_count" | ||
| if [ -n "$sh_opts" ]; then | ||
| printf 'set -o %s\n' $sh_opts | ||
| fi | ||
| else | ||
| echo 'setopts 0' | ||
| fi | ||
| echo '' | ||
| if alias >/dev/null 2>&1; then | ||
| alias_count=$(alias | wc -l | tr -d ' ') | ||
| echo "aliases $alias_count" | ||
| alias | ||
| echo '' | ||
| else | ||
| echo 'aliases 0' | ||
| fi | ||
| if export -p >/dev/null 2>&1; then | ||
| export_count=$(export -p | wc -l | tr -d ' ') | ||
| echo "exports $export_count" | ||
| export -p | ||
| else | ||
| export_count=$(env | wc -l | tr -d ' ') | ||
| echo "exports $export_count" | ||
| env | sort | while IFS='=' read -r key value; do | ||
| escaped=$(printf "%s" "$value" | sed "s/'/'\"'\"'/g") | ||
| printf "export %s='%s'\n" "$key" "$escaped" | ||
| done | ||
| fi | ||
| "# | ||
| } | ||
|
|
||
| fn powershell_snapshot_script() -> &'static str { | ||
| r#"$ErrorActionPreference = 'Stop' | ||
| Write-Output '# Snapshot file' | ||
| Write-Output '# Unset all aliases to avoid conflicts with functions' | ||
| Write-Output 'Remove-Item Alias:* -ErrorAction SilentlyContinue' | ||
| Write-Output '# Functions' | ||
| Get-ChildItem Function: | ForEach-Object { | ||
| "function {0} {{`n{1}`n}}" -f $_.Name, $_.Definition | ||
| } | ||
| Write-Output '' | ||
| $aliases = Get-Alias | ||
| Write-Output ("aliases " + $aliases.Count) | ||
| $aliases | ForEach-Object { | ||
| "Set-Alias -Name {0} -Value {1}" -f $_.Name, $_.Definition | ||
| } | ||
| Write-Output '' | ||
| $envVars = Get-ChildItem Env: | ||
| Write-Output ("exports " + $envVars.Count) | ||
| $envVars | ForEach-Object { | ||
| $escaped = $_.Value -replace "'", "''" | ||
| "`$env:{0}='{1}'" -f $_.Name, $escaped | ||
| } | ||
| "# | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use tempfile::tempdir; | ||
|
|
||
| async fn get_snapshot(shell_type: ShellType) -> Result<String> { | ||
| let dir = tempdir()?; | ||
| let path = dir.path().join("snapshot.sh"); | ||
| write_shell_snapshot(shell_type, &path).await?; | ||
| let content = fs::read_to_string(&path).await?; | ||
| Ok(content) | ||
| } | ||
|
|
||
| #[cfg(target_os = "macos")] | ||
| #[tokio::test] | ||
| async fn macos_zsh_snapshot_includes_sections() -> Result<()> { | ||
| let snapshot = get_snapshot(ShellType::Zsh).await?; | ||
| assert!(snapshot.contains("# Snapshot file")); | ||
| assert!(snapshot.contains("aliases ")); | ||
| assert!(snapshot.contains("exports ")); | ||
| assert!(snapshot.contains("export CARGO")); | ||
| assert!(snapshot.contains("setopts ")); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(target_os = "linux")] | ||
| #[tokio::test] | ||
| async fn linux_bash_snapshot_includes_sections() -> Result<()> { | ||
| let snapshot = get_snapshot(ShellType::Bash).await?; | ||
| assert!(snapshot.contains("# Snapshot file")); | ||
| assert!(snapshot.contains("aliases ")); | ||
| assert!(snapshot.contains("exports ")); | ||
| assert!(snapshot.contains("export CARGO")); | ||
jif-oai marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| assert!(snapshot.contains("setopts ")); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(target_os = "linux")] | ||
| #[tokio::test] | ||
| async fn linux_sh_snapshot_includes_sections() -> Result<()> { | ||
| let snapshot = get_snapshot(ShellType::Sh).await?; | ||
| assert!(snapshot.contains("# Snapshot file")); | ||
| assert!(snapshot.contains("aliases ")); | ||
| assert!(snapshot.contains("exports ")); | ||
| assert!(snapshot.contains("export CARGO")); | ||
| assert!(snapshot.contains("setopts ")); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(target_os = "windows")] | ||
| #[tokio::test] | ||
| async fn windows_powershell_snapshot_includes_sections() -> Result<()> { | ||
jif-oai marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let snapshot = get_snapshot(ShellType::PowerShell).await?; | ||
| assert!(snapshot.contains("# Snapshot file")); | ||
| assert!(snapshot.contains("aliases ")); | ||
| assert!(snapshot.contains("exports ")); | ||
| Ok(()) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shell snapshot capture runs the shell under a 10s
timeout, but on timeout we immediately bubble an error without cancelling the spawned child.tokio::time::timeoutonly drops the future, so a login shell that hangs (e.g., because profile scripts prompt or stall) will keep running even though snapshot creation aborts, leaving a stray shell process consuming resources for the rest of the session.Useful? React with 👍 / 👎.