Skip to content

Instantly share code, notes, and snippets.

@buzztaiki
Last active February 20, 2025 12:22
Show Gist options
  • Save buzztaiki/f74468bcab38cb5b68c3398dc742c552 to your computer and use it in GitHub Desktop.
Save buzztaiki/f74468bcab38cb5b68c3398dc742c552 to your computer and use it in GitHub Desktop.
#!/bin/bash
usage_exit() {
die <<EOF
Usage: $0 <query>
Search text in source code from GitHub.
Options:
-h show this help
-f output format {yaml,json,line} (default: yaml)
Example:
% gh-code-search GitHub CLI org:cli | head -n 5
https://github.com/cli/gh-webhook/blob/b8fb5686ed688da846f68eb2cc96f517d451712f/go.mod
https://github.com/cli/cli/blob/88cc4d2531cc361225c77558ec85799ff4352c58/pkg/cmd/root/root.go
https://github.com/cli/cli/blob/3a228694396e52f99aceb3496da5b025bd1c067f/pkg/cmd/repo/repo.go
https://github.com/cli/cli/blob/c5ce6855a712afe378665785e2a40f5343001b23/pkg/cmd/pr/pr.go
https://github.com/cli/cli/blob/c5ce6855a712afe378665785e2a40f5343001b23/pkg/cmd/issue/issue.go
EOF
}
die() {
cat
exit 1
}
format=yaml
while getopts "hf:" opt; do
case $opt in
h)
usage_exit 0
;;
f)
format="$OPTARG"
;;
*)
usage_exit 1 1>&2
;;
esac
done
shift $((OPTIND-1))
[[ $# -gt 0 ]] || usage_exit 1 1>&2
format() {
case $format in
yaml) yq --input-format=json '.' ;;
json) jq '.' ;;
line) jq -r '.html_url' ;;
*) die <<<"Invalid format: $format" 1>&2
esac
}
# https://docs.github.com/en/rest/search/search
gh_args=(
-H "Accept: application/vnd.github.text-match+json"
--paginate
--jq '.items[]'
"/search/code?q=$(jq -Rr '@uri' <<<"$*")"
)
gh api "${gh_args[@]}" |
jq '.text_matches[] as $text_matches | {html_url, repository: .repository.full_name, path, fragment: $text_matches.fragment}' |
format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment