-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathleash
More file actions
executable file
·1235 lines (1060 loc) · 41.1 KB
/
leash
File metadata and controls
executable file
·1235 lines (1060 loc) · 41.1 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
# git-leash — helps you stay focused on what you're supposed to be doing.
# by a puppygirl 🐾
#
# A pre-commit hook that blocks commits during configured focus windows,
# with optional puppygirl-flavored bark messages.
set -euo pipefail
LEASH_VERSION="0.1.2"
if ((BASH_VERSINFO < 4)); then
echo "git-leash requires Bash 4+. Currently running ${BASH_VERSION}"
exit 1
fi
# --- Config Parser -----------------------------------------------------------
# Parses INI-style config with named sections and multi-value keys.
# Supports: [schedule "name"], [tone "name"], [defaults], [task], [override]
# Parse a config file into a flat key-value store.
# Section headers become prefixes: schedule.work-focus.start=09:00
# Multi-value keys (allow, block) get numbered: schedule.work-focus.allow.0=remote:foo
declare -A CONFIG
declare -a SCHEDULE_NAMES=()
declare -a TONE_NAMES=()
parse_config_file() {
local file="$1"
local current_section=""
local current_name=""
local prefix=""
declare -A multicount
[[ -f "$file" ]] || return 0
while IFS= read -r line || [[ -n "$line" ]]; do
# strip comments and trailing whitespace
line="${line%%#*}"
line="${line%"${line##*[![:space:]]}"}"
# skip blank lines
[[ -z "$line" ]] && continue
# named section: [schedule "work-focus"]
if [[ "$line" =~ ^\[([a-zA-Z_-]+)\ +\"([^\"]+)\"\]$ ]]; then
current_section="${BASH_REMATCH[1]}"
current_name="${BASH_REMATCH[2]}"
prefix="${current_section}.${current_name}."
if [[ "$current_section" == "schedule" ]]; then
# track schedule names (avoid duplicates on merge)
local found=0
for sn in "${SCHEDULE_NAMES[@]:-}"; do
[[ "$sn" == "$current_name" ]] && found=1 && break
done
[[ $found -eq 0 ]] && SCHEDULE_NAMES+=("$current_name")
elif [[ "$current_section" == "tone" ]]; then
# track tone names (avoid duplicates on merge)
local found=0
for tn in "${TONE_NAMES[@]:-}"; do
[[ "$tn" == "$current_name" ]] && found=1 && break
done
[[ $found -eq 0 ]] && TONE_NAMES+=("$current_name")
fi
continue
fi
# plain section: [task], [override], [messages]
if [[ "$line" =~ ^\[([a-zA-Z_-]+)\]$ ]]; then
current_section="${BASH_REMATCH[1]}"
current_name=""
prefix="${current_section}."
continue
fi
# key=value
if [[ "$line" =~ ^([a-zA-Z_-]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
# trim leading/trailing whitespace from value
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
# multi-value keys: allow, block, bark
if [[ "$key" == "allow" || "$key" == "block" || "$key" == "bark" ]]; then
local count_key="${prefix}${key}._count"
local count="${multicount[$count_key]:-${CONFIG[$count_key]:-0}}"
CONFIG["${prefix}${key}.${count}"]="$value"
count=$((count + 1))
CONFIG["$count_key"]="$count"
multicount["$count_key"]="$count"
else
CONFIG["${prefix}${key}"]="$value"
fi
fi
done < "$file"
}
# Get a config value with optional default
cfg() {
local key="$1"
local default="${2:-}"
echo "${CONFIG[$key]:-$default}"
}
# Load config: global first, then project (project wins)
load_config() {
CONFIG=()
SCHEDULE_NAMES=()
TONE_NAMES=()
# global
parse_config_file "${HOME}/.leash"
# project-local (overrides global for same keys)
local git_root
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -n "$git_root" && -f "${git_root}/.leash" ]]; then
parse_config_file "${git_root}/.leash"
fi
# migrate deprecated [messages] → [defaults]
migrate_messages_to_defaults
}
# Handle [messages] → [defaults] deprecation
migrate_messages_to_defaults() {
local has_messages=0
# check for any messages.* keys
for key in "${!CONFIG[@]}"; do
if [[ "$key" == messages.* ]]; then
has_messages=1
break
fi
done
(( has_messages == 0 )) && return 0
local suppress
suppress="$(cfg "defaults.suppress_warnings" "$(cfg "messages.suppress_warnings" "false")")"
if [[ "$suppress" != "true" ]]; then
echo " 🐾 leash: [messages] is deprecated, use [defaults] instead" >&2
echo " tone= and noun= now go in [defaults]. see: leash example" >&2
echo " set suppress_warnings=true in [defaults] to silence this" >&2
fi
# migrate: messages.tone → defaults.tone (if defaults.tone not already set)
local msg_tone
msg_tone="$(cfg "messages.tone" "")"
if [[ -n "$msg_tone" && -z "$(cfg "defaults.tone" "")" ]]; then
CONFIG["defaults.tone"]="$msg_tone"
fi
# migrate: messages.noun → defaults.noun
local msg_noun
msg_noun="$(cfg "messages.noun" "")"
if [[ -n "$msg_noun" && -z "$(cfg "defaults.noun" "")" ]]; then
CONFIG["defaults.noun"]="$msg_noun"
fi
# migrate: messages.suppress_warnings → defaults.suppress_warnings
local msg_suppress
msg_suppress="$(cfg "messages.suppress_warnings" "")"
if [[ -n "$msg_suppress" && -z "$(cfg "defaults.suppress_warnings" "")" ]]; then
CONFIG["defaults.suppress_warnings"]="$msg_suppress"
fi
}
# --- Time & Day Checking -----------------------------------------------------
time_to_minutes() {
local t="$1"
local h="${t%%:*}"
local m="${t##*:}"
# strip leading zeros for arithmetic
h=$((10#$h))
m=$((10#$m))
echo $(( h * 60 + m ))
}
is_in_time_window() {
local start_min="$1"
local end_min="$2"
local now_min="$3"
if (( start_min <= end_min )); then
# normal window: 09:00-17:00
(( now_min >= start_min && now_min < end_min ))
else
# overnight window: 23:00-06:00
(( now_min >= start_min || now_min < end_min ))
fi
}
day_matches() {
local days_str="$1"
local current_day="$2"
local -a _day_list
IFS=',' read -ra _day_list <<< "$days_str"
for d in "${_day_list[@]}"; do
d="${d#"${d%%[![:space:]]*}"}"
d="${d%"${d##*[![:space:]]}"}"
d="${d,,}" # lowercase
[[ "$d" == "$current_day" ]] && return 0
done
return 1
}
# --- Repo Matching ------------------------------------------------------------
get_all_remotes() {
git remote -v 2>/dev/null | awk '{print $2}' | sort -u
}
get_repo_path() {
git rev-parse --show-toplevel 2>/dev/null
}
get_repo_dirname() {
local path
path="$(get_repo_path)"
basename "$path" 2>/dev/null
}
# Match a single pattern like "remote:github.com/company/*" against repo
match_repo_pattern() {
local pattern="$1"
local type="${pattern%%:*}"
local glob="${pattern#*:}"
case "$type" in
remote)
local remotes
remotes="$(get_all_remotes)"
while IFS= read -r remote_url; do
# strip protocol prefix for matching
local stripped="$remote_url"
stripped="${stripped#https://}"
stripped="${stripped#http://}"
stripped="${stripped#git@}"
stripped="${stripped#ssh://}"
# git@github.com:user/repo.git -> github.com/user/repo.git
stripped="${stripped/://}"
# strip .git suffix
stripped="${stripped%.git}"
# shellcheck disable=SC2053
if [[ "$stripped" == $glob ]]; then
return 0
fi
done <<< "$remotes"
;;
path)
local repo_path
repo_path="$(get_repo_path)"
# shellcheck disable=SC2053
[[ "$repo_path" == $glob ]] && return 0
;;
dir)
local repo_dir
repo_dir="$(get_repo_dirname)"
# shellcheck disable=SC2053
[[ "$repo_dir" == $glob ]] && return 0
;;
*)
# unknown prefix, no match
return 1
;;
esac
return 1
}
# Check if repo matches any pattern in a list
repo_matches_any() {
local prefix="$1" # e.g., schedule.work-focus.allow
local count
count="$(cfg "${prefix}._count" "0")"
(( count == 0 )) && return 1
local i
for (( i = 0; i < count; i++ )); do
local pattern
pattern="$(cfg "${prefix}.${i}" "")"
[[ -n "$pattern" ]] && match_repo_pattern "$pattern" && return 0
done
return 1
}
# --- Warnings -----------------------------------------------------------------
leash_warn_allow_block() {
local schedule_name="$1"
local suppress
suppress="$(cfg "defaults.suppress_warnings" "false")"
[[ "$suppress" == "true" ]] && return 0
echo " 🐾 leash: warning: schedule \"${schedule_name}\" has both allow= and block= lines" >&2
echo " block= lines are ignored when allow= is present" >&2
echo " set suppress_warnings=true in [defaults] to silence this" >&2
}
# --- Core Check Logic ---------------------------------------------------------
# Returns 0 if commit should be blocked, 1 if allowed.
# Sets BLOCK_SCHEDULE_NAME and BLOCK_SCHEDULE_* vars on block.
check_should_block() {
local tz current_day current_time_str now_min
for schedule_name in "${SCHEDULE_NAMES[@]:-}"; do
local sp="schedule.${schedule_name}."
# get timezone
tz="$(cfg "${sp}timezone" "local")"
# get current day and time in the right timezone
if [[ "$tz" == "local" ]]; then
current_day="$(date +%a)"
current_time_str="$(date +%H:%M)"
else
current_day="$(TZ="$tz" date +%a)"
current_time_str="$(TZ="$tz" date +%H:%M)"
fi
current_day="${current_day,,}" # lowercase
# check day
local days
days="$(cfg "${sp}days" "mon,tue,wed,thu,fri")"
day_matches "$days" "$current_day" || continue
# check time
local start end
start="$(cfg "${sp}start" "")"
end="$(cfg "${sp}end" "")"
[[ -z "$start" || -z "$end" ]] && continue
local start_min end_min
start_min="$(time_to_minutes "$start")"
end_min="$(time_to_minutes "$end")"
now_min="$(time_to_minutes "$current_time_str")"
is_in_time_window "$start_min" "$end_min" "$now_min" || continue
# we're in the time window — check repo filters
local has_allow has_block
has_allow="$(cfg "${sp}allow._count" "0")"
has_block="$(cfg "${sp}block._count" "0")"
if (( has_allow > 0 )); then
# warn if block= lines are being ignored
if (( has_block > 0 )); then
leash_warn_allow_block "$schedule_name"
fi
# allow mode: block unless repo matches
repo_matches_any "${sp}allow" && continue
# repo not in allow list — block
elif (( has_block > 0 )); then
# block mode: block only if repo matches
repo_matches_any "${sp}block" || continue
# repo in block list — block
fi
# else: no filters, block everything in this window
# blocked!
BLOCK_SCHEDULE_NAME="$schedule_name"
BLOCK_DAYS="$days"
BLOCK_START="$start"
BLOCK_END="$end"
BLOCK_TZ="$tz"
# per-schedule task, fall back to global [task]
BLOCK_TASK="$(cfg "${sp}task" "$(cfg "task.current" "")")"
return 0
done
return 1
}
# --- Tone Defaults ------------------------------------------------------------
# Built-in tone data. User config adds to / overrides these.
declare -A BUILTIN_TONE
init_builtin_tones() {
# --- puppy ---
BUILTIN_TONE[puppy.emoji]="🐾"
BUILTIN_TONE[puppy.noun]="puppy,girl"
BUILTIN_TONE[puppy.task_line]="be a good {noun} and work on: {task} 🐶"
BUILTIN_TONE[puppy.env_label]="slip the leash:"
BUILTIN_TONE[puppy.slip_label]="one-time walkies:"
BUILTIN_TONE[puppy.nuclear_label]="...or --no-verify, but that's cheating and you know it"
BUILTIN_TONE[puppy.bark._count]=8
BUILTIN_TONE[puppy.bark.0]="arf arf! bad {noun}!! no commits during focus time!!"
BUILTIN_TONE[puppy.bark.1]="woof! hey! you're not supposed to be doing that!!"
BUILTIN_TONE[puppy.bark.2]="bork bork! paws OFF the commit button!!"
BUILTIN_TONE[puppy.bark.3]="*tugs leash* nuh uh!! it's focus time!!"
BUILTIN_TONE[puppy.bark.4]="*whimper* you promised you'd focus this time..."
BUILTIN_TONE[puppy.bark.5]="WOOF! sit! stay! no commit!"
BUILTIN_TONE[puppy.bark.6]="*pulls you back by the collar* not so fast!!"
BUILTIN_TONE[puppy.bark.7]="arf! you silly {noun}, it's not commit time yet!"
# --- wolf ---
BUILTIN_TONE[wolf.emoji]="🐺"
BUILTIN_TONE[wolf.noun]="wolf,puppy"
BUILTIN_TONE[wolf.task_line]="your task, {noun}: {task}"
BUILTIN_TONE[wolf.env_label]="break free:"
BUILTIN_TONE[wolf.slip_label]="one-time howl:"
BUILTIN_TONE[wolf.nuclear_label]="go lone wolf:"
BUILTIN_TONE[wolf.bark._count]=6
BUILTIN_TONE[wolf.bark.0]="*growl* ...you know better than this, {noun}."
BUILTIN_TONE[wolf.bark.1]="the pack doesn't commit during focus time."
BUILTIN_TONE[wolf.bark.2]="*bares teeth* step away from the keyboard."
BUILTIN_TONE[wolf.bark.3]="*low growl* not now. you have work to do."
BUILTIN_TONE[wolf.bark.4]="*pins you down* no. focus."
BUILTIN_TONE[wolf.bark.5]="you're not going anywhere, {noun}. back to work."
# --- cat ---
BUILTIN_TONE[cat.emoji]="🐱"
BUILTIN_TONE[cat.noun]="kitten,kitty"
BUILTIN_TONE[cat.task_line]="{noun}, you should be working on: {task}"
BUILTIN_TONE[cat.env_label]="earn your freedom:"
BUILTIN_TONE[cat.slip_label]="one treat:"
BUILTIN_TONE[cat.nuclear_label]="knock it off the table:"
BUILTIN_TONE[cat.bark._count]=7
BUILTIN_TONE[cat.bark.0]="*knocks your commit off the table*"
BUILTIN_TONE[cat.bark.1]="*stares at you judgmentally* ...no."
BUILTIN_TONE[cat.bark.2]="mrrp. no commits right now, {noun}."
BUILTIN_TONE[cat.bark.3]="*sits on your keyboard* you're not doing that."
BUILTIN_TONE[cat.bark.4]="*slow blink* ...did I say you could commit?"
BUILTIN_TONE[cat.bark.5]="hssss!! it's focus time!!"
BUILTIN_TONE[cat.bark.6]="*pushes your laptop closed*"
# --- bunny ---
BUILTIN_TONE[bunny.emoji]="🐰"
BUILTIN_TONE[bunny.noun]="bunny"
BUILTIN_TONE[bunny.task_line]="please work on: {task} 🥺"
BUILTIN_TONE[bunny.env_label]="hop away:"
BUILTIN_TONE[bunny.slip_label]="one carrot:"
BUILTIN_TONE[bunny.nuclear_label]="...i can't stop you:"
BUILTIN_TONE[bunny.bark._count]=6
BUILTIN_TONE[bunny.bark.0]="*nose twitch* u-um... it's focus time, {noun}..."
BUILTIN_TONE[bunny.bark.1]="*hides behind monitor* p-please don't commit right now..."
BUILTIN_TONE[bunny.bark.2]="*thump thump* no!! focus time!!"
BUILTIN_TONE[bunny.bark.3]="*soft ears droop* you said you'd focus..."
BUILTIN_TONE[bunny.bark.4]="*tugs your sleeve gently* not yet..."
BUILTIN_TONE[bunny.bark.5]="eep! {noun}! it's not commit time!"
# --- fox ---
BUILTIN_TONE[fox.emoji]="🦊"
BUILTIN_TONE[fox.noun]="fox"
BUILTIN_TONE[fox.task_line]="be clever and work on: {task}"
BUILTIN_TONE[fox.env_label]="outsmart the fox:"
BUILTIN_TONE[fox.slip_label]="one-time trick:"
BUILTIN_TONE[fox.nuclear_label]="just cheat (boring):"
BUILTIN_TONE[fox.bark._count]=6
BUILTIN_TONE[fox.bark.0]="*tilts head* oh? committing during focus time, {noun}?"
BUILTIN_TONE[fox.bark.1]="heh. nice try~ but it's focus time."
BUILTIN_TONE[fox.bark.2]="*flicks tail* nah. not right now."
BUILTIN_TONE[fox.bark.3]="what does the fox say? ...no commits, {noun}."
BUILTIN_TONE[fox.bark.4]="*curls around your keyboard* this is mine now."
BUILTIN_TONE[fox.bark.5]="clever {noun}~ but not clever enough to commit right now."
# --- robot ---
BUILTIN_TONE[robot.emoji]="🤖"
BUILTIN_TONE[robot.noun]="user"
BUILTIN_TONE[robot.task_line]="DESIGNATED TASK: {task}"
BUILTIN_TONE[robot.env_label]="OVERRIDE CODE:"
BUILTIN_TONE[robot.slip_label]="SINGLE-USE PASS:"
BUILTIN_TONE[robot.nuclear_label]="BYPASS ALL SAFETY:"
BUILTIN_TONE[robot.bark._count]=6
BUILTIN_TONE[robot.bark.0]="COMMIT REJECTED. FOCUS PROTOCOL ACTIVE."
BUILTIN_TONE[robot.bark.1]="ERROR: unauthorized commit during focus window."
BUILTIN_TONE[robot.bark.2]="ALERT: {noun} attempted commit outside permitted hours."
BUILTIN_TONE[robot.bark.3]="NEGATIVE. PRODUCTIVITY SUBROUTINE ENGAGED."
BUILTIN_TONE[robot.bark.4]="ACCESS DENIED. RETURN TO DESIGNATED TASK."
BUILTIN_TONE[robot.bark.5]="BEEP. no. focus mode is active, {noun}."
}
# --- Tone Resolution ----------------------------------------------------------
# Pick a random element from a comma-separated string
# Uses /dev/urandom instead of $RANDOM for better distribution
# ($RANDOM seeds from PID — sequential hook invocations get correlated values)
pick_random() {
local IFS=','
local -a items
read -ra items <<< "$1"
local count=${#items[@]}
(( count == 1 )) && { echo "${items[0]}"; return; }
local rand
rand=$(( $(od -An -tu4 -N4 /dev/urandom | tr -d ' ') % count ))
echo "${items[$rand]}"
}
# Resolve a tone field with fallback chain:
# [tone "x"] → [defaults] → builtin → hardcoded fallback
tone_cfg() {
local tone="$1"
local field="$2"
local fallback="${3:-}"
local val
# 1. [tone "x"] in config
val="$(cfg "tone.${tone}.${field}" "")"
[[ -n "$val" ]] && { echo "$val"; return; }
# 2. [defaults] in config
val="$(cfg "defaults.${field}" "")"
[[ -n "$val" ]] && { echo "$val"; return; }
# 3. builtin tone defaults
val="${BUILTIN_TONE[${tone}.${field}]:-}"
[[ -n "$val" ]] && { echo "$val"; return; }
# 4. hardcoded fallback
echo "$fallback"
}
# Collect all barks for a tone: builtin + user [tone "x"] + user [defaults]
get_tone_barks() {
local tone="$1"
local noun="$2"
local -a all_barks=()
# builtin barks
local builtin_count="${BUILTIN_TONE[${tone}.bark._count]:-0}"
local i
for (( i = 0; i < builtin_count; i++ )); do
all_barks+=("${BUILTIN_TONE[${tone}.bark.${i}]}")
done
# user barks from [tone "x"]
local user_count
user_count="$(cfg "tone.${tone}.bark._count" "0")"
for (( i = 0; i < user_count; i++ )); do
all_barks+=("$(cfg "tone.${tone}.bark.${i}" "")")
done
# user barks from [defaults] (apply to all tones)
local default_count
default_count="$(cfg "defaults.bark._count" "0")"
for (( i = 0; i < default_count; i++ )); do
all_barks+=("$(cfg "defaults.bark.${i}" "")")
done
if (( ${#all_barks[@]} == 0 )); then
echo "focus time is active."
return
fi
local bark_count=${#all_barks[@]}
local bark_idx
bark_idx=$(( $(od -An -tu4 -N4 /dev/urandom | tr -d ' ') % bark_count ))
local bark="${all_barks[$bark_idx]}"
echo "${bark//\{noun\}/$noun}"
}
# --- Message Rendering --------------------------------------------------------
# plain default tone — no personality
msg_default_tone() {
local env_var slip_file
env_var="$(cfg "override.env_var" "UNLEASH")"
slip_file="$(cfg "override.slip_file" ".leash-slip")"
echo ""
echo " 🐾 leash: focus time is active — schedule \"${BLOCK_SCHEDULE_NAME}\""
echo " ${BLOCK_DAYS} ${BLOCK_START}–${BLOCK_END} (${BLOCK_TZ})"
echo ""
if [[ -n "$BLOCK_TASK" ]]; then
echo " you should be working on: ${BLOCK_TASK}"
echo ""
fi
printf " %-20s %s=1 git commit ...\n" "override:" "$env_var"
printf " %-20s leash slip (or touch %s)\n" "one-time:" "$slip_file"
printf " %-20s git commit --no-verify\n" "nuclear:"
echo ""
}
show_block_message() {
init_builtin_tones
# pick a tone
local tone_str tone
tone_str="$(tone_cfg default tone "default")"
tone="$(pick_random "$tone_str")"
if [[ "$tone" == "default" ]]; then
msg_default_tone
return
fi
# resolve fields
local noun emoji task_line env_label slip_label nuclear_label
noun="$(pick_random "$(tone_cfg "$tone" noun "one")")"
emoji="$(tone_cfg "$tone" emoji "🐾")"
task_line="$(tone_cfg "$tone" task_line "you should be working on: {task}")"
env_label="$(tone_cfg "$tone" env_label "override:")"
slip_label="$(tone_cfg "$tone" slip_label "one-time:")"
nuclear_label="$(tone_cfg "$tone" nuclear_label "nuclear:")"
# get a bark with {noun} substituted
local bark
bark="$(get_tone_barks "$tone" "$noun")"
# substitute {noun} and {task} in task_line
task_line="${task_line//\{noun\}/$noun}"
task_line="${task_line//\{task\}/$BLOCK_TASK}"
# render
local env_var slip_file
env_var="$(cfg "override.env_var" "UNLEASH")"
slip_file="$(cfg "override.slip_file" ".leash-slip")"
echo ""
echo " ${emoji} ${bark}"
echo " schedule \"${BLOCK_SCHEDULE_NAME}\" is active"
echo " ${BLOCK_DAYS} ${BLOCK_START}–${BLOCK_END} (${BLOCK_TZ})"
echo ""
if [[ -n "$BLOCK_TASK" ]]; then
echo " ${task_line}"
echo ""
fi
printf " %-20s %s=1 git commit ...\n" "$env_label" "$env_var"
printf " %-20s leash slip (or touch %s)\n" "$slip_label" "$slip_file"
# if nuclear label is short, use it as a prefix; if long, it's standalone
if (( ${#nuclear_label} <= 20 )); then
printf " %-20s git commit --no-verify\n" "$nuclear_label"
else
echo " ${nuclear_label}"
fi
echo ""
}
# --- Hook Check (called by pre-commit hook) -----------------------------------
do_check() {
load_config
# check overrides first (fast exit)
local env_var slip_file
env_var="$(cfg "override.env_var" "UNLEASH")"
slip_file="$(cfg "override.slip_file" ".leash-slip")"
# env var override
if [[ "${!env_var:-}" == "1" ]]; then
return 0
fi
# slip file override (burns on use)
local git_root
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
local slip_path="${git_root:-.}/${slip_file}"
if [[ -f "$slip_path" ]]; then
rm -f "$slip_path"
echo " 🐾 leash: slip used — this one's free. don't make a habit of it~"
return 0
fi
# no schedules configured = no restrictions
(( ${#SCHEDULE_NAMES[@]} == 0 )) && return 0
if check_should_block; then
show_block_message >&2
return 1
fi
return 0
}
# --- Hook Generator -----------------------------------------------------------
generate_hook() {
local leash_path="$1"
cat << HOOK_EOF
#!/usr/bin/env bash
# git-leash pre-commit hook (auto-generated)
# This hook blocks commits during configured focus windows.
# Config: ~/.leash (global) and .leash (project-local)
# Override: set env var (default UNLEASH=1), touch slip file, or --no-verify
__leash_bin="${leash_path}"
# find leash: saved path > PATH > give up (allow commit)
if [[ -x "\$__leash_bin" ]]; then
"\$__leash_bin" check
elif command -v leash &>/dev/null; then
leash check
else
# leash not found — don't block commits, just warn once
echo " 🐾 leash: can't find leash script (was at \$__leash_bin)" >&2
echo " commits are unguarded. reinstall with: leash install" >&2
exit 0
fi
__leash_exit=\$?
# if leash blocked, fail fast — don't run backup hook
(( __leash_exit != 0 )) && exit \$__leash_exit
# chain: run existing pre-commit hook if it was backed up
if [[ -x "\$(dirname "\$0")/pre-commit.leash-backup" ]]; then
"\$(dirname "\$0")/pre-commit.leash-backup" "\$@"
exit \$?
fi
exit 0
HOOK_EOF
}
# --- Install / Uninstall ------------------------------------------------------
cmd_install() {
local global=0
while [[ $# -gt 0 ]]; do
case "$1" in
--global) global=1; shift ;;
*) echo "Unknown option: $1" >&2; return 1 ;;
esac
done
# resolve path to this script
local self_path
self_path="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
if (( global )); then
local hooks_dir="${HOME}/.leash-hooks"
local prev_hooks_path
prev_hooks_path="$(git config --global core.hooksPath 2>/dev/null || true)"
# save previous hooksPath for restore on uninstall
local state_file="${HOME}/.leash-hooks/.prev-hooks-path"
mkdir -p "$hooks_dir"
if [[ -n "$prev_hooks_path" && "$prev_hooks_path" != "$hooks_dir" ]]; then
echo "$prev_hooks_path" > "$state_file"
echo " saved previous core.hooksPath: ${prev_hooks_path}"
else
rm -f "$state_file"
fi
generate_hook "$self_path" > "${hooks_dir}/pre-commit"
chmod +x "${hooks_dir}/pre-commit"
git config --global core.hooksPath "$hooks_dir"
echo " 🐾 leash: installed globally"
echo " hooks path: ${hooks_dir}"
echo " config: ~/.leash"
echo ""
echo " tip: create ~/.leash with your schedule (see leash example)"
return 0
fi
# local install
local git_root
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "$git_root" ]]; then
echo "error: not in a git repository" >&2
return 1
fi
# resolve hooks directory (handles worktrees, custom git-dir, etc.)
local hooks_dir
hooks_dir="$(git rev-parse --git-path hooks 2>/dev/null)"
if [[ -z "$hooks_dir" ]]; then
hooks_dir="${git_root}/.git/hooks"
fi
mkdir -p "$hooks_dir"
# backup existing pre-commit hook
if [[ -f "${hooks_dir}/pre-commit" ]]; then
# don't back up if it's already a leash hook
if ! grep -q "git-leash" "${hooks_dir}/pre-commit" 2>/dev/null; then
mv "${hooks_dir}/pre-commit" "${hooks_dir}/pre-commit.leash-backup"
echo " backed up existing pre-commit hook → pre-commit.leash-backup"
fi
fi
generate_hook "$self_path" > "${hooks_dir}/pre-commit"
chmod +x "${hooks_dir}/pre-commit"
# stealth: add .leash and .leash-slip to .git/info/exclude
local exclude_file
exclude_file="$(git rev-parse --git-path info/exclude 2>/dev/null)"
if [[ -z "$exclude_file" ]]; then
exclude_file="${git_root}/.git/info/exclude"
fi
mkdir -p "$(dirname "$exclude_file")"
touch "$exclude_file"
for pattern in ".leash" ".leash-slip"; do
if ! grep -qxF "$pattern" "$exclude_file" 2>/dev/null; then
echo "$pattern" >> "$exclude_file"
fi
done
echo " 🐾 leash: installed to ${git_root}"
echo " hook: ${hooks_dir}/pre-commit"
echo " .leash and .leash-slip added to .git/info/exclude (stealth mode)"
echo ""
echo " tip: create .leash with your schedule (see leash example)"
# validate config if present
load_config
for sn in "${SCHEDULE_NAMES[@]:-}"; do
local sp="schedule.${sn}."
local ac bc
ac="$(cfg "${sp}allow._count" "0")"
bc="$(cfg "${sp}block._count" "0")"
if (( ac > 0 && bc > 0 )); then
leash_warn_allow_block "$sn"
fi
done
}
cmd_uninstall() {
local global=0
while [[ $# -gt 0 ]]; do
case "$1" in
--global) global=1; shift ;;
*) echo "Unknown option: $1" >&2; return 1 ;;
esac
done
if (( global )); then
local hooks_dir="${HOME}/.leash-hooks"
local state_file="${hooks_dir}/.prev-hooks-path"
rm -f "${hooks_dir}/pre-commit"
# restore previous hooksPath if we saved one
if [[ -f "$state_file" ]]; then
local prev_path
prev_path="$(cat "$state_file")"
rm -f "$state_file"
if [[ -n "$prev_path" ]]; then
git config --global core.hooksPath "$prev_path"
echo " restored previous core.hooksPath: ${prev_path}"
else
git config --global --unset core.hooksPath 2>/dev/null || true
fi
else
git config --global --unset core.hooksPath 2>/dev/null || true
fi
echo " 🐾 leash: uninstalled globally"
return 0
fi
local git_root
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "$git_root" ]]; then
echo "error: not in a git repository" >&2
return 1
fi
local hooks_dir
hooks_dir="$(git rev-parse --git-path hooks 2>/dev/null)"
if [[ -z "$hooks_dir" ]]; then
hooks_dir="${git_root}/.git/hooks"
fi
if [[ -f "${hooks_dir}/pre-commit" ]] && grep -q "git-leash" "${hooks_dir}/pre-commit" 2>/dev/null; then
rm -f "${hooks_dir}/pre-commit"
# restore backup if exists
if [[ -f "${hooks_dir}/pre-commit.leash-backup" ]]; then
mv "${hooks_dir}/pre-commit.leash-backup" "${hooks_dir}/pre-commit"
echo " restored previous pre-commit hook from backup"
fi
echo " 🐾 leash: uninstalled from ${git_root}"
else
echo " leash hook not found in this repo"
fi
}
# --- Slip ---------------------------------------------------------------------
cmd_slip() {
local git_root slip_file slip_path
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "$git_root" ]]; then
echo "error: not in a git repository" >&2
return 1
fi
load_config
slip_file="$(cfg "override.slip_file" ".leash-slip")"
slip_path="${git_root}/${slip_file}"
touch "$slip_path"
echo " 🐾 leash: slip created — your next commit gets a free pass"
echo " (${slip_file} will be auto-deleted after one use)"
}
# --- Status -------------------------------------------------------------------
cmd_status() {
load_config
init_builtin_tones
local git_root
git_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
echo ""
echo " 🐾 git-leash status"
echo " ─────────────────────"
echo ""
# config sources
if [[ -f "${HOME}/.leash" ]]; then
echo " global config: ~/.leash"
else
echo " global config: (none)"
fi
if [[ -n "$git_root" && -f "${git_root}/.leash" ]]; then
echo " project config: ${git_root}/.leash"
else
echo " project config: (none)"
fi
echo ""
# schedules
if (( ${#SCHEDULE_NAMES[@]} == 0 )); then
echo " no schedules configured"
else
for sn in "${SCHEDULE_NAMES[@]}"; do
local sp="schedule.${sn}."
local days start end tz
days="$(cfg "${sp}days" "mon,tue,wed,thu,fri")"
start="$(cfg "${sp}start" "")"
end="$(cfg "${sp}end" "")"
tz="$(cfg "${sp}timezone" "local")"
# check if currently active
local active=" "
if [[ -n "$start" && -n "$end" ]]; then
local current_day current_time_str
if [[ "$tz" == "local" ]]; then
current_day="$(date +%a)"
current_time_str="$(date +%H:%M)"
else
current_day="$(TZ="$tz" date +%a)"
current_time_str="$(TZ="$tz" date +%H:%M)"
fi
current_day="${current_day,,}"
if day_matches "$days" "$current_day"; then
local start_min end_min now_min
start_min="$(time_to_minutes "$start")"
end_min="$(time_to_minutes "$end")"
now_min="$(time_to_minutes "$current_time_str")"
if is_in_time_window "$start_min" "$end_min" "$now_min"; then
active="▶ "
fi
fi
fi
local time_range="${start:-??:??}–${end:-??:??}"
echo " ${active}schedule \"${sn}\": ${days} ${time_range} (${tz})"
# show allow/block rules
local allow_count block_count
allow_count="$(cfg "${sp}allow._count" "0")"
block_count="$(cfg "${sp}block._count" "0")"
local i
for (( i = 0; i < allow_count; i++ )); do
echo " allow: $(cfg "${sp}allow.${i}" "")"
done
for (( i = 0; i < block_count; i++ )); do
echo " block: $(cfg "${sp}block.${i}" "")"
done
done
fi
echo ""
# task
local task
task="$(cfg "task.current" "")"
if [[ -n "$task" ]]; then
echo " current task: ${task}"
else
echo " current task: (none)"
fi
# tone
local tone noun
tone="$(tone_cfg default tone "default")"
noun="$(cfg "defaults.noun" "(per-tone defaults)")"
echo " tone: ${tone}"
echo " noun: ${noun}"
# override config
local env_var slip_file
env_var="$(cfg "override.env_var" "UNLEASH")"
slip_file="$(cfg "override.slip_file" ".leash-slip")"
echo " override env: ${env_var}=1"
echo " slip file: ${slip_file}"
# current time
echo ""
echo " current time: $(date '+%a %H:%M %Z')"
# check if would block right now
if (( ${#SCHEDULE_NAMES[@]} > 0 )); then
if check_should_block; then
echo " status: BLOCKED (schedule \"${BLOCK_SCHEDULE_NAME}\")"
else
echo " status: free to commit"