~skiqqy/bin

bin/goto -rwxr-xr-x 1.1 KiB
c0954778Stephen Cochrane Prog on deploy 2 days ago
                                                                                
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
#!/usr/bin/env bash
# cd to git repos, and start a subshell in that directory.
# Written by skiqqy with love.
# Usage: goto -h

usage()
{
	cat << EOF
$(basename "$0") ~ Git Repository Finder.

Usage: goto [OPTIONS] PATTERN

OPTIONS
-h          Shows This Message.
-f          Always goto the first matched expr.
-s SHELL    Specify the shell to use (defaults to bash).
EOF
	exit "$1"
}

main()
{
	all=true
	shell=bash
	while getopts hfs: opt
	do
		case "$opt" in
			h)
				usage 0
				;;
			f)
				all=false
				;;
			s)
				shell="$OPTARG"
				! command -v "$shell" > /dev/null && exit 1
				;;
			*)
				usage 1
				;;
		esac
	done
	shift "$((OPTIND-1))" # Get rid of parsed options

	[ -z "$1" ] && usage 1

	dirs=( $(find . -regex ".*$1.*\.git" | sed -E 's|(.*)/\.git|\1|g') ) # I want splitting

	if "$all" && [ "${#dirs[@]}" -gt 1 ]
	then
		select dir in "${dirs[@]}"
		do
			[ -n "$dir" ] && break
		done

	elif [ "${#dirs[@]}" -ge 1 ]
	then
		dir="${dirs[0]}"
	else
		printf -- 'Pattern did not match a repo.\n'
		exit 1
	fi

	[ -d "$dir" ] && cd "$dir" || exit 1
	$shell # Start the subshell
}

main "$@"