use std::env;
use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
pub const CD_ENV: &str = "VKIT_WT_CD_FILE";
pub const EXEC_ENV: &str = "VKIT_WT_EXEC_FILE";
pub fn write_cd(path: &Path) -> Result<bool> {
let Some(file) = env::var_os(CD_ENV) else {
return Ok(false);
};
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
env::current_dir()?.join(path)
};
fs::write(&file, abs.to_string_lossy().as_bytes())
.with_context(|| format!("写入 CD 指令失败:{}", Path::new(&file).display()))?;
Ok(true)
}
pub fn write_exec(script: &str) -> Result<bool> {
let Some(file) = env::var_os(EXEC_ENV) else {
return Ok(false);
};
fs::write(&file, script.as_bytes())
.with_context(|| format!("写入 EXEC 指令失败:{}", Path::new(&file).display()))?;
Ok(true)
}
pub fn print_init(shell: &str) -> Result<()> {
match shell {
"zsh" | "bash" => {
print!("{BASH_ZSH_INIT}");
}
"fish" => {
print!("{FISH_INIT}");
}
other => anyhow::bail!("暂不支持 shell:{other}(可用 zsh / bash / fish)"),
}
Ok(())
}
const BASH_ZSH_INIT: &str = r#"# vkit worktree shell integration — eval "$(vkit wt shell-init zsh)"
vkit-wt() {
local cd_file exec_file exit_code=0
cd_file="$(mktemp)"
exec_file="$(mktemp)"
VKIT_WT_CD_FILE="$cd_file" VKIT_WT_EXEC_FILE="$exec_file" command vkit wt "$@" || exit_code=$?
if [[ -s "$cd_file" ]]; then
builtin cd -- "$(<"$cd_file")" || {
local cd_exit=$?
[[ $exit_code -eq 0 ]] && exit_code=$cd_exit
}
fi
if [[ -s "$exec_file" ]]; then
# shellcheck disable=SC1090
source "$exec_file" || {
local src_exit=$?
[[ $exit_code -eq 0 ]] && exit_code=$src_exit
}
fi
rm -f "$cd_file" "$exec_file"
return "$exit_code"
}
alias vwt=vkit-wt
"#;
const FISH_INIT: &str = r#"# vkit worktree shell integration — vkit wt shell-init fish | source
function vkit-wt
set -l cd_file (mktemp)
set -l exec_file (mktemp)
set -l exit_code 0
env VKIT_WT_CD_FILE="$cd_file" VKIT_WT_EXEC_FILE="$exec_file" command vkit wt $argv
or set exit_code $status
if test -s "$cd_file"
cd (cat "$cd_file"); or set exit_code $status
end
if test -s "$exec_file"
source "$exec_file"; or set exit_code $status
end
rm -f "$cd_file" "$exec_file"
return $exit_code
end
alias vwt=vkit-wt
"#;