aboutsummaryrefslogtreecommitdiff
path: root/bin/vis
blob: 01ff31cf7cce343fdf9fd2be6a908a684e65a172 (plain) (blame)
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
#!/usr/bin/env bash

#
# vis(1) -- Create and edit executable scripts in a directory VISPATH (defaults
# to ~/.local/bin).
#
# Author: Tom Ryder
# Copyright: 2015
# License: Public domain
#

# Name self
self=vis

# Define a function to show usage
usage() {
    printf 'USAGE: %s [EDITOR_OPTS] [--] FILE1 [FILE2...]\n' \
        "$self"
}

# Process options, including detecting requests for help
declare -a opts
for arg ; do
    case $arg in
        --help|-h|-\?)
            usage
            exit 0
            ;;
        --)
            shift
            break
            ;;
        -*)
            shift
            opts[${#opts[@]}]=$arg
            ;;
        *)
            break
            ;;
    esac
done

# If no arguments left, spit usage as an error and bail
if ! (($#)) ; then
    usage >&2
    exit 1
fi

# Create the script directory if it doesn't exist yet
vispath=${VISPATH:-$HOME/.local/bin}
if [[ ! -d $vispath ]] ; then
    mkdir -p -- "$vispath" || exit
fi

# Create a new array with the script directory prepended to the given names
declare -a files
files=("${@/#/$vispath/}")

# Collect the names of any scripts that don't exist yet so we can make them
# executable after we're done editing
declare -a creations
for file in "${files[@]}" ; do
    [[ -e $file ]] && continue
    creations[${#creations[@]}]=$file
done

# Run the editor; if EDITOR isn't set, use vi(1)
"${EDITOR:-vi}" "${opts[@]}" -- "${files[@]}"

# Make any created scripts executable if they now appear to be files
for creation in "${creations[@]}" ; do
    [[ -f $creation ]] || continue
    chmod +x -- "$creation"
done