思い付いたらすぐにuv initして書き始めたいが、uv init;uv venv;sourceするのが面倒臭い。.zprofileでフックしよう。
以下を.zprofileに追加して、source ~/.zprofileする。
uv() {
if [[ "$1" == "init" ]]; then
shift
local dir=""
local args=()
# 引数解析: オプション(-で始まるもの)と非オプションを分離する
while [[ $# -gt 0 ]]; do
if [[ "$1" == "--" ]]; then
# '--' 以降はすべて非オプションとして扱う
args+=("$1")
shift
if [[ -z "$dir" && $# -gt 0 ]]; then
dir="$1"
fi
while [[ $# -gt 0 ]]; do
args+=("$1")
shift
done
break
fi
case "$1" in
-p)
# -p オプションはパラメータを伴うので、その次の引数もセット
args+=("$1")
shift
if [[ $# -gt 0 ]]; then
args+=("$1")
shift
fi
;;
-*)
# その他のオプションはそのまま追加
args+=("$1")
shift
;;
*)
# 非オプション引数をディレクトリとみなす(最初の1個だけ採用)
if [[ -z "$dir" ]]; then
dir="$1"
fi
args+=("$1")
shift
;;
esac
done
# uv init に全引数(オプションとディレクトリ)を元の順序で渡す
command uv init "${args[@]}"
# uv init によりディレクトリが作成されたと仮定し、そのディレクトリに移動
if [[ -n "$dir" ]]; then
cd "$dir" || return
fi
command uv venv
if [[ -f .venv/bin/activate ]]; then
source .venv/bin/activate
else
echo "Warning: .venv/bin/activate not found."
fi
else
command uv "$@"
fi
}
Pythonのバージョンを指定する。
% uv init -p 3.13 test_uv
Initialized project `test-uv` at `/Users/rifujita/Desktop/test_uv`
Using CPython 3.13.2 interpreter at: /opt/homebrew/opt/python@3.13/bin/python3.13
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
Pythonのバージョンを指定しない。
% uv init test_uv
Initialized project `test-uv` at `/Users/rifujita/Desktop/test_uv`
Using CPython 3.11.11
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
引数の順番を変える。
% uv init test_uv -p 3.13
Initialized project `test-uv` at `/Users/rifujita/Desktop/test_uv`
Using CPython 3.13.2 interpreter at: /opt/homebrew/opt/python@3.13/bin/python3.13
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate
大丈夫かな?