start 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. #!/bin/bash
  2. # Dotfiles sync script
  3. set -euo pipefail
  4. # Configuration
  5. hostname_id=$(uname -n)
  6. checkout_dir=$HOME/.dofiles
  7. script_dir=$checkout_dir/dotfiles
  8. dots_dir=$checkout_dir/dotfiles/dots
  9. dots_host_dir=$checkout_dir/dotfiles/dots.$hostname_id
  10. repo="https://git.capella.pro/capella/dotfiles.git"
  11. ProgName=$(basename "$0")
  12. # Colors for output
  13. RED='\033[0;31m'
  14. GREEN='\033[0;32m'
  15. YELLOW='\033[1;33m'
  16. NC='\033[0m' # No Color
  17. # Logging functions
  18. log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
  19. log_warn() { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
  20. log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
  21. # Get group names for the current host (sorted, one per line)
  22. get_groups() {
  23. local groups_file="$script_dir/groups.$hostname_id"
  24. if [[ -f "$groups_file" ]]; then
  25. grep -v '^\s*#' "$groups_file" | grep -v '^\s*$' | sort
  26. fi
  27. }
  28. # Get combined sync list (common + groups + host-specific, deduplicated)
  29. get_sync_list() {
  30. {
  31. cat "$script_dir/to_sync" 2>/dev/null || true
  32. while IFS= read -r group; do
  33. cat "$script_dir/to_sync.@$group" 2>/dev/null || true
  34. done < <(get_groups)
  35. cat "$script_dir/to_sync.$hostname_id" 2>/dev/null || true
  36. } | grep -v '^\s*$' | sort -u || true
  37. }
  38. # Resolve source path: common -> groups (alpha) -> host-specific (last wins)
  39. resolve_source() {
  40. local p="$1"
  41. local result="$dots_dir/$p"
  42. while IFS= read -r group; do
  43. if [[ -e "$script_dir/dots.@$group/$p" ]]; then
  44. result="$script_dir/dots.@$group/$p"
  45. fi
  46. done < <(get_groups)
  47. if [[ -e "$dots_host_dir/$p" ]]; then
  48. result="$dots_host_dir/$p"
  49. fi
  50. echo "$result"
  51. }
  52. # Check if a file contains @host or @group markers
  53. file_has_markers() {
  54. grep -qE '@(host|group) ' "$1" 2>/dev/null
  55. }
  56. # Check if any file in a directory tree contains markers
  57. dir_has_markers() {
  58. grep -rqlE '@(host|group) ' "$1" 2>/dev/null
  59. }
  60. # Detect the comment style from the first marker line in a file
  61. # Returns "block" for /* */ style, or the line-comment prefix (# // ; --)
  62. detect_comment_style() {
  63. local src="$1"
  64. local marker_line
  65. marker_line=$(grep -m1 -E '@(host|group) ' "$src")
  66. # Extract everything before @host or @group
  67. local prefix="${marker_line%%@*}"
  68. # Trim trailing whitespace
  69. prefix="${prefix%"${prefix##*[![:space:]]}"}"
  70. # Check if it's a block comment opener
  71. if [[ "$prefix" == "/*" ]]; then
  72. echo "block"
  73. else
  74. echo "$prefix"
  75. fi
  76. }
  77. # Process a file with @host/@group markers, outputting only matching sections
  78. process_markers() {
  79. local src="$1"
  80. local in_block=0
  81. local include_block=0
  82. # Pre-load groups into an associative array for fast lookup
  83. declare -A host_groups
  84. while IFS= read -r g; do
  85. host_groups["$g"]=1
  86. done < <(get_groups)
  87. while IFS= read -r line || [[ -n "$line" ]]; do
  88. if [[ $in_block -eq 0 ]]; then
  89. if [[ "$line" =~ @host[[:space:]]+([^[:space:]]+) ]]; then
  90. in_block=1
  91. if [[ "${BASH_REMATCH[1]}" == "$hostname_id" ]]; then
  92. include_block=1
  93. else
  94. include_block=0
  95. fi
  96. elif [[ "$line" =~ @group[[:space:]]+([^[:space:]]+) ]]; then
  97. in_block=1
  98. if [[ -v "host_groups[${BASH_REMATCH[1]}]" ]]; then
  99. include_block=1
  100. else
  101. include_block=0
  102. fi
  103. elif [[ "$line" =~ @end ]]; then
  104. # Stray @end outside a block, skip it
  105. continue
  106. else
  107. printf '%s\n' "$line"
  108. fi
  109. else
  110. if [[ "$line" =~ @end ]]; then
  111. in_block=0
  112. include_block=0
  113. elif [[ $include_block -eq 1 ]]; then
  114. printf '%s\n' "$line"
  115. fi
  116. fi
  117. done < "$src"
  118. if [[ $in_block -eq 1 ]]; then
  119. log_warn "Unclosed @host/@group block in $src"
  120. fi
  121. }
  122. # Ensure we cleanup on exit
  123. trap 'cd "$HOME"' EXIT
  124. # Create checkout directory if needed
  125. mkdir -p "$checkout_dir"
  126. sub_help(){
  127. local groups
  128. groups=$(get_groups | tr '\n' ', ' | sed 's/,$//')
  129. cat << EOF
  130. Usage: $ProgName <subcommand> [options]
  131. Subcommands:
  132. sync [--machine|--group <name>] [dot_file]
  133. Sync dotfiles (optionally add a new dotfile)
  134. --machine: add to host-specific config ($hostname_id)
  135. --group <name>: add to group-specific config
  136. list List currently synced dotfiles
  137. status Show git status of dotfiles repo
  138. Host: $hostname_id
  139. Groups: ${groups:-none}
  140. Resolution order: common -> groups (alpha) -> host-specific
  141. Common dotfiles: dots/ + to_sync
  142. Group dotfiles: dots.@<group>/ + to_sync.@<group>
  143. Host overrides: dots.$hostname_id/ + to_sync.$hostname_id
  144. In-file markers:
  145. # @host <name> ... # @end (host-specific block)
  146. # @group <name> ... # @end (group-specific block)
  147. Files with markers are processed and written (not symlinked).
  148. For help with each subcommand run:
  149. $ProgName <subcommand> -h|--help
  150. EOF
  151. }
  152. sub_sync(){
  153. # Clone repo if it doesn't exist
  154. if [[ ! -d "$checkout_dir/dotfiles/.git" ]]; then
  155. log_info "Cloning dotfiles repository..."
  156. cd "$checkout_dir"
  157. if ! git clone "$repo"; then
  158. log_error "Failed to clone repository"
  159. exit 1
  160. fi
  161. cd "$script_dir"
  162. git submodule init
  163. git submodule update
  164. fi
  165. # Navigate to script directory
  166. cd "$script_dir"
  167. # Get current branch
  168. current_branch=$(git branch --show-current)
  169. log_info "Pulling latest changes from $current_branch..."
  170. git pull origin "$current_branch" || log_warn "Git pull failed, continuing anyway"
  171. git submodule update --init --recursive
  172. # Parse flags for adding new dotfiles
  173. local machine_specific=0
  174. local group_target=""
  175. if [[ "${1:-}" == "--machine" ]]; then
  176. machine_specific=1
  177. shift
  178. elif [[ "${1:-}" == "--group" ]]; then
  179. group_target="${2:-}"
  180. if [[ -z "$group_target" ]]; then
  181. log_error "--group requires a group name"
  182. exit 1
  183. fi
  184. shift 2
  185. fi
  186. # Add new dotfile if provided
  187. if [ -n "${1:-}" ]; then
  188. local file_to_add="$1"
  189. # Validate that file exists
  190. if [[ ! -e "$HOME/$file_to_add" ]]; then
  191. log_error "File $HOME/$file_to_add does not exist"
  192. exit 1
  193. fi
  194. log_info "Adding new dotfile: $file_to_add"
  195. real_path=$(realpath "$HOME/$file_to_add")
  196. to_copy=${real_path#"$HOME/"}
  197. if [[ $machine_specific -eq 1 ]]; then
  198. target_dots_dir="$dots_host_dir"
  199. sync_file="$script_dir/to_sync.$hostname_id"
  200. log_info "Adding as host-specific ($hostname_id)"
  201. elif [[ -n "$group_target" ]]; then
  202. target_dots_dir="$script_dir/dots.@$group_target"
  203. sync_file="$script_dir/to_sync.@$group_target"
  204. log_info "Adding as group-specific (@$group_target)"
  205. else
  206. target_dots_dir="$dots_dir"
  207. sync_file="$script_dir/to_sync"
  208. fi
  209. # Create parent directory structure
  210. mkdir -p "$(dirname "$target_dots_dir/$to_copy")"
  211. # Copy to dots directory
  212. if cp -R "$real_path" "$target_dots_dir/$to_copy"; then
  213. log_info "Copied $file_to_add to $target_dots_dir/$to_copy"
  214. else
  215. log_error "Failed to copy $file_to_add"
  216. exit 1
  217. fi
  218. # Add to sync file if not already there
  219. if ! grep -qxF "$to_copy" "$sync_file" 2>/dev/null; then
  220. echo "$to_copy" >> "$sync_file"
  221. log_info "Added $to_copy to $(basename "$sync_file")"
  222. else
  223. log_info "$to_copy already in $(basename "$sync_file")"
  224. fi
  225. # Remove original and create symlink
  226. rm -rf "$real_path"
  227. ln -s "$target_dots_dir/$to_copy" "$real_path"
  228. log_info "Created symlink: $real_path -> $target_dots_dir/$to_copy"
  229. fi
  230. # Stage tracked files from all source directories
  231. log_info "Staging changes..."
  232. get_sync_list | while IFS= read -r p; do
  233. if [[ -e "$dots_dir/$p" ]]; then
  234. git add "$dots_dir/$p"
  235. fi
  236. while IFS= read -r group; do
  237. if [[ -e "$script_dir/dots.@$group/$p" ]]; then
  238. git add "$script_dir/dots.@$group/$p"
  239. fi
  240. done < <(get_groups)
  241. if [[ -e "$dots_host_dir/$p" ]]; then
  242. git add "$dots_host_dir/$p"
  243. fi
  244. done
  245. git add start to_sync
  246. # Stage host-specific, group-specific, and groups files
  247. for f in to_sync.* groups.*; do
  248. [[ -f "$f" ]] && git add "$f"
  249. done
  250. for d in dots.*/; do
  251. [[ -d "$d" ]] && git add "$d"
  252. done
  253. # Commit and push if there are changes
  254. if git diff --cached --quiet; then
  255. log_info "No changes to commit"
  256. else
  257. log_info "Committing changes..."
  258. if git commit -m "Sync: $(date '+%Y-%m-%d %H:%M:%S')"; then
  259. log_info "Pushing to remote..."
  260. git remote add origin "$repo" 2>/dev/null || true
  261. if git push -u origin "$current_branch"; then
  262. log_info "Successfully pushed changes"
  263. else
  264. log_error "Failed to push changes"
  265. exit 1
  266. fi
  267. else
  268. log_error "Failed to commit changes"
  269. exit 1
  270. fi
  271. fi
  272. # Deploy a single file: process markers or symlink
  273. deploy_file() {
  274. local src="$1"
  275. local dest="$2"
  276. mkdir -p "$(dirname "$dest")"
  277. if file_has_markers "$src"; then
  278. # File has markers — process and write (not symlink)
  279. if [[ -L "$dest" ]]; then
  280. rm "$dest"
  281. fi
  282. local comment_style
  283. comment_style=$(detect_comment_style "$src")
  284. {
  285. if [[ "$comment_style" == "block" ]]; then
  286. echo "/* DO NOT EDIT - Generated by dotsync from: $src"
  287. echo " Regenerate with: dotsync */"
  288. else
  289. echo "$comment_style DO NOT EDIT - Generated by dotsync from:"
  290. echo "$comment_style $src"
  291. echo "$comment_style Regenerate with: dotsync"
  292. fi
  293. echo ""
  294. process_markers "$src"
  295. } > "$dest.dotsync_tmp"
  296. # Only update if content changed
  297. if [[ -f "$dest" ]] && cmp -s "$dest" "$dest.dotsync_tmp"; then
  298. rm "$dest.dotsync_tmp"
  299. else
  300. [[ -e "$dest" ]] && rm "$dest"
  301. mv "$dest.dotsync_tmp" "$dest"
  302. chmod --reference="$src" "$dest"
  303. log_info "Processed: $dest (from $src)"
  304. fi
  305. else
  306. # No markers — symlink
  307. if [[ -L "$dest" ]] && [[ "$(readlink "$dest")" == "$src" ]]; then
  308. return # Already correctly linked
  309. fi
  310. if [[ -e "$dest" ]] || [[ -L "$dest" ]]; then
  311. log_warn "Removing existing $dest"
  312. rm -rf "$dest"
  313. fi
  314. if ln -s "$src" "$dest"; then
  315. log_info "Linked: $dest -> $src"
  316. else
  317. log_error "Failed to create symlink for $(basename "$dest")"
  318. fi
  319. fi
  320. }
  321. # Deploy dotfiles (symlink or process markers)
  322. log_info "Deploying dotfiles for $hostname_id..."
  323. get_sync_list | while IFS= read -r p; do
  324. local source
  325. source=$(resolve_source "$p")
  326. local destination="$HOME/$p"
  327. if [[ ! -e "$source" ]]; then
  328. log_warn "Source $source does not exist, skipping"
  329. continue
  330. fi
  331. if [[ -d "$source" ]]; then
  332. if dir_has_markers "$source"; then
  333. # Directory contains markers — expand into per-file operations
  334. # Remove directory-level symlink if present
  335. if [[ -L "$destination" ]]; then
  336. log_warn "Replacing directory symlink $destination with expanded files"
  337. rm "$destination"
  338. fi
  339. mkdir -p "$destination"
  340. # Walk all files in the source directory
  341. while IFS= read -r src_file; do
  342. local rel="${src_file#"$source/"}"
  343. deploy_file "$src_file" "$destination/$rel"
  344. done < <(find "$source" -type f | sort)
  345. else
  346. # No markers in directory — symlink the whole directory
  347. if [[ -L "$destination" ]] && [[ "$(readlink "$destination")" == "$source" ]]; then
  348. continue # Already correctly linked
  349. fi
  350. if [[ -e "$destination" ]] || [[ -L "$destination" ]]; then
  351. log_warn "Removing existing $destination"
  352. rm -rf "$destination"
  353. fi
  354. if ln -s "$source" "$destination"; then
  355. log_info "Linked: $destination -> $source"
  356. else
  357. log_error "Failed to create symlink for $p"
  358. fi
  359. fi
  360. else
  361. # Single file entry
  362. deploy_file "$source" "$destination"
  363. fi
  364. done
  365. log_info "Sync complete!"
  366. }
  367. sub_list(){
  368. echo "Host: $hostname_id"
  369. local groups
  370. groups=$(get_groups | tr '\n' ', ' | sed 's/,$//')
  371. if [[ -n "$groups" ]]; then
  372. echo "Groups: $groups"
  373. fi
  374. echo ""
  375. if [[ -f "$script_dir/to_sync" ]]; then
  376. echo "Common dotfiles (to_sync):"
  377. while IFS= read -r p; do
  378. [[ -z "$p" ]] && continue
  379. local source
  380. source=$(resolve_source "$p")
  381. local tag=""
  382. if [[ "$source" == "$dots_host_dir/"* ]]; then
  383. tag=" [override: $hostname_id]"
  384. elif [[ "$source" == *"/dots.@"* ]]; then
  385. local gname
  386. gname=$(echo "$source" | sed 's|.*dots\.@\([^/]*\)/.*|\1|')
  387. tag=" [override: @$gname]"
  388. fi
  389. local marker_tag=""
  390. if [[ -f "$source" ]] && file_has_markers "$source"; then
  391. marker_tag=" [processed]"
  392. fi
  393. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  394. echo " + $p$tag$marker_tag"
  395. else
  396. echo " - $p (not deployed)$tag$marker_tag"
  397. fi
  398. done < "$script_dir/to_sync"
  399. fi
  400. # Group-specific dotfiles
  401. while IFS= read -r group; do
  402. local gsync="$script_dir/to_sync.@$group"
  403. if [[ -f "$gsync" ]] && [[ -s "$gsync" ]]; then
  404. echo ""
  405. echo "Group dotfiles (to_sync.@$group):"
  406. while IFS= read -r p; do
  407. [[ -z "$p" ]] && continue
  408. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  409. echo " + $p"
  410. else
  411. echo " - $p (not deployed)"
  412. fi
  413. done < "$gsync"
  414. fi
  415. done < <(get_groups)
  416. # Host-specific dotfiles
  417. if [[ -f "$script_dir/to_sync.$hostname_id" ]] && [[ -s "$script_dir/to_sync.$hostname_id" ]]; then
  418. echo ""
  419. echo "Host-specific dotfiles (to_sync.$hostname_id):"
  420. while IFS= read -r p; do
  421. [[ -z "$p" ]] && continue
  422. if [[ -L "$HOME/$p" ]] || [[ -f "$HOME/$p" ]] || [[ -d "$HOME/$p" ]]; then
  423. echo " + $p"
  424. else
  425. echo " - $p (not deployed)"
  426. fi
  427. done < "$script_dir/to_sync.$hostname_id"
  428. fi
  429. }
  430. sub_status(){
  431. if [[ ! -d "$script_dir/.git" ]]; then
  432. log_error "Dotfiles repository not found"
  433. exit 1
  434. fi
  435. cd "$script_dir"
  436. log_info "Host: $hostname_id"
  437. log_info "Git status:"
  438. git status
  439. }
  440. subcommand=${1:-}
  441. case $subcommand in
  442. "" | "-h" | "--help")
  443. sub_help
  444. ;;
  445. sync|list|status)
  446. shift
  447. "sub_${subcommand}" "$@"
  448. ;;
  449. *)
  450. log_error "'$subcommand' is not a known subcommand."
  451. echo " Run '$ProgName --help' for a list of known subcommands." >&2
  452. exit 1
  453. ;;
  454. esac