Repository navigation
Expand file tree
/
Copy pathgitsync
More file actions
executable file
·572 lines (508 loc) · 20.3 KB
/
Copy pathgitsync
File metadata and controls
executable file
·572 lines (508 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#!/usr/bin/env bash
# gitsync - Automate add/commit/pull(rebase)/push across GitHub accounts; auto-stage new files, rebase remote changes, handle conflicts, and auto-update the README table for repo after commits.
# ──────────────────────────────────────────────────────
# Author: Don Ferris
# Created: [15-10-2025]
# Current Revision: v2.6
# ──────────────────────────────────────────────────────
# Revision History
# ----------------
# v2.6 — 2025-10-24 — [NEW FEATURE] add -m "commit message" runtime option; https://github.com/copilot/c/c5274c01-1515-4dbc-84e8-986126d37384
# v2.5 — 2025-10-24 — [REFINEMENT] Only delete .git/next.commit after the main push succeeds; if you override the suggested message, mark next.commit for deletion after successful push.
# v2.4 — 2025-10-23 — [NEW FEATURE] Add .git/next.commit integration: gitsync automatically writes commit message (with revision number, date, changes in the revision, and the Copilot converstaion permalink) to .git/commit.next - the contents of which are displayed (as the default commit message - just hit Enter - when gitsync prompts for a commit message. A future script will allow for appending quick, simple commit messages to next.commit so that changes to multiple files will be properly documented.
# v2.3 — 2025-10-23 — [REFINEMENT] Rewrite update_readme: single two-column table (File | Description), File column links to repo blob on current branch, escape pipes
# v2.2 — 2025-10-23 — [REFINEMENT] update_readme now commits and pushes README automatically when it changes.
# v2.1 — 2025-10-23 — [MINOR REFINEMENT] update_readme only runs when a commit was created during the sync run (to avoid unnecessary README churn).
# v2.0 — 2025-10-23 — [NEW FEATURE] Automatic documentation of new scripts! update_readme() function automatically updates the Scripts and Files table in the README, using a comment line in the script header as the description.
# v1.7 — 2025-10-22 — [NEW FEATURE] Interactive conflict handling: on rebase failure present A/B/C options (auto-recover, manual shell, abort) with automatic stash/reapply attempt.
# v1.6 — 2025-10-22 — [REFINEMENT] Preflight and auto-track behavior: automatically stage new files by default (git add --all); earlier interactive preflight replaced by automatic staging unless conflict occur[...]
# v1.5 — 2025-10-21 — [MULTIPLE REFINEMENTS] Multi-account support and .git_ID parsing hardened: allow leading comment lines in .git_ID and use first non-comment mapping line; per-account SSH key selection and origin UR[...]
# v1.0 — 2025-10-20 — [INITIAL CORE] stage all changes, prompt for commit message, pull --rebase origin/current-branch, push, and optionally stash/pop untracked files to avoid interference.
########
set -euo pipefail
# Configuration
LOG_FILE="${LOG_FILE:-$HOME/gitsync.log}"
GIT_ID_FILE="${GIT_ID_FILE:-.git_ID}"
SSH_DIR="${SSH_DIR:-$HOME/.ssh}"
REPO_OWNER="don-ferris"
REPO_NAME="bash-scripts"
# Logging helper
log_message() {
local level="$1"; shift
local message="$*"
local timestamp
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local entry="$timestamp [$level] $message"
printf '%s\n' "$entry" >> "$LOG_FILE"
printf '%s\n' "$entry"
}
check_git_repo() {
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
log_message "ERROR" "This is not a Git repository. Aborting."
exit 1
fi
}
get_account_details() {
local abbrev="$1"
case "$abbrev" in
df)
GIT_USER_NAME="don-ferris"
GIT_USER_EMAIL="dev@donferris.me"
SSH_KEY_PATH="$SSH_DIR/id_ed25519-github-ssh-df"
;;
cx)
GIT_USER_NAME="convergenx"
GIT_USER_EMAIL="convergenx@donferris.me"
SSH_KEY_PATH="$SSH_DIR/id_ed25519-github-ssh-cx"
;;
ncmm)
GIT_USER_NAME="network-configurator-for-mere-mortals"
GIT_USER_EMAIL="ncmm@donferris.me"
SSH_KEY_PATH="$SSH_DIR/id_ed25519-github-ssh-ncmm"
;;
dlc)
GIT_USER_NAME="digital-lifestyle-creations"
GIT_USER_EMAIL="dev@digitallifestylecreations.com"
SSH_KEY_PATH="$SSH_DIR/id_ed25519-github-ssh-dlc"
;;
*)
log_message "ERROR" "Unknown account abbreviation '$abbrev' in $GIT_ID_FILE."
log_message "ERROR" "Valid abbreviations are: df, cx, ncmm, dlc."
exit 1
;;
esac
log_message "INFO" "Configuring for account: $GIT_USER_NAME"
}
# === README update helper (standardized header-aware) ===
update_readme() {
check_git_repo
local README="README.md"
local TMP
TMP=$(mktemp) || return 1
local BRANCH
BRANCH="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
if [ -z "$BRANCH" ]; then BRANCH="main"; fi
log_message "INFO" "Building scripts table from top-level files (File -> Description)..."
cat > "$TMP" <<'TABLE_EOF'
| File | Description |
|---|---|
TABLE_EOF
mapfile -t files < <(
{
git ls-files --full-name | awk -F/ 'NF==1'
git ls-files --others --exclude-standard --full-name | awk -F/ 'NF==1'
} | sort -u
)
for name in "${files[@]}"; do
case "$name" in
README.md|.git*|.github|.gitignore) continue ;;
esac
[ -f "$name" ] || continue
local url="https://github.com/${REPO_OWNER}/${REPO_NAME}/blob/${BRANCH}/${name}"
local file_link="[\`${name}\`](${url})"
# Collect top-of-file comments (robust to incidental blank comment lines)
local desc=""
local -a comments=()
local saw_comments=0
while IFS= read -r line; do
local tline
tline="$(printf '%s' "$line" | sed -e 's/^[[:space:]]*//')"
if [[ "$tline" =~ ^#! ]]; then
continue
fi
if [[ "$tline" =~ ^# ]]; then
saw_comments=1
local comment
comment="$(printf '%s' "$tline" | sed -e 's/^#\+//; s/^[[:space:]]*//; s/[[:space:]]*$//')"
comments+=("$comment")
continue
else
if [ "$saw_comments" -eq 1 ]; then
break
else
break
fi
fi
done < "$name"
if [ "${#comments[@]}" -gt 0 ]; then
# Remove leading incidental blank comment lines
while [ "${#comments[@]}" -gt 0 ] && [ -z "${comments[0]}" ]; do
comments=("${comments[@]:1}")
done
# New rule: if first comment matches the single-line pattern "[filename] - Description", use that.
# Match: starts with filename (case-insensitive) followed by " - " then the description
local first_comment="${comments[0]:-}"
if [ -n "$first_comment" ]; then
local lc_first_comment lc_name
lc_first_comment="$(printf '%s' "$first_comment" | tr '[:upper:]' '[:lower:]')"
lc_name="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
if printf '%s' "$first_comment" | grep -q -E "^[[:space:]]*${name}[[:space:]]*-[[:space:]]+" 2>/dev/null || \
printf '%s' "$lc_first_comment" | grep -q -E "^[[:space:]]*${lc_name}[[:space:]]*-[[:space:]]+" 2>/dev/null; then
# extract everything after the first " - "
desc="$(printf '%s' "$first_comment" | sed -E 's/^[[:space:]]*[^-]+-[[:space:]]*//')"
else
# Existing behavior: parse multi-line header (skip decorative lines, stop at divider/metadata)
local -a out_lines=()
local i=0
local n=${#comments[@]}
# If first non-empty comment equals the filename alone, skip it
local firstc="${comments[0]}"
local lc_firstc lc_n
lc_firstc="$(printf '%s' "$firstc" | tr '[:upper:]' '[:lower:]')"
lc_n="$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')"
if [ "$lc_firstc" = "$lc_n" ]; then
i=1
fi
for (( ; i < n; i++ )); do
local c="${comments[i]}"
if printf '%s' "$c" | grep -q -E '^[[:punct:][:space:]]+$'; then
continue
fi
if printf '%s' "$c" | grep -q -E '^[[:space:]]*[-─=]{5,}[[:space:]]*$'; then
break
fi
if printf '%s' "$c" | grep -q -i -E '^(author:|created:|current revision:|revision history|revision:)$'; then
break
fi
if [ -n "$c" ]; then
out_lines+=("$c")
fi
done
if [ "${#out_lines[@]}" -gt 0 ]; then
desc="$(printf '%s ' "${out_lines[@]}")"
desc="$(printf '%s' "$desc" | sed -e 's/[[:space:]]\{2,\}/ /g' -e 's/^[[:space:]]*//; s/[[:space:]]*$//')"
fi
fi
fi
fi
if [ -z "$desc" ]; then
desc="(no header)"
fi
desc="${desc//|/\\|}"
printf "| %s | %s |\n" "$file_link" "$desc" >> "$TMP"
done
local START_MARKER="<!-- SCRIPTS_TABLE_START -->"
local END_MARKER="<!-- SCRIPTS_TABLE_END -->"
# Remove legacy 4-column table block if present between BEGIN/END markers
if grep -qF '<!-- BEGIN SCRIPTS -->' "$README" && grep -qF '<!-- END SCRIPTS -->' "$README"; then
sed -i '/<!-- BEGIN SCRIPTS -->/,/<!-- END SCRIPTS -->/d' "$README"
log_message "INFO" "Removed legacy BEGIN/END SCRIPTS block from README."
fi
if grep -qF "$START_MARKER" "$README"; then
local NEWREADME
NEWREADME=$(mktemp) || { rm -f "$TMP"; return 1; }
awk -v start="$START_MARKER" -v end="$END_MARKER" -v tblfile="$TMP" '
{
lines[NR] = $0
}
END {
for (i = 1; i <= NR; i++) {
if (index(lines[i], start)) {
for (j=1;j<=i;j++) print lines[j]
while ((getline t < tblfile) > 0) print t
k = i+1
while (k <= NR && index(lines[k], end) == 0) k++
if (k <= NR) {
print lines[k]
for (j = k+1; j <= NR; j++) print lines[j]
}
exit
}
}
for (i=1;i<=NR;i++) print lines[i]
}' "$README" > "$NEWREADME"
mv "$NEWREADME" "$README"
log_message "INFO" "README updated between markers."
else
{
echo
echo "$START_MARKER"
cat "$TMP"
echo "$END_MARKER"
} >> "$README"
log_message "INFO" "Markers not found; appended table to README."
fi
rm -f "$TMP"
git add "$README"
if git diff --staged --quiet; then
log_message "INFO" "No changes to README to commit."
return 0
else
git commit -m "chore: update README scripts table"
log_message "INFO" "Committed README update."
local branch
branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
if [ -z "$branch" ]; then branch="main"; fi
if git push origin "$branch"; then
log_message "INFO" "Pushed README update to origin/$branch"
else
log_message "ERROR" "Failed to push README update to origin/$branch"
return 1
fi
fi
}
# conflict handling helper (unchanged)
handle_rebase_conflict() {
local branch="$1"
echo
echo "gitsync: pull --rebase failed (likely conflicts). Choose an option:"
echo " [A] Auto-recover: abort rebase, stash (incl untracked), pull/rebase, pop stash and auto-commit if clean"
echo " [B] Manual: drop to a shell so you can resolve conflicts (then run 'git rebase --continue')"
echo " [C] Abort: run 'git rebase --abort' and exit"
printf "Select [A/B/C]: "
IFS= read -r -n 1 choice
printf "\n"
choice="${choice^^}"
case "$choice" in
A)
log_message "INFO" "Attempting automatic recovery..."
git rebase --abort >/dev/null 2>&1 || true
local stash_name="gitsync-auto-recovery-$(date +%Y%m%d%H%M%S)"
git stash push --include-untracked -m "$stash_name"
if git pull --rebase origin "$branch"; then
log_message "INFO" "Pull/rebase succeeded after stashing."
if git stash list | grep -qF "$stash_name"; then
if git stash pop; then
log_message "INFO" "Stash popped successfully."
git add --all
if ! git diff --cached --quiet; then
git commit -m "chore: restore local changes after rebase (auto)"
log_message "INFO" "Committed restored local changes."
fi
return 0
else
log_message "WARN" "Conflicts occurred while popping stash. Please resolve manually."
return 1
fi
fi
return 0
else
log_message "ERROR" "Automatic pull/rebase after stashing failed."
return 1
fi
;;
B)
log_message "INFO" "Entering interactive shell for manual resolution. Resolve conflicts, then run 'git rebase --continue'."
$SHELL
return 0
;;
C)
log_message "INFO" "Aborting rebase and exiting."
git rebase --abort >/dev/null 2>&1 || true
return 2
;;
*)
log_message "WARN" "Invalid choice; aborting."
return 2
;;
esac
}
# --- Main sync flow ---
# Accept an optional commit message via runtime flag -m "message"
sync_repo() {
# Optional first parameter: explicit commit message passed via -m/--message
local passed_msg="${1:-}"
check_git_repo
if [ ! -f "$GIT_ID_FILE" ]; then
log_message "ERROR" "Missing $GIT_ID_FILE in this directory."
log_message "ERROR" "Please run '$0 --id' to initialize this repo or create the file manually."
log_message "ERROR" "Format: [repo_name] | [abbrev]"
exit 1
fi
local id_line
id_line="$(grep -v '^[[:space:]]*#' "$GIT_ID_FILE" | sed -n '1p' || true)"
if [ -z "$id_line" ]; then
log_message "ERROR" "$GIT_ID_FILE does not contain a valid mapping line (after skipping comments)."
exit 1
fi
local remote_repo_name account_abbrev
remote_repo_name="$(printf '%s' "$id_line" | awk -F ' *\\| *' '{print $1}')"
account_abbrev="$(printf '%s' "$id_line" | awk -F ' *\\| *' '{print $2}')"
if [ -z "$remote_repo_name" ] || [ -z "$account_abbrev" ]; then
log_message "ERROR" "Invalid $GIT_ID_FILE format. Expected '[repo_name] | [abbrev]'."
exit 1
fi
get_account_details "$account_abbrev"
if [ ! -f "$SSH_KEY_PATH" ]; then
log_message "ERROR" "SSH key not found at $SSH_KEY_PATH"
exit 1
fi
export GIT_SSH_COMMAND="ssh -i $SSH_KEY_PATH -o IdentitiesOnly=yes"
git config user.name "$GIT_USER_NAME"
git config user.email "$GIT_USER_EMAIL"
local branch
branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
if [ -z "$branch" ]; then branch="main"; fi
local expected_origin="git@github.com:${GIT_USER_NAME}/${remote_repo_name}.git"
local current_origin
current_origin="$(git remote get-url origin 2>/dev/null || true)"
if [ "$current_origin" != "$expected_origin" ]; then
log_message "WARN" "Remote 'origin' URL is incorrect or missing."
if [ -z "$current_origin" ]; then
log_message "INFO" "Adding remote 'origin': $expected_origin"
git remote add origin "$expected_origin"
else
log_message "INFO" "Updating remote 'origin' to: $expected_origin"
git remote set-url origin "$expected_origin"
fi
fi
# Auto-track new files: stage everything
log_message "INFO" "Staging all changes (including new files)."
git add --all
local commit_made=false
local delete_next_after_push=false
if ! git diff --cached --quiet; then
log_message "INFO" "Staged changes detected."
# If .git/next.commit exists use it as default commit message (only used when prompting)
local next_commit_file=".git/next.commit"
local default_msg=""
if [ -f "$next_commit_file" ]; then
default_msg="$(cat "$next_commit_file")"
fi
local commit_message=""
if [ -n "$passed_msg" ]; then
# User supplied -m at runtime: use it directly (do not prompt).
commit_message="$passed_msg"
# Treat this as an explicit override: mark next.commit for deletion after successful push
delete_next_after_push=true
echo "Using commit message provided on command-line (-m)."
else
# NEW: Clear the screen and display the contents (or not-found) before prompting
if command -v clear >/dev/null 2>&1; then
clear
fi
echo "Contents of the next-commit log:"
if [ -n "$default_msg" ]; then
printf '%s\n' "$default_msg"
else
echo "[file not found]"
fi
echo
echo "If you'd like to use this as your commit message, just press the [Enter] key."
echo
if [ -n "$default_msg" ]; then
echo
fi
if [ -n "$default_msg" ]; then
read -r -p "Enter commit message (press ENTER to accept default shown above): " commit_message
# If user accepts (empty), use default; if user enters a different message, use that.
if [ -z "$commit_message" ]; then
commit_message="$default_msg"
# user accepted default -> mark next.commit for deletion after successful push
delete_next_after_push=true
else
# user supplied a different message -> mark next.commit for deletion after successful push
delete_next_after_push=true
fi
else
read -r -p "Enter commit message: " commit_message
if [ -z "$commit_message" ]; then
log_message "ERROR" "Commit message cannot be empty. Aborting."
exit 1
fi
fi
fi
git commit -m "$commit_message"
commit_made=true
else
log_message "INFO" "No staged changes to commit."
fi
log_message "INFO" "Pulling remote changes with rebase..."
if git pull --rebase origin "$branch"; then
log_message "INFO" "Pull/rebase succeeded."
else
log_message "ERROR" "Pull/rebase failed (conflicts?)."
handle_rebase_conflict "$branch"
local rc=$?
if [ "$rc" -eq 0 ]; then
log_message "INFO" "Conflict handling succeeded; continuing."
elif [ "$rc" -eq 1 ]; then
log_message "WARN" "Recovery attempted but unresolved conflicts remain. Please resolve manually."
exit 1
else
log_message "INFO" "User aborted conflict handling. Exiting."
exit 0
fi
fi
# Push local commits (wrap in conditional so we can react to success/failure)
log_message "INFO" "Pushing changes to origin/$branch..."
if git push origin "$branch"; then
log_message "INFO" "Pushed commits to origin/$branch"
# Only delete .git/next.commit if requested and the push succeeded
if [ "$delete_next_after_push" = true ] && [ -f ".git/next.commit" ]; then
rm -f ".git/next.commit"
log_message "INFO" "Deleted .git/next.commit after successful push."
fi
else
log_message "ERROR" "Failed to push commits to origin/$branch"
log_message "INFO" "Leaving .git/next.commit intact (if present) so you can retry or inspect it."
exit 1
fi
if [ "$commit_made" = true ]; then
log_message "INFO" "Local commit created; regenerating README table..."
if ! update_readme; then
log_message "WARN" "update_readme failed or returned an error."
fi
else
log_message "INFO" "No local commit created; skipping README update."
fi
log_message "SUCCESS" "Sync complete for $GIT_USER_NAME/$remote_repo_name on branch $branch"
}
# Placeholder initialization function
initialize_repos() {
log_message "INFO" "initialize_repos called (placeholder)"
:
}
show_usage() {
cat <<'USAGE'
Usage: gitsync [OPTIONS] [COMMAND]
Options:
-m "message" Provide a commit message at runtime (non-interactive). If supplied, gitsync will use this message and will not prompt.
Commands:
(no command) Syncs current repository (auto-add, commit, pull --rebase, push).
--id Interactive repo initialization (create .git_ID files).
--update-readme Regenerate README table and commit+push it.
--help Show this help message.
USAGE
}
main() {
# Parse -m/--message anywhere on the command line and collect remaining args as command
local COMMIT_MSG_ARG=""
local -a rest_args=()
while [ $# -gt 0 ]; do
case "$1" in
-m|--message)
shift
if [ $# -eq 0 ]; then
log_message "ERROR" "Missing argument for -m/--message."
exit 1
fi
COMMIT_MSG_ARG="$1"
shift
;;
--id|--update-readme|--help)
rest_args+=("$1")
shift
;;
-*)
# Unknown short/long option
rest_args+=("$1")
shift
;;
*)
rest_args+=("$1")
shift
;;
esac
done
# Restore positional params to the (possibly reduced) rest_args
set -- "${rest_args[@]:-}"
case "${1:-}" in
--id) initialize_repos ;;
--update-readme) update_readme ;;
--help) show_usage ;;
"") sync_repo "$COMMIT_MSG_ARG" ;;
*) log_message "ERROR" "Unknown command: $1"; show_usage; exit 1 ;;
esac
}
main "$@"