-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshelf.sh
More file actions
828 lines (779 loc) · 26.5 KB
/
Copy pathshelf.sh
File metadata and controls
828 lines (779 loc) · 26.5 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
##############################################################
# shelf.sh
# Useful shell functions (source from ~/.zshrc)
##############################################################
# This file is auto-generated by build.sh. DO NOT EDIT!
##############################################################
# changedir.sh
# Used by other shelf utils to change working-directory.
##############################################################
changedir() {
# Change the current working-directory to the given path
# and print the transition to stdout.
local TARGET="$1"
if [[ -z "${TARGET}" ]]; then
TARGET="${HOME}"
fi
TARGET="$(realpath -m "${TARGET}")"
echo "${PWD} ${TARGET}" | sed "s|${HOME}|~|g"
cd "${TARGET}"
}
##############################################################
# git.sh
# Little git helpers.
##############################################################
function git-go() {
if [ -d ".git" ]; then
echo ".git already exists in the current working-directory."
return 1
fi
local PARENT=".."
local SEARCH="$PARENT"
while true; do
if [ -d "$SEARCH/.git" ]; then
echo "$PWD"
cd "$SEARCH"
return 0
elif [ "$(realpath "$SEARCH")" = "/" ]; then
echo "No parent .git project."
return 1
else
SEARCH="$PARENT/$SEARCH"
fi
done
}
function git-scrub() {
local CURRENT_BRANCH="$(git branch --show-current)"
if [[ "$CURRENT_BRANCH" != "main" && "$CURRENT_BRANCH" != "master" ]]; then
echo "Must be on main or master branch to git-scrub!"
return 1
fi
for branch in $(git branch --merged HEAD | grep -vw "$CURRENT_BRANCH"); do
git branch -d "$branch"
done
}
git-strip() {
local files=()
local since_ref=""
while [[ $# -gt 0 ]]; do
case $1 in
--since)
since_ref="$2"
shift 2
;;
*)
files+=("$1")
shift
;;
esac
done
if [[ -n "$since_ref" ]]; then
echo "Finding files changed since $since_ref..."
local git_files=()
while IFS= read -r -d $'\0' file; do
git_files+=("$file")
done < <(git diff --name-only -z --diff-filter=ACMR "$since_ref")
files+=("${git_files[@]}")
fi
if [[ ${#files[@]} -eq 0 ]]; then
echo "Usage: git-strip [--since <ref>] [files...]"
echo " --since <ref> Process files changed since git ref"
echo " files... Process specific files"
return 1
fi
local processed=0
for file in "${files[@]}"; do
if [[ ! -f "$file" ]]; then
echo "Skipping $file (not a regular file)"
continue
fi
if sed --version &>/dev/null 2>&1; then
sed -i 's/[[:space:]]*$//' "$file"
else
sed -i '' 's/[[:space:]]*$//' "$file"
fi
echo "✓ $file"
((processed++))
done
echo ""
echo "Processed $processed file(s)"
}
##############################################################
# kubectl.sh
# Common kubectl shortcuts
##############################################################
alias k='kubectl'
##############################################################
# python.sh
# venv etc.
##############################################################
alias activate='source ./venv/bin/activate'
##############################################################
# repo.sh
# Quickly clone/search/switch-to repo directories.
##############################################################
REPO_ROOT="${SHELF_REPOS:-$(realpath ~/repos)}"
REPO_STAT="%Y %W %n"
REPO_LIST="$REPO_ROOT/_manifest.txt"
REPO_HOST="_server.txt"
repo_git_all() {
find "${REPO_ROOT}" -mindepth 4 -maxdepth 4 -type d -name .git -printf "%p "
}
repo_init() {
if [[ ! -d "${REPO_ROOT}" ]]; then mkdir -p "${REPO_ROOT}"; fi
if [[ ! -f "${REPO_LIST}" ]]; then repo_git_all | xargs -- stat -c "${REPO_STAT}" | sed "s|${REPO_ROOT}/||;s|/\.git\$||" > "${REPO_LIST}"; fi
}
repo_reset() {
if [[ -f "${REPO_LIST}" ]]; then
>&2 echo "Resetting ${REPO_LIST}"
rm -f "${REPO_LIST}"
fi
repo_init
}
repo_stat() {
local SELECT="$1"
stat -c "${REPO_STAT}" "${REPO_ROOT}/${SELECT}/.git" | sed "s|${REPO_ROOT}/||;s|/\.git\$||"
}
repo_usage() {
>&2 echo "Usage: repo [-c <URL> | -s | [-d] <TERMS...>]
Searches cloned repositories for given TERMS and changes-dir to the match.
More terms can be added to narrow down the search. Changes directory to the
matching repository if only one match is found.
-b, --browse Scroll through all cloned repositories (or a specific remote).
--clone Clone a repository with the given terms.
-c Sort by git clone date.
-d Sort by repo selection history.
-g Sort by git activity date.
If no terms are given, switches to most recently-accessed repo."
}
repo() {
repo_init
local GIT_URI_REGEX='^git@[A-Za-z0-9_.-]+(:[0-9]+)?:[A-Za-z0-9_.\/-]+\.git$'
local GIT_HTTP_REGEX='^https?://[A-Za-z0-9_.-]+(/[A-Za-z0-9_.\/-]+)?\.git$'
local ACTION="search"
local ORDER="name"
local REMOTE=""
local SEARCH=""
local FILTER=""
local MATCHES=""
local COUNT=""
local SORTER="sort"
local FIELDS="-nk3,3"
local GITURI=""
local SERVER=""
local SELECT=""
case "$1" in
-h|--help) repo_usage; return 0 ;;
-b|--browse) ACTION="browse"; REMOTE="$2"; ;;
--clone) ACTION="clone"; REMOTE="$2"; SEARCH="$3" ;;
-c) ORDER="clone"; shift 1; SEARCH="$*" ;;
-d) ORDER="history"; shift 1; SEARCH="$*" ;;
-g) ORDER="activity"; shift 1; SEARCH="$*" ;;
-n) ORDER="name"; shift 1; SEARCH="$*" ;;
*) SEARCH="$*" ;;
esac
case "${ACTION}" in
browse)
if [[ -z "${REMOTE}" ]]; then
tree -dL3 "${REPO_ROOT}" | less
return $?
elif [[ -d "${REPO_ROOT}/${REMOTE}" ]]; then
tree -dL2 "${REPO_ROOT}/${REMOTE}" | less
return $?
else
>&2 echo "Remote ${REMOTE} is not one of the known remotes:"
tree -dL1 "${REPO_ROOT}"
return 1
fi
;;
clone)
if [[ -z "${SEARCH}" ]]; then
GITURI="${REMOTE}"
if [[ "${GITURI}" =~ $GIT_URI_REGEX ]]; then
SEARCH="${GITURI##*:}"
SEARCH="${SEARCH%.git}"
SERVER="${GITURI%:*}"
SERVER="${SERVER#git@}"
elif [[ "${GITURI}" =~ $GIT_HTTP_REGEX ]]; then
SERVER="${GITURI#*://}"
SERVER="${SERVER%%/*}"
SEARCH="${GITURI#*://}"
SEARCH="${SEARCH#*/}"
SEARCH="${SEARCH%.git}"
else
>&2 echo "Either provide a git@ URI, an HTTPS URL or <remote> <name>/<repo>"
return 1
fi
REMOTE=""
for name in "${REPO_ROOT}"/*; do
if [[ ! -d "${name}" || ! -f "${name}/${REPO_HOST}" ]]; then continue; fi
name="$(basename "${name}")"
if [[ "${SERVER}" = "$(cat "${REPO_ROOT}/${name}/${REPO_HOST}")" ]]; then
REMOTE="${name}"
break
fi
done
if [[ -z "${REMOTE}" ]]; then
>&2 echo "Remote not found for ${SERVER}"
REMOTE="${SERVER%%[^a-zA-Z0-9]*}"
if [[ -z "${REMOTE}" ]]; then
>&2 echo "Remote name is empty. Cannot create remote."
return 1
elif [[ -d "${REPO_ROOT}/${REMOTE}" ]]; then
>&2 echo "Remote ${REMOTE} already exists."
return 1
fi
>&2 echo "Creating remote ${REMOTE} for ${SERVER}"
mkdir -p "${REPO_ROOT}/${REMOTE}"
echo "${SERVER}" > "${REPO_ROOT}/${REMOTE}/${REPO_HOST}"
fi
else
# REMOTE and SEARCH given separately (e.g. repo --clone github quiteclose/shelf)
if [[ ! -f "${REPO_ROOT}/${REMOTE}/${REPO_HOST}" ]]; then
>&2 echo "Remote ${REMOTE} does not have a ${REPO_HOST} file."
return 1
fi
SERVER="$(cat "${REPO_ROOT}/${REMOTE}/${REPO_HOST}")"
GITURI="git@${SERVER}:${SEARCH}.git"
fi
if [[ ! -d "${REPO_ROOT}/${REMOTE}" ]]; then
>&2 echo "Remote ${REMOTE} does not exist. Try cloning a full git@ URI."
return 1
fi
if [[ ! -f "${REPO_ROOT}/${REMOTE}/${REPO_HOST}" ]]; then
>&2 echo "Remote ${REMOTE} does not have a ${REPO_HOST} file."
return 1
fi
if [[ -e "${REPO_ROOT}/${REMOTE}/${SEARCH}" ]]; then
>&2 echo "${SEARCH} already exists at ${REPO_ROOT}/${REMOTE}/${SEARCH}"
return 1
fi
SERVER="$(cat "${REPO_ROOT}/${REMOTE}/${REPO_HOST}")"
SELECT="${REMOTE}/${SEARCH}"
mkdir -p "$(dirname "${REPO_ROOT}/${SELECT}")"
if [[ -z "${GITURI}" ]]; then
GITURI="git@${SERVER}:${SEARCH}.git"
fi
git clone "${GITURI}" "${REPO_ROOT}/${SELECT}"
;;
search)
FILTER="$(echo "${SEARCH}" | sed 's/ /\\\|/g')"
if [[ "${ORDER}" = "activity" ]]; then FIELDS="-nk1,3"; fi
if [[ "${ORDER}" = "clone" ]]; then FIELDS="-nk2,3"; fi
if [[ "${ORDER}" = "history" ]]; then FIELDS=""; SORTER="cat"; fi
if [[ "${ORDER}" = "name" ]]; then FIELDS="-k3"; fi
MATCHES="$(${SORTER} ${FIELDS} "${REPO_LIST}" | awk '{print $NF}')"
while [[ -n "$1" && -n "${MATCHES}" ]]; do
MATCHES="$(echo "${MATCHES}" | grep -i "$1")"
shift 1
done
if [[ -z "${SEARCH}" ]]; then
SELECT="$(echo "${MATCHES}" | tail -n1 | xargs)"
if [[ -z "${SELECT}" ]]; then
>&2 echo "Unexpected: No repositories found?"
repo_reset
return 1
fi
else
COUNT="$(echo "${MATCHES}" | wc -l | xargs)"
if [[ "${COUNT}" -eq 1 ]]; then
SELECT="$(echo "${MATCHES}" | head -n1 | xargs)"
else
>&2 echo "Found ${COUNT} matching repositories:"
echo "${MATCHES}" | sed 's/^/ /' | grep -i --color "${FILTER}"
fi
fi
;;
esac
if [[ -n "${SELECT}" ]]; then
local MATCH="$(grep -m1 -w "${SELECT}" "${REPO_LIST}")"
if [[ -n "${MATCH}" ]]; then
local OTHERS="$(grep -vw "${SELECT}" "${REPO_LIST}")"
{ echo "${OTHERS}"; echo "${MATCH}"; } > "${REPO_LIST}"
else
repo_stat "${SELECT}" >> "${REPO_LIST}"
fi
changedir "${REPO_ROOT}/${SELECT}"
fi
return 0
}
##############################################################
# shoes.sh
# Manages a common token file and cluster login files. Source
# the token with -t, edit it with -e. Name a cluster to source
# a matching cluster file. If multiple cluster files match,
# falls-back to searching for the given name. You can force
# this search-behaviour with -s if you don't want to login.
# When naming a cluster, use -e and -c to create a new cluster
# file with the given name.
##############################################################
function shoes() {
local SHOES_PATH="${SHELF_SHOES:-$HOME/.local/share/shoes}"
local ACTION=""
local CLUSTER=""
mkdir -p "${SHOES_PATH}"{,/cluster}
case "$1" in
-c|--create)
ACTION="create"
CLUSTER="$2"
;;
-e|--edit)
ACTION="edit"
CLUSTER="$2"
;;
-h|--help)
ACTION="help"
;;
-s|--search)
ACTION="search"
CLUSTER="$2"
;;
-t|--token)
ACTION="token"
CLUSTER="$2"
;;
*)
ACTION="login"
CLUSTER="$1"
;;
esac
case "$ACTION" in
help)
echo "Usage: shoes [OPTIONS] <CLUSTER>"
echo " Login to a cluster with a saved token. If no single cluster-file"
echo " matches the given name, list all matches. Non-login actions are"
echo " triggered via options:"
echo
echo " -c, --create Create a cluster-file with the given name."
echo " -e, --edit Edit the token (or cluster-file if given.)"
echo " -h, --help Display this help message."
echo " -s, --search List matching cluster files."
echo " -t, --token Source the token."
return 0
;;
create)
if [ -z "$CLUSTER" ]; then
>&2 echo "Name a cluster to create."
return 1
fi
if [ -e "$SHOES_PATH/cluster/$CLUSTER.sh" ]; then
>&2 echo "Cluster file already exists at $SHOES_PATH/cluster/$CLUSTER.sh"
return 1
fi
>&2 echo "Editing cluster file at $SHOES_PATH/cluster/$CLUSTER.sh"
"${EDITOR:-vi}" "$SHOES_PATH/cluster/$CLUSTER.sh"
return $?
;;
edit)
if [ -n "$CLUSTER" ]; then
if [ -e "$SHOES_PATH/cluster/$CLUSTER.sh" ]; then
>&2 echo "Editing cluster file at $SHOES_PATH/cluster/$CLUSTER.sh"
"${EDITOR:-vi}" "$SHOES_PATH/cluster/$CLUSTER.sh"
return $?
fi
>&2 echo "Cluster file does not exist at $SHOES_PATH/cluster/$CLUSTER.sh"
return 1
fi
>&2 echo -n "Backing up token: "
cp -v "$SHOES_PATH/_token.txt" "$SHOES_PATH/_token.txt.bak"
>&2 echo "Editing token at $SHOES_PATH/_token.txt"
>&2 echo "If you want to source the token, run:"
>&2 echo " shoes -t"
"${EDITOR:-vi}" "$SHOES_PATH/_token.txt"
return $?
;;
token)
if [ -n "$CLUSTER" ]; then
>&2 echo "Error: Do not specify a cluster when sourcing the token."
return 1
fi
>&2 echo "Sourcing token from $SHOES_PATH/_token.txt"
export VAULT_TOKEN="$(cat "$SHOES_PATH/_token.txt")"
return 0
;;
login)
if [ -z "$CLUSTER" ]; then
>&2 echo "Name a cluster to search for."
return 1
fi
if [ -e "$SHOES_PATH/cluster/$CLUSTER.sh" ]; then
>&2 echo "Sourcing cluster file at $SHOES_PATH/cluster/$CLUSTER.sh"
source "$SHOES_PATH/cluster/$CLUSTER.sh"
return $?
fi
;& # fall-through if no cluster file matches exactly
search)
if [ -z "$CLUSTER" ]; then
CLUSTER=".*"
fi
local CLUSTER_LIST="$(ls "$SHOES_PATH/cluster" | grep -v '^_' | awk -F. '{print $1}' | sort)"
local MATCHES="$(grep "$CLUSTER" <<< "$CLUSTER_LIST")"
local LENGTH="$(wc -l <<< "$MATCHES" | xargs)"
if [ "$MATCHES" = "" ]; then
>&2 echo "Found 0 clusters matching \"$CLUSTER\""
return 1
elif [ "$LENGTH" -gt 1 ]; then
ACTION="search"
fi
if [ "$ACTION" = "search" ]; then
>&2 echo "Found $LENGTH matching clusters:"
sed 's/^/ /' <<< "$MATCHES" | grep --color "$CLUSTER"
return 0
else
>&2 echo "Sourcing cluster file at $SHOES_PATH/cluster/$MATCHES.sh"
source "$SHOES_PATH/cluster/$MATCHES.sh"
fi
;;
esac
}
##############################################################
# tempdir.sh
# Quickly create/search/switch-to temporary directories.
##############################################################
tempdir_usage() {
>&2 echo "Usage: tempdir -c | -p | [<SORT>] [<TERMS...>] [--browse]
Creates & searches tempdirs. Changes to that directory when only one matches.
-c Create a tempdir (optionally with a <LABEL>)
-p, --prune Delete empty tempdirs older than 7 days.
-b, --browse Do not changedir.
-t, --tree View the tempdirs as a tree.
SORT options (upper-case reverses the sort):
-d,-D Sort by tempdir selection history.
-f,-F Sort by file-name.
-n,-N Sort by name.
TERMS: A series of filters that apply successively to previous results.
Find expressions start with a dash (-) (or ! for negation) and
are applied to each matching tempdir. They generate output that
can be filtered or browsed. Find expressions come in a series of
key-value pairs, and are passed directly to the find command.
Note that only the following find expressions are allowed:
-ctime
-maxdepth
-mindepth
-mtime
-name
-type
Grep filters are terms that DO NOT start with a dash. They are
fed the input of the previous find command (or grep.) Successive
grep filters reduce the results. You can generate more results
by issuing a find expression on the current-matches.
Note that if the 1st term is a grep filter, a default find
command will be used to seed the initial search.
"
}
TEMPDIR_ROOT="${SHELF_TEMPDIRS:-$(realpath -m ~/tempdirs)}"
TEMPDIR_LIST="${TEMPDIR_ROOT}/_manifest.txt"
TEMPDIR_FIND_PREFIX=( \
\( \
-name .git -o -name .github -o -name node_modules -o -name venv -o -name .venv \
-o -name dist -o -name build -o -name out -o -name target -o -name __pycache__ \
-o -name .idea -o -name .vscode -o -name .tox -o -name .eggs -o -name .cache \
-o -name .mypy_cache -o -name .pytest_cache -o -name .egg-info \
-o -name .DS_Store -o -name .directory -o -name .project -o -name .classpath \
-o -name .settings -o -name .gitignore -o -name .gitattributes -o -name .gitmodules \
-o -name .hg -o -name .hgignore -o -name .hgrc -o -name .svn -o -name .bzr \
-o -name LICENSE -o -name COPYING -o -name README.md -o -name CHANGELOG.md \
\) \
-prune -o \
)
TEMPDIR_FIND_SUFFIX=(-print)
tempdir_all() {
find "${TEMPDIR_ROOT}" -mindepth 1 -maxdepth 1 -type d "${TEMPDIR_FIND_SUFFIX[@]}" | sed "s|${TEMPDIR_ROOT}/||"
}
tempdir_create() {
tempdir_init
local STAMP="$(date '+%y%m%d')"
mktemp -d -p "${TEMPDIR_ROOT}" "${STAMP}.XXXXXX" | sed "s|^${TEMPDIR_ROOT}/||" | tee -a "${TEMPDIR_LIST}"
}
tempdir_prune() {
tempdir_init
local PRUNED=0
while IFS= read -r dir; do
local FULL="${TEMPDIR_ROOT}/${dir}"
if [[ ! -d "${FULL}" ]]; then continue; fi
local CONTENTS
CONTENTS="$(find "${FULL}" -mindepth 1 -maxdepth 1 2>/dev/null)"
if [[ -z "${CONTENTS}" ]]; then
>&2 echo "Pruning empty tempdir: ${dir}"
rm -rf "${FULL}"
((PRUNED++))
fi
done < <(find "${TEMPDIR_ROOT}" -mindepth 1 -maxdepth 1 -type d -mtime +7 -printf "%f\n")
if [[ "${PRUNED}" -gt 0 ]]; then
>&2 echo "Pruned ${PRUNED} empty tempdir(s). Resetting manifest."
tempdir_reset
else
>&2 echo "Nothing to prune."
fi
}
tempdir_init() {
if [[ ! -d "${TEMPDIR_ROOT}" ]]; then mkdir -p "${TEMPDIR_ROOT}"; fi
if [[ ! -f "${TEMPDIR_LIST}" ]]; then tempdir_all | sort -n > "${TEMPDIR_LIST}"; fi
}
tempdir_reset() {
if [[ -f "${TEMPDIR_LIST}" ]]; then
>&2 echo "Resetting ${TEMPDIR_LIST}"
rm -f "${TEMPDIR_LIST}"
fi
tempdir_init
}
tempdir_sort_by_filename() {
awk -F/ '{print $NF, $0}' | sort | cut -d' ' -f2-
}
tempdir_sort_by_history() {
awk -F/ '
NR==FNR { o[$1]=++n; next }
{ key=$1; print (o[key] ? o[key] : 999999), $0 }
' <(tac "${TEMPDIR_LIST}") - | sort -n | cut -d' ' -f2-
}
tempdir_sort_by_name() {
sort "${1:-/dev/stdin}"
}
tempdir_reverse_by_filename() {
tempdir_sort_by_filename | tac
}
tempdir_reverse_by_history() {
tempdir_sort_by_history | tac
}
tempdir_reverse_by_name() {
tac "${1:-/dev/stdin}"
}
tempdir() {
tempdir_init
case "$1" in
-c|--create) changedir "${TEMPDIR_ROOT}/$(tempdir_create)"; return $?;;
-p|--prune) tempdir_prune; return $?;;
-h|--help) tempdir_usage; return 0;;
esac
local ACTION="seek"
local RENDER="list"
local GIVEN_ARGS=()
local TERM_SORT="-d"
local TERMS=()
local RESULTS=""
local MATCHES=""
local COUNT=0
local SORTER=()
local SELECT=""
local FIND_GLOBAL=()
local FIND_EXPR=()
local GREP_PREFIX=(-iE)
local TREE_PREFIX=(-L3)
local HISTORY_MATCH=""
local HISTORY_ALL=""
if [[ "$1" =~ ^-(d|f|n|D|F|N)$ ]]; then
TERM_SORT="$1";
shift;
fi
case "${TERM_SORT}" in
-d) SORTER=tempdir_sort_by_history;;
-f) SORTER=tempdir_sort_by_filename;;
-n) SORTER=tempdir_sort_by_name;;
-D) SORTER=tempdir_reverse_by_history;;
-F) SORTER=tempdir_reverse_by_filename;;
-N) SORTER=tempdir_reverse_by_name;;
esac
MATCHES="$(tempdir_all)"
if [ -z "${MATCHES}" ]; then
>&2 echo "No tempdirs found."
return 1
fi
GIVEN_ARGS=("$@")
if [ -z "${GIVEN_ARGS[*]}" ]; then
MATCHES="$(echo "${MATCHES}" | $SORTER)"
elif [[ ! "$1" =~ ^-[^-] && ! "$1" == "!" ]]; then
FIND_GLOBAL=(-mindepth 0 -maxdepth 2)
RESULTS="$(echo "${MATCHES}" | sed "s|^|${TEMPDIR_ROOT}/|" | xargs -d '\n' -I{} find {} "${FIND_GLOBAL[@]}" "${TEMPDIR_FIND_PREFIX[@]}" "${FIND_EXPR[@]}" "${TEMPDIR_FIND_SUFFIX[@]}" | sed "s|${TEMPDIR_ROOT}/||" | $SORTER)"
fi
while [ -n "$1" ]; do
case "$1" in
-b|--browse) ACTION="browse"; shift 1; continue;;
-t|--tree) RENDER="tree"; shift 1; continue;;
esac
if [[ "$1" =~ ^-[^-] || "$1" == "!" ]]; then
FIND_GLOBAL=()
FIND_EXPR=()
while [[ "$1" =~ ^-[^-] || "$1" == "!" ]]; do
if [[ "$1" == "-name" ]]; then
TERMS+=("$(echo "$2" | sed 's|*|.*|g;s|?|.|g')")
fi
case "$1" in
-maxdepth|-mindepth)
FIND_GLOBAL+=("$1" "$2"); shift 2;;
-ctime|-mtime|-name|-type)
FIND_EXPR+=("$1" "$2"); shift 2;;
-o|-or|-a|-and|!|-not)
FIND_EXPR+=("$1"); shift 1;;
*) >&2 echo "Blocked find option: $1"; return 1;;
esac
done
TERMS+=("/")
RESULTS="$(echo "${MATCHES}" | sed "s|^|${TEMPDIR_ROOT}/|" | xargs -d '\n' -I{} find {} "${FIND_GLOBAL[@]}" "${TEMPDIR_FIND_PREFIX[@]}" "${FIND_EXPR[@]}" "${TEMPDIR_FIND_SUFFIX[@]}" | sed "s|${TEMPDIR_ROOT}/||" | $SORTER)"
else
TERMS+=("$1")
RESULTS="$(echo "${RESULTS}" | grep "${GREP_PREFIX[@]}" "$1" | $SORTER)"
shift 1
fi
MATCHES="$(echo "${RESULTS}" | sed "s/\/.*//" | awk '!seen[$0]++')"
done
if [ ${#GIVEN_ARGS[@]} -eq 0 ]; then
SELECT="$(echo "${MATCHES}" | head -n1 | xargs)"
if [ -z "${SELECT}" ]; then
>&2 echo "Unexpected: No tempdirs found?"
tempdir_reset
return 1
fi
else
if [ -t 1 ]; then
GREP_PREFIX+=(--color=always)
fi
COUNT="$(echo "${MATCHES}" | wc -l | xargs)"
if [ "$COUNT" -eq 1 ] && [ "$ACTION" != "browse" ]; then
SELECT="$(echo "${MATCHES}" | head -n1 | xargs)"
elif [ "${RENDER}" = "tree" ]; then
echo "${MATCHES}" | sed "s|^|${TEMPDIR_ROOT}/|" | xargs -d '\n' -- tree --noreport "${TREE_PREFIX[@]}" | grep "${GREP_PREFIX[@]}" "^|$(IFS="|"; echo "${TERMS[*]}")" | less -RF
elif [ "${RENDER}" = "list" ]; then
>&2 echo "Found ${COUNT} matching tempdirs."
echo "${RESULTS}" | sed "s|^${TEMPDIR_ROOT}/| |" | grep "${GREP_PREFIX[@]}" "^|$(IFS="|"; echo "${TERMS[*]}")" | less -RF
fi
fi
if [ -n "${SELECT}" ] && [ "${ACTION}" = "seek" ]; then
SELECT="$(echo "${SELECT}" | sed "s|^${TEMPDIR_ROOT}/||;s|/$||")"
HISTORY_MATCH="$(grep -wm1 "${SELECT}" "${TEMPDIR_LIST}")"
if [ -n "${HISTORY_MATCH}" ]; then
HISTORY_ALL="$(grep -vw "${SELECT}" "${TEMPDIR_LIST}")"
{ echo "${HISTORY_ALL}"; echo "${HISTORY_MATCH}"; } > "${TEMPDIR_LIST}"
else
echo "${SELECT}" >> "${TEMPDIR_LIST}"
fi
changedir "${TEMPDIR_ROOT}/${SELECT}"
fi
return 0
}
##############################################################
# timestamp.sh
# Records lines of text along with a timestamp. Use with a -
# to add a note to the last timestamp, or with --all to see
# with notes.
##############################################################
function ts() {
local STAMP="$(date -u '+%y%m%d.%H%MZ')"
local TXT="timestamps.txt"
if [ -z "$1" ]; then
if [ -e "$TXT" ]; then
grep --color '^[0-9]\S*' <(cat "$TXT"; echo "$STAMP <<< Current time.")
else
echo "$STAMP <<< Current time." | grep --color '^\S*'
fi
elif [[ "$*" = "--help" ]]; then
echo "Usage: ts [OPTIONS] [MESSAGE]"
echo "Record a message to timestamps.txt along with a timestamp."
echo
echo " - Add a note to the last timestamp."
echo " --all Show all timestamps with notes."
echo
elif [[ "$*" = "--all" ]]; then
grep --color '^\S*' <(cat "$TXT"; echo "$STAMP <<< Current time.")
elif [[ "$*" = "-" ]]; then
grep '^[0-9]' "$TXT" | tail -n1 | grep --color '^\S*'
echo "Enter notes:" | grep --color '.*'
sed 's/^/ /' >> "$TXT"
echo "Use \"ts --all\" to see notes." | grep --color '.*'
else
echo "$STAMP $*" | tee -a "$TXT" | grep --color '^\S*'
fi
}
function tsl() {
ts | sed 's/Z/+0000/' | while read -r line; do
local GIVEN_STAMP="$(awk '{print $1}' <<< "$line")"
local CONVERTED_STAMP="$(/bin/date -j -f '%y%m%d.%H%M%z' "$GIVEN_STAMP" '+%y%m%d.%H%M%z')"
sed "s/$GIVEN_STAMP/$CONVERTED_STAMP/" <<< "$line"
done | grep --color '^\S*'
}
##############################################################
# workspace.sh
# Quickly create/search/switch-to project directories. Run
# with any term to search existing workspaces (or to switch to
# that workspace if only one is matched.) Use -d to sort by
# timestamp or -c to create a new workspace.
##############################################################
function workspace() {
local WORKSPACE_ROOT="${SHELF_WORKSPACES:-$HOME/workspaces}"
local ACTION=""
local ORDER="name"
local LABEL=""
case "$1" in
-c|--create)
ACTION="create"
LABEL="$2"
;;
-h|--help)
ACTION="help"
;;
-d|--date)
ORDER="date"
ACTION="goto"
LABEL="$2"
;;
*)
ACTION="goto"
LABEL="$1"
;;
esac
case "$ACTION" in
help)
echo "Usage: workspace [OPTIONS] <LABEL>"
echo "Switch to a workspace with the given label. Or, if an option is given:"
echo
echo " -c, --create Create a workspace with the given label."
echo " -h, --help Display this help message."
echo
echo "If no argument is given, switch to the latest workspace."
return 0
;;
create)
if [ -z "$LABEL" ]; then
>&2 echo "Provide a label to create a workspace."
return 1
fi
local TIMESTAMP="$(date '+%y%m%d')"
local WORKSPACE_PATH="$WORKSPACE_ROOT/$LABEL.$TIMESTAMP"
if [ -e "$WORKSPACE_PATH" ]; then
>&2 echo "Workspace already exists at $WORKSPACE_PATH"
return 1
fi
>&2 mkdir -p "$WORKSPACE_PATH"
>&2 echo "Leaving $PWD"
cd "$WORKSPACE_PATH"
return $?
;;
*)
if [ -z "$LABEL" ]; then
>&2 echo "Leaving $PWD"
cd "$(ls -td "$WORKSPACE_ROOT"/* | head -n1)"
return 0
fi
local WORKSPACES="$(ls -td "$WORKSPACE_ROOT"/* | awk -F/ '{print $NF}')"
if [ "$ORDER" = "date" ]; then
local WORKSPACE_LIST="$(awk -F. '{print $2,$0}' <<< "$WORKSPACES" | sort -n | awk '{print $2}')"
else
local WORKSPACE_LIST="$(sort <<< "$WORKSPACES")"
fi
if ! grep -q "$LABEL" <<< "$WORKSPACE_LIST"; then
>&2 echo "Found 0 workspaces matching \"$LABEL\""
return 1
else
local MATCHES="$(grep --color "$LABEL" <<< "$WORKSPACE_LIST")"
if [ "$(wc -l <<< "$MATCHES" | xargs)" -eq 1 ]; then
>&2 echo "Leaving $PWD"
cd "$WORKSPACE_ROOT/$MATCHES"
else
>&2 echo "Found $(wc -l <<< "$MATCHES" | xargs) matching workspaces:"
sed 's/^/ /' <<< "$MATCHES" | grep --color "$LABEL"
return 1
fi
fi
return $?
;;
esac
}