Skip to content

Instantly share code, notes, and snippets.

@aztack
Created November 19, 2025 09:31
Show Gist options
  • Select an option

  • Save aztack/e914916662529b322e1656515ce3f79e to your computer and use it in GitHub Desktop.

Select an option

Save aztack/e914916662529b322e1656515ce3f79e to your computer and use it in GitHub Desktop.
clone_sub
# 用法:
# clone_sub <repo-url> <remote-path> <target-path> [branch]
# 说明:
# - remote-path:可以是文件(如 .roomodes)或目录(如 src/lib)
# - target-path:
# * 如果 remote-path 是文件:
# - target-path 是已存在目录 或 以 / 结尾:复制到这个目录里
# - 否则:按“目标文件路径”处理(不会多一层目录)
# * 如果 remote-path 是目录:
# - target-path 一律当作“目标目录”使用
clone_sub() {
local repo_url="$1"
local remote_path="$2"
local target_path="$3"
local branch="${4:-main}" # 默认为 main 分支
if [[ -z "$repo_url" || -z "$remote_path" || -z "$target_path" ]]; then
echo "用法: clone_sub <repo-url> <remote-path> <target-path> [branch]" >&2
return 1
fi
# 1. 创建随机临时目录
local tmpdir
tmpdir=$(mktemp -d) || {
echo "无法创建临时目录" >&2
return 1
}
echo "使用临时目录: $tmpdir"
# 2. clone 指定分支(浅克隆)
if ! git clone --depth=1 --branch "$branch" "$repo_url" "$tmpdir"; then
echo "Git clone 失败(仓库、分支或网络问题)" >&2
rm -rf "$tmpdir"
return 1
fi
# 3. 判断是文件还是目录
local full_path="$tmpdir/$remote_path"
if [[ -f "$full_path" ]]; then
# === 远程是文件 ===
if [[ -d "$target_path" || "$target_path" == */ ]]; then
# 目标是目录(或以 / 结尾)→ 复制到目录中
mkdir -p "$target_path" || {
echo "创建目标目录失败: $target_path" >&2
rm -rf "$tmpdir"
return 1
}
if ! cp "$full_path" "$target_path/"; then
echo "复制文件失败: $remote_path -> $target_path/" >&2
rm -rf "$tmpdir"
return 1
fi
else
# 目标当作“文件路径”处理
mkdir -p "$(dirname "$target_path")" || {
echo "创建目标文件所在目录失败: $(dirname "$target_path")" >&2
rm -rf "$tmpdir"
return 1
}
if ! cp "$full_path" "$target_path"; then
echo "复制文件失败: $remote_path -> $target_path" >&2
rm -rf "$tmpdir"
return 1
fi
fi
elif [[ -d "$full_path" ]]; then
# === 远程是目录 ===
mkdir -p "$target_path" || {
echo "创建目标目录失败: $target_path" >&2
rm -rf "$tmpdir"
return 1
}
if ! cp -r "$full_path"/. "$target_path/"; then
echo "复制目录失败: $remote_path -> $target_path/" >&2
rm -rf "$tmpdir"
return 1
fi
else
echo "远程路径不存在,或既不是文件也不是目录: $remote_path" >&2
rm -rf "$tmpdir"
return 1
fi
# 4. 清理临时目录
rm -rf "$tmpdir"
echo "完成!已从分支 '$branch' 将 $remote_path 复制到 $target_path"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment