blob: eca4de400964b9e485ecf00ad27bc1eb134b3b6c [file] [log] [blame]
#!/bin/bash
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#### CATEGORY=Source tree
### print lines in the Fuchsia sources matching the given pattern
## usage: fx grep [options] <pattern> [-- type_filter...]
##
## Convenience wrapper around 'jiri grep' to search the Fuchsia source tree and
## print lines matching the given pattern.
##
## Narrow your search to specific file types:
## c, cpp: C/C++ source and header files
## rs, rust: Rust source files
## py, python: Python source files
## go: Go source files
## dart: Dart source files
## fidl: FIDL source files
## service, config: Services configuration files
## cm, manifest: Component manifest files
## gn, build: GN build files
## md, doc: Documentation source files
##
## The following example searches both C++ and Python files for 'tcgetattr':
## fx grep tcgetattr -- cpp py
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/../lib/vars.sh || exit $?
set -e
# Map supported options to list of file types
SELECTED_FILE_TYPES=()
get_type_list() {
case $1 in
'c'|'cpp') SELECTED_FILE_TYPES+=('*.c' '*.cc' '*.cpp' '*.h' '*.hpp');;
'rs'|'rust') SELECTED_FILE_TYPES+=('*.rs');;
'py'|'python') SELECTED_FILE_TYPES+=('*.py');;
'go') SELECTED_FILE_TYPES+=('*.go');;
'dart') SELECTED_FILE_TYPES+=('*.dart');;
'fidl') SELECTED_FILE_TYPES+=('*.fidl');;
'service'|'config') SELECTED_FILE_TYPES+=('*.config');;
'cm'|'manifest') SELECTED_FILE_TYPES+=('*.cml');;
'gn'|'build') SELECTED_FILE_TYPES+=('*.gn' '*.gni');;
'md'|'doc') SELECTED_FILE_TYPES+=('*.md');;
*) fx-error "Unsupported file type: $1" && fx-command-help && exit 1;;
esac
}
# Separate grep arguments from file filters
COMMAND_OPTS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--help|-h)
fx-command-help
exit 0
;;
--)
shift
break
;;
-*)
COMMAND_OPTS+=( $1 )
shift
;;
*)
COMMAND_QUERY="$1"
shift
;;
esac
done
# Check arguments for a valid query pattern
if [[ -z "$COMMAND_QUERY" ]]; then
# No pattern argument available
fx-error "grep requires a query pattern"
fx-command-help
exit 1
fi
# Check filter arguments
for i in "$@"; do
get_type_list "$i"
done
# Build pathspec from chosen file types
FILTER_ARGS=()
if [[ ${#SELECTED_FILE_TYPES[@]} -ne 0 ]]; then
# Search selected file types
FILTER_ARGS+=(--)
for i in "${SELECTED_FILE_TYPES[@]}"; do
FILTER_ARGS+=( ":/**/${i}" )
done
fi
fx-command-run jiri grep "${COMMAND_OPTS[@]}" "${COMMAND_QUERY}" "${FILTER_ARGS[@]}"