blob: 7c3705b7c88e7f416d68af35c370595f80b523f4 [file] [log] [blame] [edit]
#!/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 and Zircon sources matching the given pattern
## usage: fx grep [options] <pattern> [-- type_filter...]
##
## Convenience wrapper around 'jiri grep' to search the Fuchsia and Zircon
## 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
## dart: Dart source files
## fidl: FIDL source 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 $?
fx-config-read
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');;
'dart') SELECTED_FILE_TYPES+=('*.dart');;
'fidl') SELECTED_FILE_TYPES+=('*.fidl');;
'cm'|'manifest') SELECTED_FILE_TYPES+=('*.cmx' '*.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[@]}"