wd.sh 12 KB
Newer Older
Markus Færevaag's avatar
Markus Færevaag committed
1
2
#!/bin/zsh

3
4
# WARP DIRECTORY
# ==============
Markus Færevaag's avatar
Markus Færevaag committed
5
6
7
8
9
# Jump to custom directories in terminal
# because `cd` takes too long...
#
# @github.com/mfaerevaag/wd

10
# version
11
readonly WD_VERSION=0.5.0
Markus Færevaag's avatar
Markus Færevaag committed
12

13
# colors
14
15
16
17
18
readonly WD_BLUE="\033[96m"
readonly WD_GREEN="\033[92m"
readonly WD_YELLOW="\033[93m"
readonly WD_RED="\033[91m"
readonly WD_NOC="\033[m"
Markus Færevaag's avatar
Markus Færevaag committed
19

20
## functions
Markus Færevaag's avatar
Markus Færevaag committed
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# helpers
wd_yesorno()
{
    # variables
    local question="${1}"
    local prompt="${question} "
    local yes_RETVAL="0"
    local no_RETVAL="3"
    local RETVAL=""
    local answer=""

    # read-eval loop
    while true ; do
        printf $prompt
        read -r answer

        case ${answer:=${default}} in
39
            "Y"|"y"|"YES"|"yes"|"Yes" )
40
41
42
                RETVAL=${yes_RETVAL} && \
                    break
                ;;
43
            "N"|"n"|"NO"|"no"|"No" )
44
45
46
47
48
49
50
51
                RETVAL=${no_RETVAL} && \
                    break
                ;;
            * )
                echo "Please provide a valid answer (y or n)"
                ;;
        esac
    done
52

53
54
    return ${RETVAL}
}
55

56
57
58
59
60
61
wd_print_msg()
{
    if [[ -z $wd_quiet_mode ]]
    then
        local color=$1
        local msg=$2
Markus Færevaag's avatar
Markus Færevaag committed
62

63
64
65
66
67
68
69
70
        if [[ $color == "" || $msg == "" ]]
        then
            print " ${WD_RED}*${WD_NOC} Could not print message. Sorry!"
        else
            print " ${color}*${WD_NOC} ${msg}"
        fi
    fi
}
Markus Færevaag's avatar
Markus Færevaag committed
71

72
73
wd_print_usage()
{
Atk's avatar
Atk committed
74
    command cat <<- EOF
75
Usage: wd [command] [point]
Markus Færevaag's avatar
Markus Færevaag committed
76

77
Commands:
78
79
    <point>         Warps to the directory specified by the warp point
    <point> <path>  Warps to the directory specified by the warp point with path appended
80
81
82
83
84
85
86
87
88
    add <point>     Adds the current working directory to your warp points
    add             Adds the current working directory to your warp points with current directory's name
    rm <point>      Removes the given warp point
    rm              Removes the given warp point with current directory's name
    show <point>    Print path to given warp point
    show            Print warp points to current directory
    list            Print all stored warp points
    ls  <point>     Show files from given warp point (ls)
    path <point>    Show the path to given warp point (pwd)
89
    clean           Remove points warping to nonexistent directories (will prompt unless --force is used)
90
91
92
93
94

    -v | --version  Print version
    -d | --debug    Exit after execution with exit codes (for testing)
    -c | --config   Specify config file (default ~/.warprc)
    -q | --quiet    Suppress all output
95
    -f | --force    Allows overwriting without warning (for add & clean)
96
97

    help            Show this extremely helpful text
98
99
100
101
102
103
104
EOF
}

wd_exit_fail()
{
    local msg=$1

105
    wd_print_msg "$WD_RED" "$msg"
106
107
108
109
110
111
112
    WD_EXIT_CODE=1
}

wd_exit_warn()
{
    local msg=$1

113
    wd_print_msg "$WD_YELLOW" "$msg"
114
115
116
    WD_EXIT_CODE=1
}

Markus Faerevaag's avatar
Markus Faerevaag committed
117
118
119
120
wd_getdir()
{
    local name_arg=$1

121
    point=$(wd_show "$name_arg")
Markus Faerevaag's avatar
Markus Faerevaag committed
122
123
124
125
126
127
128
129
130
131
132
    dir=${point:28+$#name_arg+7}

    if [[ -z $name_arg ]]; then
        wd_exit_fail "You must enter a warp point"
        break
    elif [[ -z $dir ]]; then
        wd_exit_fail "Unknown warp point '${name_arg}'"
        break
    fi
}

133
# core
Markus Færevaag's avatar
Markus Færevaag committed
134
135
136

wd_warp()
{
137
    local point=$1
138
    local sub=$2
139
140

    if [[ $point =~ "^\.+$" ]]
Markus Færevaag's avatar
Markus Færevaag committed
141
    then
142
        if [[ $#1 < 2 ]]
Markus Færevaag's avatar
Markus Færevaag committed
143
        then
144
            wd_exit_warn "Warping to current directory?"
Markus Færevaag's avatar
Markus Færevaag committed
145
146
147
148
        else
            (( n = $#1 - 1 ))
            cd -$n > /dev/null
        fi
149
    elif [[ ${points[$point]} != "" ]]
Markus Færevaag's avatar
Markus Færevaag committed
150
    then
151
152
153
154
155
156
        if [[ $sub != "" ]]
        then
            cd ${points[$point]/#\~/$HOME}/$sub
        else
            cd ${points[$point]/#\~/$HOME}
        fi
Markus Færevaag's avatar
Markus Færevaag committed
157
    else
158
        wd_exit_fail "Unknown warp point '${point}'"
Markus Færevaag's avatar
Markus Færevaag committed
159
160
161
162
163
    fi
}

wd_add()
{
164
165
    local point=$1
    local force=$2
166

167
168
    if [[ $point == "" ]]
    then
169
        point=$(basename "$PWD")
170
171
    fi

172
173
    if [[ $point =~ "^[\.]+$" ]]
    then
174
        wd_exit_fail "Warp point cannot be just dots"
Markus Faerevaag's avatar
Markus Faerevaag committed
175
    elif [[ $point =~ "[[:space:]]+" ]]
Markus Færevaag's avatar
Markus Færevaag committed
176
    then
177
        wd_exit_fail "Warp point should not contain whitespace"
Atk's avatar
Atk committed
178
    elif [[ $point =~ : ]] || [[ $point =~ / ]]
Markus Færevaag's avatar
Markus Færevaag committed
179
    then
Atk's avatar
Atk committed
180
        wd_exit_fail "Warp point contains illegal character (:/)"
181
    elif [[ ${points[$point]} == "" ]] || [ ! -z "$force" ]
182
    then
183
184
        wd_remove "$point" > /dev/null
        printf "%q:%s\n" "${point}" "${PWD/#$HOME/~}" >> "$WD_CONFIG"
Marc Cornellà's avatar
Marc Cornellà committed
185
186
187
        if (whence sort >/dev/null); then
            local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
            # use 'cat' below to ensure we respect $WD_CONFIG as a symlink
Atk's avatar
Atk committed
188
            command sort -o "${config_tmp}" "$WD_CONFIG" && command cat "${config_tmp}" > "$WD_CONFIG" && command rm "${config_tmp}"
Marc Cornellà's avatar
Marc Cornellà committed
189
        fi
190

191
192
        wd_export_static_named_directories

193
        wd_print_msg "$WD_GREEN" "Warp point added"
194

195
196
197
        # override exit code in case wd_remove did not remove any points
        # TODO: we should handle this kind of logic better
        WD_EXIT_CODE=0
Markus Færevaag's avatar
Markus Færevaag committed
198
    else
199
        wd_exit_warn "Warp point '${point}' already exists. Use 'add --force' to overwrite."
Markus Færevaag's avatar
Markus Færevaag committed
200
201
202
203
204
    fi
}

wd_remove()
{
205
    local point_list=$1
206

207
    if [[ "$point_list" == "" ]]
208
    then
209
        point_list=$(basename "$PWD")
210
211
    fi

212
213
    for point_name in $point_list ; do
        if [[ ${points[$point_name]} != "" ]]
Markus Færevaag's avatar
Markus Færevaag committed
214
        then
215
216
217
218
219
220
221
222
            local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
            # Copy and delete in two steps in order to preserve symlinks
            if sed -n "/^${point_name}:.*$/!p" "$WD_CONFIG" > "$config_tmp" && command cp "$config_tmp" "$WD_CONFIG" && command rm "$config_tmp"
            then
                wd_print_msg "$WD_GREEN" "Warp point removed"
            else
                wd_exit_fail "Something bad happened! Sorry."
            fi
Markus Færevaag's avatar
Markus Færevaag committed
223
        else
224
            wd_exit_fail "Warp point was not found"
Markus Færevaag's avatar
Markus Færevaag committed
225
        fi
226
    done
Markus Færevaag's avatar
Markus Færevaag committed
227
228
229
230
}

wd_list_all()
{
231
    wd_print_msg "$WD_BLUE" "All warp points:"
232

233
    entries=$(sed "s:${HOME}:~:g" "$WD_CONFIG")
234
235
236
237
238
239
240
241
242
243
244
245

    max_warp_point_length=0
    while IFS= read -r line
    do
        arr=(${(s,:,)line})
        key=${arr[1]}

        length=${#key}
        if [[ length -gt max_warp_point_length ]]
        then
            max_warp_point_length=$length
        fi
246
    done <<< "$entries"
247

248
    while IFS= read -r line
Markus Færevaag's avatar
Markus Færevaag committed
249
250
251
252
253
254
255
    do
        if [[ $line != "" ]]
        then
            arr=(${(s,:,)line})
            key=${arr[1]}
            val=${arr[2]}

256
257
            if [[ -z $wd_quiet_mode ]]
            then
258
                printf "%${max_warp_point_length}s  ->  %s\n" "$key" "$val"
259
            fi
Markus Færevaag's avatar
Markus Færevaag committed
260
        fi
261
    done <<< "$entries"
262
263
}

Markus Faerevaag's avatar
Markus Faerevaag committed
264
265
wd_ls()
{
266
267
    wd_getdir "$1"
    ls "${dir/#\~/$HOME}"
Markus Faerevaag's avatar
Markus Faerevaag committed
268
269
270
271
}

wd_path()
{
272
    wd_getdir "$1"
Atk's avatar
Atk committed
273
    echo "$(echo "$dir" | sed "s:~:${HOME}:g")"
Markus Faerevaag's avatar
Markus Faerevaag committed
274
275
}

276
277
wd_show()
{
278
279
    local name_arg=$1
    # if there's an argument we look up the value
280
    if [[ -n $name_arg ]]
281
282
283
    then
        if [[ -z $points[$name_arg] ]]
        then
284
            wd_print_msg "$WD_BLUE" "No warp point named $name_arg"
285
        else
286
            wd_print_msg "$WD_GREEN" "Warp point: ${WD_GREEN}$name_arg${WD_NOC} -> $points[$name_arg]"
287
288
289
290
291
292
        fi
    else
        # hax to create a local empty array
        local wd_matches
        wd_matches=()
        # do a reverse lookup to check whether PWD is in $points
293
        PWD="${PWD/$HOME/~}"
294
        if [[ ${points[(r)$PWD]} == "$PWD" ]]
295
296
297
        then
            for name in ${(k)points}
            do
298
                if [[ $points[$name] == "$PWD" ]]
299
300
301
302
303
                then
                    wd_matches[$(($#wd_matches+1))]=$name
                fi
            done

304
            wd_print_msg "$WD_BLUE" "$#wd_matches warp point(s) to current directory: ${WD_GREEN}$wd_matches${WD_NOC}"
305
        else
306
            wd_print_msg "$WD_YELLOW" "No warp point to $(echo "$PWD" | sed "s:$HOME:~:")"
307
308
        fi
    fi
Markus Færevaag's avatar
Markus Færevaag committed
309
310
}

311
312
313
314
315
wd_clean() {
    local force=$1
    local count=0
    local wd_tmp=""

316
    while read -r line
317
318
319
320
321
322
    do
        if [[ $line != "" ]]
        then
            arr=(${(s,:,)line})
            key=${arr[1]}
            val=${arr[2]}
323

324
            if [ -d "${val/#\~/$HOME}" ]
325
            then
326
                wd_tmp=$wd_tmp"\n"`echo "$line"`
327
            else
328
                wd_print_msg "$WD_YELLOW" "Nonexistent directory: ${key} -> ${val}"
329
330
331
                count=$((count+1))
            fi
        fi
332
    done < "$WD_CONFIG"
333
334

    if [[ $count -eq 0 ]]
Markus Færevaag's avatar
Markus Færevaag committed
335
    then
336
        wd_print_msg "$WD_BLUE" "No warp points to clean, carry on!"
Markus Færevaag's avatar
Markus Færevaag committed
337
    else
338
        if [ ! -z "$force" ] || wd_yesorno "Removing ${count} warp points. Continue? (y/n)"
339
        then
340
341
            echo "$wd_tmp" >! "$WD_CONFIG"
            wd_print_msg "$WD_GREEN" "Cleanup complete. ${count} warp point(s) removed"
342
        else
343
            wd_print_msg "$WD_BLUE" "Cleanup aborted"
344
        fi
Markus Færevaag's avatar
Markus Færevaag committed
345
346
347
    fi
}

348
wd_export_static_named_directories() {
349
  if [[ ! -z $WD_EXPORT ]]
350
  then
351
    command grep '^[0-9a-zA-Z_-]\+:' "$WD_CONFIG" | sed -e "s,~,$HOME," -e 's/:/=/' | while read -r warpdir ; do
Marc Cornellà's avatar
Marc Cornellà committed
352
        hash -d "$warpdir"
353
354
355
356
357
    done
  fi
}

local WD_CONFIG=${WD_CONFIG:-$HOME/.warprc}
358
359
360
local WD_QUIET=0
local WD_EXIT_CODE=0
local WD_DEBUG=0
361

362
363
364
# Parse 'meta' options first to avoid the need to have them before
# other commands. The `-D` flag consumes recognized options so that
# the actual command parsing won't be affected.
Markus Færevaag's avatar
Markus Færevaag committed
365

366
367
368
369
zparseopts -D -E \
    c:=wd_alt_config -config:=wd_alt_config \
    q=wd_quiet_mode -quiet=wd_quiet_mode \
    v=wd_print_version -version=wd_print_version \
370
371
    d=wd_debug_mode -debug=wd_debug_mode \
    f=wd_force_mode -force=wd_force_mode
Markus Færevaag's avatar
Markus Færevaag committed
372

373
374
375
376
377
378
379
380
381
382
383
if [[ ! -z $wd_print_version ]]
then
    echo "wd version $WD_VERSION"
fi

if [[ ! -z $wd_alt_config ]]
then
    WD_CONFIG=$wd_alt_config[2]
fi

# check if config file exists
384
if [ ! -e "$WD_CONFIG" ]
385
386
then
    # if not, create config file
387
    touch "$WD_CONFIG"
388
389
else
    wd_export_static_named_directories
390
391
392
393
394
395
396
397
fi

# load warp points
typeset -A points
while read -r line
do
    arr=(${(s,:,)line})
    key=${arr[1]}
398
399
    # join the rest, in case the path contains colons
    val=${(j,:,)arr[2,-1]}
400
401

    points[$key]=$val
402
done < "$WD_CONFIG"
Markus Færevaag's avatar
Markus Færevaag committed
403
404

# get opts
405
args=$(getopt -o a:r:c:lhs -l add:,rm:,clean,list,ls:,path:,help,show -- $*)
Markus Færevaag's avatar
Markus Færevaag committed
406

407
408
# check if no arguments were given, and that version is not set
if [[ ($? -ne 0 || $#* -eq 0) && -z $wd_print_version ]]
Markus Færevaag's avatar
Markus Færevaag committed
409
410
411
then
    wd_print_usage

412
413
# check if config file is writeable
elif [ ! -w "$WD_CONFIG" ]
414
then
415
    # do nothing
416
    # can't run `exit`, as this would exit the executing shell
417
    wd_exit_fail "\'$WD_CONFIG\' is not writeable."
418
419

else
420
    # parse rest of options
421
422
    local wd_o
    for wd_o
Markus Færevaag's avatar
Markus Færevaag committed
423
    do
424
        case "$wd_o"
Markus Faerevaag's avatar
Markus Faerevaag committed
425
            in
426
            "-a"|"--add"|"add")
427
                wd_add "$2" "$wd_force_mode"
Markus Færevaag's avatar
Markus Færevaag committed
428
429
                break
                ;;
430
431
432
433
434
            "-e"|"export")
                wd_export_static_named_directories
                break
                ;;
            "-r"|"--remove"|"rm")
435
436
                # Passes all the arguments as a single string separated by whitespace to wd_remove
                wd_remove "${@:2}"
Markus Færevaag's avatar
Markus Færevaag committed
437
438
                break
                ;;
439
            "-l"|"list")
Markus Faerevaag's avatar
Markus Faerevaag committed
440
                wd_list_all
Markus Færevaag's avatar
Markus Færevaag committed
441
442
                break
                ;;
443
            "-ls"|"ls")
444
                wd_ls "$2"
Markus Faerevaag's avatar
Markus Faerevaag committed
445
446
                break
                ;;
447
            "-p"|"--path"|"path")
448
                wd_path "$2"
Markus Faerevaag's avatar
Markus Faerevaag committed
449
450
                break
                ;;
451
            "-h"|"--help"|"help")
Markus Faerevaag's avatar
Markus Faerevaag committed
452
                wd_print_usage
Markus Færevaag's avatar
Markus Færevaag committed
453
454
                break
                ;;
455
            "-s"|"--show"|"show")
456
                wd_show "$2"
457
458
                break
                ;;
459
            "-c"|"--clean"|"clean")
460
                wd_clean "$wd_force_mode"
Markus Færevaag's avatar
Markus Færevaag committed
461
462
463
                break
                ;;
            *)
464
                wd_warp "$wd_o" "$2"
Markus Færevaag's avatar
Markus Færevaag committed
465
466
                break
                ;;
Markus Faerevaag's avatar
Markus Faerevaag committed
467
468
469
470
            --)
                break
                ;;
        esac
Markus Færevaag's avatar
Markus Færevaag committed
471
472
473
474
475
476
    done
fi

## garbage collection
# if not, next time warp will pick up variables from this run
# remember, there's no sub shell
477
478
479
480
481
482
483

unset wd_warp
unset wd_add
unset wd_remove
unset wd_show
unset wd_list_all
unset wd_print_msg
484
unset wd_yesorno
485
unset wd_print_usage
486
487
488
unset wd_alt_config
unset wd_quiet_mode
unset wd_print_version
489
490
unset wd_export_static_named_directories
unset wd_o
491

Markus Faerevaag's avatar
Markus Faerevaag committed
492
unset args
493
unset points
Markus Faerevaag's avatar
Markus Faerevaag committed
494
unset val &> /dev/null # fixes issue #1
495

496
if [[ -n $wd_debug_mode ]]
497
498
499
500
501
then
    exit $WD_EXIT_CODE
else
    unset wd_debug_mode
fi