-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathasimov
More file actions
executable file
·1645 lines (1488 loc) · 66.7 KB
/
Copy pathasimov
File metadata and controls
executable file
·1645 lines (1488 loc) · 66.7 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -Eeu -o pipefail
# Restrict permissions on all files/dirs we create (mktemp temp files, cache dir).
# Temp files contain the full home-directory layout, so keep them private (0600/0700).
umask 077
# Temp files for tracking excluded directory sizes and pre-existing exclusions.
ASIMOV_SIZE_LOG="$(mktemp)"
ASIMOV_EXCLUDED_CACHE="$(mktemp)"
ASIMOV_PATH_CACHE_TMP=""
trap 'rm -f "$ASIMOV_SIZE_LOG" "$ASIMOV_EXCLUDED_CACHE" "$ASIMOV_PATH_CACHE_TMP"' EXIT
# Look through the local filesystem and exclude development dependencies
# from Apple Time Machine backups.
#
# Since these files can be restored easily via their respective installation
# tools, there's no reason to waste time/bandwidth on backing them up.
#
# To retrieve a full list of excluded files, you may run:
#
# sudo mdfind "com_apple_backup_excludeItem = 'com.apple.backupd'"
#
# For a full explanation, please see https://apple.stackexchange.com/a/25833/206772
#
# @author Steve Grunwell
# @license MIT
# Keep ASIMOV_VERSION in sync with CHANGELOG and package managers (e.g. Homebrew).
readonly ASIMOV_VERSION='0.10.0'
print_usage() {
printf 'Usage: asimov [--dry-run] [--verbose] [--quiet] [--stats] [--no-read-cache] [--no-write-cache] [directory]\n'
printf ' asimov prune [--quiet]\n'
printf ' asimov doctor [--quiet]\n'
printf '\n'
printf 'Exclude development dependency directories from Time Machine backups.\n'
printf '\n'
printf 'Commands:\n'
printf ' prune Report Time Machine exclusions whose directory no longer\n'
printf ' exists, and compact Asimov'\''s own cache. Read-only:\n'
printf ' it prints the removal command rather than running it\n'
printf ' doctor Check this install for problems: a shadowed binary, a\n'
printf ' leftover schedule, an unreadable cache, a bad config.\n'
printf ' Read-only; exits 1 if it finds anything\n'
printf '\n'
printf 'Options:\n'
printf ' --dry-run Print what would be excluded without changing Time Machine\n'
printf ' --verbose Show all directories including already-excluded ones\n'
printf ' --quiet Suppress all output except errors\n'
printf ' --stats Show directory sizes and total space in the summary\n'
printf ' --no-read-cache Ignore cached state; re-discover and re-verify everything (rebuilds the cache)\n'
printf ' --no-write-cache Run normally but do not persist any cache updates\n'
printf ' --full-scan Alias for --no-read-cache\n'
printf ' --no-cache Alias for --no-read-cache --no-write-cache (fully stateless run)\n'
printf ' --help Show this help and exit\n'
printf ' --version Show version and exit\n'
printf '\n'
printf 'Arguments:\n'
printf ' directory Directory to scan (default: home directory)\n'
printf '\n'
printf 'To scan additional directories on every run, add them to the config file\n'
printf '(~/.config/asimov/config) under a [scan] section:\n'
printf '\n'
printf ' [scan]\n'
printf ' extra = /private/var/www\n'
}
# Parse options (before we need ASIMOV_ROOT).
# Supports: --help, --version, --dry-run, --verbose, --quiet. Unknown options cause exit 1.
ASIMOV_DRY_RUN=
ASIMOV_VERBOSE=
ASIMOV_QUIET=
ASIMOV_STATS=
ASIMOV_NO_READ_CACHE=
ASIMOV_NO_WRITE_CACHE=
ASIMOV_SCAN_DIR=
# Subcommands are recognised only as the first argument, so that a directory
# sharing the name stays reachable as `asimov ./prune`.
ASIMOV_COMMAND=scan
case "${1:-}" in
prune) ASIMOV_COMMAND=prune; shift ;;
doctor) ASIMOV_COMMAND=doctor; shift ;;
esac
readonly ASIMOV_COMMAND
for arg in "$@"; do
case "$arg" in
--dry-run) ASIMOV_DRY_RUN=1 ;;
--verbose) ASIMOV_VERBOSE=1 ;;
--quiet) ASIMOV_QUIET=1 ;;
--stats) ASIMOV_STATS=1 ;;
# Cache controls along two axes. --full-scan and --no-cache are kept as
# back-compat aliases: --full-scan = --no-read-cache; --no-cache = both.
--no-read-cache) ASIMOV_NO_READ_CACHE=1 ;;
--no-write-cache) ASIMOV_NO_WRITE_CACHE=1 ;;
--full-scan) ASIMOV_NO_READ_CACHE=1 ;;
--no-cache) ASIMOV_NO_READ_CACHE=1; ASIMOV_NO_WRITE_CACHE=1 ;;
--help) print_usage; exit 0 ;;
--version) printf '%s\n' "$ASIMOV_VERSION"; exit 0 ;;
-*)
echo "asimov: unknown option '$arg'" >&2
print_usage >&2
exit 1
;;
*)
ASIMOV_SCAN_DIR="$arg"
;;
esac
done
readonly ASIMOV_DRY_RUN
readonly ASIMOV_VERBOSE
readonly ASIMOV_QUIET
readonly ASIMOV_STATS
readonly ASIMOV_NO_READ_CACHE
readonly ASIMOV_NO_WRITE_CACHE
if [[ -n "$ASIMOV_QUIET" && -n "$ASIMOV_VERBOSE" ]]; then
echo "asimov: --quiet and --verbose are mutually exclusive" >&2
exit 1
fi
# Named constants for size formatting.
readonly ASIMOV_KB_PER_MB=1024
readonly ASIMOV_KB_PER_GB=1048576
# Disable colors when stdout is not a terminal (e.g. launchd, pipes, redirects).
if [[ -t 1 ]]; then
readonly ASIMOV_COLOR_INFO=$'\033[0;36m'
readonly ASIMOV_COLOR_SUCCESS=$'\033[0;32m'
readonly ASIMOV_COLOR_DIM=$'\033[0;90m'
readonly ASIMOV_COLOR_RESET=$'\033[0m'
else
readonly ASIMOV_COLOR_INFO=''
readonly ASIMOV_COLOR_SUCCESS=''
readonly ASIMOV_COLOR_DIM=''
readonly ASIMOV_COLOR_RESET=''
fi
# Print a dim timestamped debug line when --verbose is set.
# Uses bash's built-in $SECONDS variable (auto-increments from 0 at script start).
# Output goes to stderr so it stays visible even when stdout is redirected
# (e.g. inside discover_new_paths_via_mdfind whose stdout is captured to a file).
verbose_timing() {
[[ -n "$ASIMOV_VERBOSE" ]] || return 0
printf '%s [%ds] %s%s\n' "$ASIMOV_COLOR_DIM" "$SECONDS" "$1" "$ASIMOV_COLOR_RESET" >&2
}
# Resolve the root directory to scan (console user's home when running as root).
resolve_asimov_root() {
if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
local console_user
console_user="$(stat -f '%Su' /dev/console 2>/dev/null || echo '')"
if [[ -n "$console_user" && "$console_user" != "root" ]]; then
local root_dir
root_dir="$(dscl . -read "/Users/${console_user}" NFSHomeDirectory 2>/dev/null | awk '{print $2}')"
if [[ -n "$root_dir" ]]; then
echo "$root_dir"
return
fi
fi
echo ~
else
echo ~
fi
}
ASIMOV_ROOT="$(resolve_asimov_root)"
readonly ASIMOV_ROOT
readonly ASIMOV_EXCLUDED_STATE="${ASIMOV_ROOT}/.cache/asimov/excluded"
readonly ASIMOV_FAILED_STATE="${ASIMOV_ROOT}/.cache/asimov/failed"
readonly ASIMOV_MDFIND_SEEN="${ASIMOV_ROOT}/.cache/asimov/mdfind_seen"
readonly ASIMOV_PATH_CACHE="${ASIMOV_ROOT}/.cache/asimov/paths"
readonly ASIMOV_CACHE_DIR="${ASIMOV_ROOT}/.cache/asimov"
# --- cache resilience ---
#
# Every cache file is an optimisation: a run must survive one being unreadable
# or unwritable rather than aborting. Without these guards a bare `cat` on an
# unreadable state file fails under `set -Eeu -o pipefail` and kills the whole
# run, printing nothing but "Permission denied" (see issue #122).
#
# The usual cause is a run as root — `sudo asimov`, or a schedule installed as
# root — leaving root-owned files behind for the next run as the user.
ASIMOV_CACHE_WARNED=
# Warn once per run that the cache is unusable, and name the fix. Always goes to
# stderr, including under --quiet: this is a degraded run, not routine chatter.
warn_unusable_cache() {
[[ -n "$ASIMOV_CACHE_WARNED" ]] && return 0
ASIMOV_CACHE_WARNED=1
printf '! %s is not %s — continuing without the cache.\n' "$1" "$2" >&2
printf ' This usually means a previous run as root left root-owned files behind.\n' >&2
printf ' To reset it:\n\n rm -rf %s\n\n' "$ASIMOV_CACHE_DIR" >&2
return 0
}
# True when a state file exists and can be read. A missing file is not an error
# (there is simply nothing cached yet), so it returns false without warning.
cache_readable() {
[[ -f "$1" ]] || return 1
[[ -r "$1" ]] && return 0
warn_unusable_cache "$1" "readable"
return 1
}
# True when a state file can be written to, creating it if necessary. An absent
# file is writable when its directory is.
cache_writable() {
if [[ -e "$1" ]]; then
[[ -w "$1" ]] && return 0
warn_unusable_cache "$1" "writable"
return 1
fi
[[ -d "$ASIMOV_CACHE_DIR" && -w "$ASIMOV_CACHE_DIR" ]] && return 0
[[ -d "$ASIMOV_CACHE_DIR" ]] || return 1 # not created yet; ensure_cache_dir reports
warn_unusable_cache "$ASIMOV_CACHE_DIR" "writable"
return 1
}
# Append a line to a state file, skipping silently when it isn't writable.
# Always returns 0 so callers can use it as the tail of an && list under set -e.
append_state() {
cache_writable "$2" || return 0
printf '%s\n' "$1" >> "$2" 2>/dev/null || true
return 0
}
# Time Machine's system preferences, home of the "sticky" path exclusion list
# (tmutil addexclusion -p). Overridable so tests can point at a fixture.
readonly ASIMOV_TM_PLIST="${ASIMOV_TM_PLIST:-/Library/Preferences/com.apple.TimeMachine.plist}"
# --- prune ---
#
# Asimov's own exclusions cannot go stale. `tmutil addexclusion PATH` stores the
# exclusion as an extended attribute on the directory itself, so deleting the
# directory deletes the exclusion with it.
#
# What *does* go stale is the "sticky" list: `tmutil addexclusion -p PATH` records
# the path in Time Machine's system preferences instead, and that entry survives
# the directory forever. Asimov has never written to that list, but other tools
# and manual commands do, and nothing surfaces the leftovers.
# Resolve a "~user/…" path, as stored in Time Machine's preferences, to an
# absolute one. Falls back to /Users/<name> when the account can't be read.
expand_tm_path() {
local path="$1" user rest home
case "$path" in
'~'*) ;;
*) printf '%s\n' "$path"; return 0 ;;
esac
path="${path#\~}"
user="${path%%/*}"
rest="${path#"$user"}"
if [[ -z "$user" ]]; then
printf '%s\n' "${ASIMOV_ROOT}${rest}"
return 0
fi
home="$(dscl . -read "/Users/${user}" NFSHomeDirectory 2>/dev/null | sed -n 's/^NFSHomeDirectory: //p')"
[[ -n "$home" ]] || home="/Users/${user}"
printf '%s\n' "${home}${rest}"
}
# Print the sticky exclusion list, one raw path per line.
# `defaults` renders it as a plist array; strip the parentheses, indentation,
# trailing commas, and surrounding quotes.
read_sticky_exclusions() {
[[ -r "$ASIMOV_TM_PLIST" ]] || return 0
defaults read "${ASIMOV_TM_PLIST%.plist}" SkipPaths 2>/dev/null \
| sed -e '/^[[:space:]]*[()]/d' \
-e 's/^[[:space:]]*//' \
-e 's/[[:space:]]*,$//' \
-e 's/^"//' -e 's/"$//' \
| grep -v '^$' || true
}
# Drop entries whose directory no longer exists from Asimov's path cache.
# Echoes the number of entries removed. This only ever touches Asimov's own
# file under ~/.cache/asimov.
prune_path_cache() {
cache_readable "$ASIMOV_PATH_CACHE" || { echo 0; return 0; }
cache_writable "$ASIMOV_PATH_CACHE" || { echo 0; return 0; }
# A brace group with a redirect runs in the current shell, so the counters
# below survive the loop.
local tmp line dropped=0
tmp="${ASIMOV_PATH_CACHE}.tmp.$$"
{
printf '# asimov path cache — updated %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
while IFS= read -r line; do
[[ "$line" =~ ^# ]] && continue
[[ -z "$line" ]] && continue
if [[ -d "$line" ]]; then
printf '%s\n' "$line"
else
dropped=$((dropped + 1))
fi
done < "$ASIMOV_PATH_CACHE"
} > "$tmp"
mv -f "$tmp" "$ASIMOV_PATH_CACHE"
echo "$dropped"
}
cmd_prune() {
local raw expanded sticky_total=0
local stale_paths="" stale_count=0
while IFS= read -r raw; do
sticky_total=$((sticky_total + 1))
expanded="$(expand_tm_path "$raw")"
if [[ ! -e "$expanded" ]]; then
stale_count=$((stale_count + 1))
stale_paths="${stale_paths}${raw}"$'\n'
fi
done < <(read_sticky_exclusions)
local cache_dropped
cache_dropped="$(prune_path_cache)"
[[ -n "$ASIMOV_QUIET" ]] && return 0
if [[ "$stale_count" -gt 0 ]]; then
printf '\n%sStale Time Machine exclusions (%s):%s\n' \
"$ASIMOV_COLOR_INFO" "$stale_count" "$ASIMOV_COLOR_RESET"
printf '%s' "$stale_paths" | while IFS= read -r raw; do
[[ -z "$raw" ]] && continue
printf ' %s %spath no longer exists%s\n' \
"$raw" "$ASIMOV_COLOR_DIM" "$ASIMOV_COLOR_RESET"
done
printf '\nThese are sticky exclusions (%stmutil addexclusion -p%s), which Asimov never sets.\n' \
"$ASIMOV_COLOR_DIM" "$ASIMOV_COLOR_RESET"
printf 'They persist after the directory is deleted. To remove one:\n\n'
printf ' sudo tmutil removeexclusion -p %s\n\n' "$(printf '%s' "$stale_paths" | head -1)"
elif [[ "$sticky_total" -gt 0 ]]; then
printf '\n%s✓%s No stale exclusions. All %s sticky entries point at directories that exist.\n' \
"$ASIMOV_COLOR_SUCCESS" "$ASIMOV_COLOR_RESET" "$sticky_total"
else
printf '\n%s✓%s No sticky Time Machine exclusions are set on this Mac.\n' \
"$ASIMOV_COLOR_SUCCESS" "$ASIMOV_COLOR_RESET"
fi
if [[ "$cache_dropped" -gt 0 ]]; then
printf 'Asimov cache: %s stale %s dropped.\n' \
"$cache_dropped" "$([[ "$cache_dropped" -eq 1 ]] && echo entry || echo entries)"
else
printf 'Asimov cache: nothing to prune.\n'
fi
printf '\n%sAsimov'\''s own exclusions are stored on the directory itself, so they are\nremoved automatically when you delete it — only sticky entries can outlive it.%s\n' \
"$ASIMOV_COLOR_DIM" "$ASIMOV_COLOR_RESET"
}
if [[ "$ASIMOV_COMMAND" == "prune" ]]; then
cmd_prune
exit 0
fi
# --- doctor ---
#
# Diagnoses an install rather than changing it. The failure modes it looks for
# are the ones people hit coming from v0.3.0 (issue #122): an old binary still
# first on PATH, a LaunchAgent pointing at a Homebrew cellar that no longer
# exists, and a cache left root-owned by a run as root.
#
# Two rules keep it safe to run at any point in a migration:
# - It never writes anything. Fixes are printed, never applied.
# - It never executes another asimov binary it finds. v0.3.0 parses no
# arguments at all, so running it to ask its version would start a real
# scan; versions are read out of the file instead.
# The label a current install schedules itself under. Everything else in the
# list below is a leftover to be removed, never re-loaded.
readonly ASIMOV_CURRENT_LABEL='com.stevegrunwell.asimov'
# Every known LaunchAgent label Asimov has ever shipped under, plus Homebrew's.
readonly ASIMOV_DOCTOR_LABELS=(
'com.stevegrunwell.asimov' # current, and the original
'com.django23.asimov' # the v0.4.x–v0.8.0 fork
'homebrew.mxcl.asimov' # brew services
)
ASIMOV_DOCTOR_PROBLEMS=0
doctor_heading() {
[[ -n "$ASIMOV_QUIET" ]] && return 0
printf '\n%s%s%s\n' "$ASIMOV_COLOR_INFO" "$1" "$ASIMOV_COLOR_RESET"
return 0
}
doctor_ok() {
[[ -n "$ASIMOV_QUIET" ]] && return 0
printf ' %s✓%s %s\n' "$ASIMOV_COLOR_SUCCESS" "$ASIMOV_COLOR_RESET" "$1"
return 0
}
doctor_note() {
[[ -n "$ASIMOV_QUIET" ]] && return 0
printf ' %s·%s %s\n' "$ASIMOV_COLOR_DIM" "$ASIMOV_COLOR_RESET" "$1"
return 0
}
# Problems print even under --quiet: a silent doctor that found something is
# worse than useless in a cron job.
doctor_problem() {
ASIMOV_DOCTOR_PROBLEMS=$((ASIMOV_DOCTOR_PROBLEMS + 1))
printf ' ✗ %s\n' "$1"
return 0
}
# Print a command the user can copy to fix the problem just reported.
doctor_fix() {
printf ' %s%s%s\n' "$ASIMOV_COLOR_DIM" "$1" "$ASIMOV_COLOR_RESET"
return 0
}
# Resolve a path to its physical location, symlinks and all. Homebrew installs
# asimov as a symlink into the cellar, so comparing raw paths would report a
# shadow that isn't there.
doctor_realpath() {
local path="$1" dir base
dir="$(cd "$(dirname "$path")" 2>/dev/null && pwd -P)" || { printf '%s\n' "$path"; return 0; }
base="$(basename "$path")"
while [[ -L "${dir}/${base}" ]]; do
local target
target="$(readlink "${dir}/${base}")"
case "$target" in
/*) dir="$(cd "$(dirname "$target")" 2>/dev/null && pwd -P)" || break ;;
*) dir="$(cd "$dir" && cd "$(dirname "$target")" 2>/dev/null && pwd -P)" || break ;;
esac
base="$(basename "$target")"
done
printf '%s/%s\n' "$dir" "$base"
}
# Read a version out of an asimov script without running it. Handles both the
# current `readonly ASIMOV_VERSION='x'` and v0.3.0's `# @version x` header.
doctor_file_version() {
local file="$1" line
line="$(grep -m1 -E "^readonly ASIMOV_VERSION=|^# @version " "$file" 2>/dev/null || true)"
[[ -n "$line" ]] || { printf 'unknown\n'; return 0; }
line="${line##*@version }"
line="${line##*=}"
line="${line//\'/}"
line="${line//\"/}"
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
printf '%s\n' "${line:-unknown}"
}
# Every `asimov` on PATH, in PATH order, deduplicated by physical path.
doctor_path_binaries() {
local dir candidate resolved seen=""
while IFS= read -r dir; do
[[ -n "$dir" ]] || continue
candidate="${dir}/asimov"
[[ -x "$candidate" && ! -d "$candidate" ]] || continue
resolved="$(doctor_realpath "$candidate")"
case "$seen" in
*"|${resolved}|"*) continue ;;
esac
seen="${seen}|${resolved}|"
printf '%s\n' "$resolved"
done < <(printf '%s\n' "${PATH//:/$'\n'}")
}
doctor_check_install() {
doctor_heading 'Install'
local running
running="$(doctor_realpath "${BASH_SOURCE[0]}")"
doctor_ok "asimov ${ASIMOV_VERSION} (${running})"
local -a found=()
while IFS= read -r line; do
[[ -n "$line" ]] && found+=("$line")
done < <(doctor_path_binaries)
if [[ ${#found[@]} -eq 0 ]]; then
doctor_note "no asimov on PATH — you are running it by path"
return 0
fi
local first="${found[0]}"
if [[ "$first" != "$running" ]]; then
doctor_problem "typing 'asimov' runs a different binary — this one is shadowed"
doctor_fix "${first} (version $(doctor_file_version "$first"))"
doctor_fix "Remove the one you don't want, or fix the order of PATH."
else
doctor_ok "'asimov' on PATH is this one"
fi
local other
for other in "${found[@]}"; do
[[ "$other" == "$first" ]] && continue
doctor_note "also installed: ${other} (version $(doctor_file_version "$other"))"
done
return 0
}
doctor_check_schedule() {
doctor_heading 'Schedule'
local agents_dir="${ASIMOV_ROOT}/Library/LaunchAgents"
local label plist program active=0
for label in "${ASIMOV_DOCTOR_LABELS[@]}"; do
plist="${agents_dir}/${label}.plist"
[[ -f "$plist" ]] || continue
active=$((active + 1))
program="$(plutil -extract Program raw "$plist" 2>/dev/null || true)"
if [[ -n "$program" && ! -x "$program" ]]; then
doctor_problem "${label}: its program ${program} no longer exists"
doctor_fix "launchctl bootout gui/\$(id -u)/${label}"
doctor_fix "rm ${plist}"
continue
fi
if launchctl list "$label" >/dev/null 2>&1; then
doctor_ok "${label} — loaded, runs daily"
elif [[ "$label" == "$ASIMOV_CURRENT_LABEL" ]]; then
doctor_problem "${label}: installed but not loaded, so it never runs"
doctor_fix "launchctl bootstrap gui/\$(id -u) ${plist}"
else
# A label we no longer ship, sitting unloaded: a leftover from an
# older install. Loading it is never the right advice.
doctor_problem "${label}: leftover from an older install, not loaded"
doctor_fix "rm ${plist}"
fi
done
if [[ "$active" -eq 0 ]]; then
doctor_note "not scheduled — Asimov only runs when you run it"
elif [[ "$active" -gt 1 ]]; then
doctor_problem "more than one schedule is installed (${active}) — they will both run"
doctor_fix "Keep com.stevegrunwell.asimov and bootout the rest."
fi
return 0
}
# Humanise an age in seconds: "3 minutes ago", "2 days ago".
doctor_humanise_age() {
local seconds="$1" value unit
if [[ "$seconds" -lt 60 ]]; then printf 'just now\n'; return 0
elif [[ "$seconds" -lt 3600 ]]; then value=$((seconds / 60)); unit=minute
elif [[ "$seconds" -lt 86400 ]]; then value=$((seconds / 3600)); unit=hour
else value=$((seconds / 86400)); unit=day
fi
printf '%s %s%s ago\n' "$value" "$unit" "$([[ "$value" -eq 1 ]] || echo s)"
}
doctor_check_cache() {
doctor_heading 'Cache'
if [[ ! -d "$ASIMOV_CACHE_DIR" ]]; then
doctor_ok "no cache yet — the next run builds one"
return 0
fi
if [[ ! -w "$ASIMOV_CACHE_DIR" ]]; then
doctor_problem "${ASIMOV_CACHE_DIR} is not writable by you"
doctor_fix "rm -rf ${ASIMOV_CACHE_DIR}"
return 0
fi
local file owner broken=0 root_owned=0
for file in "$ASIMOV_EXCLUDED_STATE" "$ASIMOV_FAILED_STATE" \
"$ASIMOV_MDFIND_SEEN" "$ASIMOV_PATH_CACHE"; do
[[ -e "$file" ]] || continue
if [[ ! -r "$file" || ! -w "$file" ]]; then
broken=$((broken + 1))
owner="$(stat -f '%Su' "$file" 2>/dev/null || echo 'unknown')"
[[ "$owner" == "root" ]] && root_owned=$((root_owned + 1))
doctor_problem "${file} is not readable and writable by you (owner: ${owner})"
fi
done
if [[ "$broken" -gt 0 ]]; then
# Only name root as the cause when root actually owns something: a
# diagnosis that guesses wrong sends people chasing the wrong fix.
if [[ "$root_owned" -gt 0 ]]; then
doctor_fix "A run as root left these behind. Clear them:"
else
doctor_fix "Asimov can't use these. Clear them:"
fi
doctor_fix "rm -rf ${ASIMOV_CACHE_DIR}"
return 0
fi
if [[ -r "$ASIMOV_PATH_CACHE" ]]; then
local entries age
entries="$(grep -cve '^#' -e '^$' "$ASIMOV_PATH_CACHE" 2>/dev/null || true)"
doctor_ok "${entries:-0} cached paths"
age="$(( $(date +%s) - $(stat -f '%m' "$ASIMOV_PATH_CACHE" 2>/dev/null || date +%s) ))"
doctor_ok "last scan: $(doctor_humanise_age "$age")"
else
doctor_ok "cache is readable, no scan recorded yet"
fi
return 0
}
doctor_check_config() {
doctor_heading 'Config'
local config_file="${ASIMOV_ROOT}/.config/asimov/config"
if [[ ! -f "$config_file" ]]; then
doctor_note "no config file — using defaults"
return 0
fi
if [[ ! -r "$config_file" ]]; then
doctor_problem "${config_file} is not readable by you"
return 0
fi
# Same grammar load_config accepts, but here anything unrecognised is
# reported instead of silently ignored — a typo'd key is invisible otherwise.
local section="" line key unknown=0
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^\[([a-z_]+)\]$ ]]; then
section="${BASH_REMATCH[1]}"
case "$section" in
fixed_dirs|scan|sentinels) ;;
*)
unknown=$((unknown + 1))
doctor_problem "unknown section [${section}] in ${config_file}"
;;
esac
continue
fi
if [[ "$line" =~ ^([a-z_]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
case "${section}:${key}" in
fixed_dirs:enabled|fixed_dirs:extra|scan:extra|\
sentinels:extra|sentinels:disabled) ;;
*)
# A key under an already-reported section is the same fault.
case "$section" in
fixed_dirs|scan|sentinels)
unknown=$((unknown + 1))
doctor_problem "unknown key '${key}' under [${section}] in ${config_file}"
;;
esac
;;
esac
fi
done < "$config_file"
[[ "$unknown" -eq 0 ]] && doctor_ok "${config_file} looks valid"
return 0
}
doctor_check_time_machine() {
doctor_heading 'Time Machine'
if ! command -v tmutil >/dev/null 2>&1; then
doctor_problem "tmutil not found — is this macOS?"
return 0
fi
if tmutil isexcluded "$ASIMOV_ROOT" >/dev/null 2>&1; then
doctor_ok "tmutil can read exclusions"
else
doctor_problem "tmutil cannot read exclusions — grant your terminal Full Disk Access"
doctor_fix "System Settings → Privacy & Security → Full Disk Access"
fi
return 0
}
cmd_doctor() {
[[ -n "$ASIMOV_QUIET" ]] || printf '\n%sAsimov doctor%s\n' \
"$ASIMOV_COLOR_INFO" "$ASIMOV_COLOR_RESET"
doctor_check_install
doctor_check_schedule
doctor_check_cache
doctor_check_config
doctor_check_time_machine
if [[ "$ASIMOV_DOCTOR_PROBLEMS" -eq 0 ]]; then
[[ -n "$ASIMOV_QUIET" ]] || printf '\n%s✓%s No problems found.\n\n' \
"$ASIMOV_COLOR_SUCCESS" "$ASIMOV_COLOR_RESET"
return 0
fi
printf '\n%s problem%s found.\n\n' "$ASIMOV_DOCTOR_PROBLEMS" \
"$([[ "$ASIMOV_DOCTOR_PROBLEMS" -eq 1 ]] || echo s)"
return 1
}
if [[ "$ASIMOV_COMMAND" == "doctor" ]]; then
cmd_doctor
exit $?
fi
# Load optional config from ~/.config/asimov/config.
# Populates ASIMOV_CONFIG_* variables. Missing file is silently ignored.
load_config() {
local config_file="${ASIMOV_ROOT}/.config/asimov/config"
ASIMOV_CONFIG_FIXED_DIRS_ENABLED=false
ASIMOV_CONFIG_EXTRA_FIXED_DIRS=()
ASIMOV_CONFIG_EXTRA_SENTINELS=()
ASIMOV_CONFIG_DISABLED_SENTINELS=()
ASIMOV_CONFIG_SCAN_DIRS=()
[[ -f "$config_file" ]] || return 0
local section="" line key value
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^\[([a-z_]+)\]$ ]]; then
section="${BASH_REMATCH[1]}"
continue
fi
if [[ "$line" =~ ^([a-z_]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
value="${value%"${value##*[![:space:]]}"}"
case "${section}:${key}" in
fixed_dirs:enabled)
ASIMOV_CONFIG_FIXED_DIRS_ENABLED="$value"
;;
fixed_dirs:extra)
value="${value/#\~/$HOME}"
ASIMOV_CONFIG_EXTRA_FIXED_DIRS+=("$value")
;;
scan:extra)
value="${value/#\~/$HOME}"
ASIMOV_CONFIG_SCAN_DIRS+=("$value")
;;
sentinels:extra)
ASIMOV_CONFIG_EXTRA_SENTINELS+=("$value")
;;
sentinels:disabled)
ASIMOV_CONFIG_DISABLED_SENTINELS+=("$value")
;;
esac
fi
done < "$config_file"
}
load_config
# Resolve the set of directories to scan into ASIMOV_SCAN_DIRS.
# - A positional CLI argument overrides everything: scan only that directory.
# - Otherwise scan the home directory plus any [scan] extra dirs from config.
# Configured dirs that don't exist are warned about and skipped rather than
# aborting the run (e.g. an unmounted external volume).
ASIMOV_SCAN_DIRS=()
if [[ -n "$ASIMOV_SCAN_DIR" ]]; then
if [[ ! -d "$ASIMOV_SCAN_DIR" ]]; then
echo "asimov: not a directory: ${ASIMOV_SCAN_DIR}" >&2
exit 1
fi
ASIMOV_SCAN_DIRS=("$ASIMOV_SCAN_DIR")
else
ASIMOV_SCAN_DIRS=("$ASIMOV_ROOT")
for scan_dir in ${ASIMOV_CONFIG_SCAN_DIRS[@]+"${ASIMOV_CONFIG_SCAN_DIRS[@]}"}; do
if [[ ! -d "$scan_dir" ]]; then
[[ -z "$ASIMOV_QUIET" ]] && \
echo "asimov: configured scan directory does not exist, skipping: ${scan_dir}" >&2
continue
fi
ASIMOV_SCAN_DIRS+=("$scan_dir")
done
fi
# Drop any scan dir that equals or nests inside another (Time Machine exclusions
# and find traversal are both recursive, so the parent already covers it). This
# also collapses exact duplicates, e.g. a configured ~/Projects under $HOME.
prune_nested_scan_dirs() {
local -a kept=()
local dir other nested dup k
for dir in "${ASIMOV_SCAN_DIRS[@]}"; do
nested=false
for other in "${ASIMOV_SCAN_DIRS[@]}"; do
[[ "$dir" == "$other" ]] && continue
if [[ "$dir" == "$other"/* ]]; then nested=true; break; fi
done
[[ "$nested" == true ]] && continue
dup=false
for k in ${kept[@]+"${kept[@]}"}; do
[[ "$k" == "$dir" ]] && { dup=true; break; }
done
[[ "$dup" == true ]] && continue
kept+=("$dir")
done
ASIMOV_SCAN_DIRS=("${kept[@]}")
}
prune_nested_scan_dirs
readonly -a ASIMOV_SCAN_DIRS
# When ignoring cached reads but still writing (e.g. --full-scan / --no-read-cache),
# clear the append-only state so the rebuilt cache reflects only this run's results.
# When not writing (--no-cache / --no-write-cache), leave every cache file untouched.
# (The paths cache is truncated separately by init_path_cache before the full scan.)
if [[ -n "$ASIMOV_NO_READ_CACHE" && -z "$ASIMOV_NO_WRITE_CACHE" ]]; then
rm -f "$ASIMOV_EXCLUDED_STATE" "$ASIMOV_FAILED_STATE" "$ASIMOV_MDFIND_SEEN" 2>/dev/null || true
fi
# Build a cache of paths already excluded from Time Machine.
# Merges Spotlight index (what macOS reports) with our own persistent state
# (written after each successful tmutil call). The persistent state handles:
# - Interrupted runs (Ctrl+C before all tmutil calls complete)
# - Spotlight indexing delays (tmutil sets xattr but Spotlight hasn't indexed it)
verbose_timing "Building excluded-path cache via Spotlight…"
: > "$ASIMOV_EXCLUDED_CACHE"
for scan_dir in "${ASIMOV_SCAN_DIRS[@]}"; do
mdfind -onlyin "$scan_dir" "com_apple_backup_excludeItem = 'com.apple.backupd'" 2>/dev/null \
>> "$ASIMOV_EXCLUDED_CACHE" || true
done
sort -u -o "$ASIMOV_EXCLUDED_CACHE" "$ASIMOV_EXCLUDED_CACHE"
spotlight_count="$(wc -l < "$ASIMOV_EXCLUDED_CACHE" | tr -d ' ')"
# Merge persistent excluded + failed state into the Spotlight cache.
# Failed paths (e.g. read-only dirs inside Go's module cache) are included so the bulk filter
# skips them instantly instead of wasting time retrying tmutil.
# Skipped under --no-read-cache (--full-scan / --no-cache): every path is then
# re-verified against the tmutil isexcluded ground truth instead.
if [[ -z "$ASIMOV_NO_READ_CACHE" ]] && { cache_readable "$ASIMOV_EXCLUDED_STATE" || cache_readable "$ASIMOV_FAILED_STATE"; }; then
{
cat "$ASIMOV_EXCLUDED_CACHE"
if cache_readable "$ASIMOV_EXCLUDED_STATE"; then cat "$ASIMOV_EXCLUDED_STATE"; fi
if cache_readable "$ASIMOV_FAILED_STATE"; then cat "$ASIMOV_FAILED_STATE"; fi
} | sort -u > "${ASIMOV_EXCLUDED_CACHE}.merged"
mv -f "${ASIMOV_EXCLUDED_CACHE}.merged" "$ASIMOV_EXCLUDED_CACHE"
fi
verbose_timing "Excluded-path cache ready ($(wc -l < "$ASIMOV_EXCLUDED_CACHE" | tr -d ' ') entries, ${spotlight_count} from Spotlight)"
# --- Path cache ---
# (ASIMOV_PATH_CACHE is defined alongside the other state files, above, so that
# the prune subcommand can reach it before any of the scan machinery runs.)
# Create the cache directory, chown to console user when running as root.
ensure_cache_dir() {
if [[ ! -d "$ASIMOV_CACHE_DIR" ]]; then
mkdir -p "$ASIMOV_CACHE_DIR" 2>/dev/null || {
warn_unusable_cache "$ASIMOV_CACHE_DIR" "writable"
return 0
}
fi
if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
local console_user
console_user="$(stat -f '%Su' /dev/console 2>/dev/null || echo '')"
if [[ -n "$console_user" && "$console_user" != "root" ]]; then
# Create the state files *before* the chown. Appending to an existing
# file never changes its owner, so every write later in this root run
# lands in a file the console user can still read next time. Chowning
# only the directory (as this did before) left root-owned files behind
# that broke the following user run outright — issue #122.
touch "$ASIMOV_EXCLUDED_STATE" "$ASIMOV_FAILED_STATE" \
"$ASIMOV_MDFIND_SEEN" "$ASIMOV_PATH_CACHE" 2>/dev/null || true
chown -R "$console_user" "$ASIMOV_CACHE_DIR" 2>/dev/null || true
fi
fi
return 0
}
# Read cached paths, filtering to those that still exist as directories
# and fall under one of the scan dirs. Outputs valid paths to stdout.
read_path_cache() {
cache_readable "$ASIMOV_PATH_CACHE" || return 0
local line d in_scope
while IFS= read -r line; do
# Skip comments and blank lines
[[ "$line" =~ ^# ]] && continue
[[ -z "$line" ]] && continue
# Must still exist as a directory
[[ -d "$line" ]] || continue
# Must be under one of the scan dirs
in_scope=false
for d in "${ASIMOV_SCAN_DIRS[@]}"; do
if [[ "$line" == "${d}"/* || "$line" == "${d}" ]]; then in_scope=true; break; fi
done
[[ "$in_scope" == true ]] || continue
printf '%s\n' "$line"
done < "$ASIMOV_PATH_CACHE"
}
# Initialize the path cache file with a header, truncating any old contents.
# No-op if --dry-run or writes are disabled (--no-write-cache / --no-cache).
init_path_cache() {
[[ -n "$ASIMOV_DRY_RUN" || -n "$ASIMOV_NO_WRITE_CACHE" ]] && return 0
ensure_cache_dir
cache_writable "$ASIMOV_PATH_CACHE" || return 0
printf '# asimov path cache — updated %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" > "$ASIMOV_PATH_CACHE"
}
# Append a single path to the cache file. No-op if --dry-run or writes are disabled (--no-write-cache / --no-cache).
append_path_to_cache() {
[[ -n "$ASIMOV_DRY_RUN" || -n "$ASIMOV_NO_WRITE_CACHE" ]] && return 0
append_state "$1" "$ASIMOV_PATH_CACHE"
}
# Remove paths that are descendants of other paths in the list.
# Expects sorted input. Outputs only outermost (non-nested) paths.
# Example: /a/node_modules and /a/node_modules/foo/node_modules → keeps only /a/node_modules
# (Time Machine exclusions are recursive, so the descendant is already covered.)
dedup_nested_paths() {
local last_kept="" path
while IFS= read -r path; do
[[ -z "$path" ]] && continue
if [[ -n "$last_kept" && "$path" == "${last_kept}/"* ]]; then
continue
fi
printf '%s\n' "$path"
last_kept="$path"
done
}
# Sort, deduplicate, and prune stale entries from the cache file.
# Writes atomically via temp file + mv. No-op if --dry-run or writes are disabled (--no-write-cache / --no-cache).
finalize_path_cache() {
[[ -n "$ASIMOV_DRY_RUN" || -n "$ASIMOV_NO_WRITE_CACHE" ]] && return 0
cache_readable "$ASIMOV_PATH_CACHE" || return 0
cache_writable "$ASIMOV_PATH_CACHE" || return 0
ASIMOV_PATH_CACHE_TMP="${ASIMOV_PATH_CACHE}.tmp.$$"
{
printf '# asimov path cache — updated %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
# Keep only lines that are existing directories, sorted and deduplicated
while IFS= read -r line; do
[[ "$line" =~ ^# ]] && continue
[[ -z "$line" ]] && continue
if [[ -d "$line" ]]; then
printf '%s\n' "$line"
fi
done < "$ASIMOV_PATH_CACHE" | sort -u | dedup_nested_paths
} > "$ASIMOV_PATH_CACHE_TMP"
mv -f "$ASIMOV_PATH_CACHE_TMP" "$ASIMOV_PATH_CACHE"
ASIMOV_PATH_CACHE_TMP=""
# Dedup the mdfind_seen file (grows with appends each run)
if cache_readable "$ASIMOV_MDFIND_SEEN" && cache_writable "$ASIMOV_MDFIND_SEEN"; then
sort -u "$ASIMOV_MDFIND_SEEN" > "${ASIMOV_MDFIND_SEEN}.tmp"
mv -f "${ASIMOV_MDFIND_SEEN}.tmp" "$ASIMOV_MDFIND_SEEN"
fi
# Dedup the failed-state file (grows with appends each run)
if cache_readable "$ASIMOV_FAILED_STATE" && cache_writable "$ASIMOV_FAILED_STATE"; then
sort -u "$ASIMOV_FAILED_STATE" > "${ASIMOV_FAILED_STATE}.tmp"
mv -f "${ASIMOV_FAILED_STATE}.tmp" "$ASIMOV_FAILED_STATE"
fi
if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
local console_user
console_user="$(stat -f '%Su' /dev/console 2>/dev/null || echo '')"
if [[ -n "$console_user" && "$console_user" != "root" ]]; then
chown "$console_user" "$ASIMOV_PATH_CACHE" 2>/dev/null || true
fi
fi
}
# Discover new dependency paths via Spotlight (mdfind) that aren't in the
# current cache. For each candidate, validate the sentinel exists in the
# parent directory. Outputs newly discovered paths to stdout.
discover_new_paths_via_mdfind() {
local cached_paths_file="$1"
# Pre-build active sentinel pairs (filter disabled once, not per candidate)
local -a dir_names=() active_sentinels=()
local pair parts dir_name seen=""
for pair in "${ASIMOV_VENDOR_DIR_SENTINELS[@]}"; do
local disabled=false
if [[ ${#ASIMOV_CONFIG_DISABLED_SENTINELS[@]} -gt 0 ]]; then
local dpair
for dpair in "${ASIMOV_CONFIG_DISABLED_SENTINELS[@]}"; do
[[ "$pair" == "$dpair" ]] && { disabled=true; break; }
done
fi
[[ "$disabled" == true ]] && continue
active_sentinels+=("$pair")
read -ra parts <<< "$pair"
dir_name="${parts[0]}"
if [[ " $seen " != *" $dir_name "* ]]; then
dir_names+=("$dir_name")
seen="$seen $dir_name"
fi
done
for pair in ${ASIMOV_CONFIG_EXTRA_SENTINELS[@]+"${ASIMOV_CONFIG_EXTRA_SENTINELS[@]}"}; do
active_sentinels+=("$pair")
read -ra parts <<< "$pair"
dir_name="${parts[0]}"
if [[ " $seen " != *" $dir_name "* ]]; then
dir_names+=("$dir_name")
seen="$seen $dir_name"
fi