/
gh-search
executable file
·86 lines (77 loc) · 1.79 KB
/
gh-search
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
#!/bin/sh
set -e
#
# gh-search: Search for filetypes on GitHub
#
usage='Usage: gh-search [-p] [-e extension] [-f filename] [-l language] [query]'
unset ext name lang print
die()(printf >&2 "%s: %s\n" "${0##*/}" "$@"; exit 1)
while [ -n "$1" ]; do case $1 in
-h|--help|-\?)
printf '%s\n' "$usage"
exit
;;
# Unbundle short options
-[p]?*)
tail="${1#??}"
head=${1%"$tail"}
shift
set -- "$head" "-$tail" "$@"
continue
;;
# Expand parametric values
-[efnl]?*|--[!=]*=*)
case $1 in
--*) tail=${1#*=}; head=${1%%=*} ;;
*) tail=${1#??}; head=${1%"$tail"} ;;
esac
shift
set -- "$head" "$tail" "$@"
continue
;;
-p|--print) print=1; ;;
-e|--extension) ext=$2; shift ;;
-f|--filename) name=$2; shift ;;
-n|--name) name=$2; shift ;;
-l|--language) lang=$2; shift ;;
--) shift; break ;;
-*) die "invalid option: '$1'" "$usage" ;;
*) break ;;
esac; shift
done
# Bail if there's nothing to search for
[ "$ext$name$lang$print$1" ] || die 'no search query specified'
# Resolve conflicting option pairs
[ -z "$ext" ] || [ -z "$name" ] ||
die 'extension and filename queries are mutually exclusive'
# Resolve search qualifiers
unset query
[ -z "$ext" ] || query="path:**/?*.${ext#.}"
[ -z "$name" ] || query="path:**/$name"
[ -z "$lang" ] || query="$query language:\"$lang\""
# Append any additional query parameters
while [ $# -gt 0 ]; do
case $1 in
*\ *) query="$query \"$1\"" ;;
*?*) query="$query $1" ;;
esac
shift
done
set -- "https://github.com/search?q=`printf %s "${query# }" | sed '
s/%/%25/g
s/:/%3A/g
s,/,%2F,g
s/?/%3F/g
s/&/%26/g
s/+/%2B/g
s/[[:blank:]]\{1,\}/+/g
'`&type=code"
# Print search url if `--print` was passed
[ -z "$print" ] || {
printf '%s\n' "$1"
exit
}
case `uname -s` in
Darwin) open "$@" ;;
*) xdg-open "$@" ;;
esac