Last active
November 18, 2022 02:20
-
-
Save konsolebox/dfa3fd3d84552cf9deecfc23b20b7a83 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shopt -s extglob | |
function grep.fail { | |
printf '%s\n' "$1" >&2 | |
exit "${2-1}" | |
} | |
function grep.get_opt_and_optarg { | |
OPT=$1 OPTARG= OPTSHIFT=0 | |
if [[ $1 == -[!-]?* ]]; then | |
OPT=${1:0:2} OPTARG=${1:2} | |
elif [[ $1 == --*=* ]]; then | |
OPT=${1%%=*} OPTARG=${1#*=} | |
elif [[ ${2+.} ]]; then | |
OPTARG=$2 OPTSHIFT=1 | |
else | |
return 1 | |
fi | |
return 0 | |
} | |
function grep { | |
local opts=() args=() regex_specified=false i | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
-[EFGPiwxzsvVbnHhoqaIrRLlcTZU]|--@(extended-regexp|fixed-strings|basic-regexp|perl-regexp|ignore-case|no-ignore-case|word-regexp|line-regexp|null-data|no-messages|invert-match|version|help|byte-offset|line-number|line-buffered|with-filename|no-filename|only-matching|text|recursive|dereference-recursive|files-without-match|files-with-matches|count|initial-tab|null|no-group-separator|binary)|--@(color|colour)?(=*)) | |
opts+=("$1") | |
;; | |
-+([[:digit:]])|-[efmdDBAC]*|--@(regexp|file|max-count|label|binary-files|directories|devices|include|exclude|exclude-from|exclude-dir|before-context|after-context|context|group-separator)?(=*)) | |
grep.get_opt_and_optarg "${@:1:2}" | |
shift "${OPTSHIFT}" | |
[[ ${OPTARG} ]] || fail "Argument for '${OPT}' can't be empty." | |
[[ ${OPT} == @(-e|--regexp) ]] && regex_specified=true | |
opts+=("${OPT}" "${OPTARG}") | |
;; | |
--) | |
args+=("${@:2}") | |
break | |
;; | |
-[!-][!-]*) | |
set -- "${1:0:2}" "-${1:2}" "${@:2}" | |
continue | |
;; | |
-?*) | |
grep.fail "Unrecognized option: $1" | |
;; | |
*) | |
args+=("$1") | |
;; | |
esac | |
shift | |
done | |
if [[ ${regex_specified} == false && ${args+.} ]]; then | |
opts+=(-e "${args}") | |
unset 'args[0]' | |
fi | |
for i in "${!args[@]}"; do | |
if [[ ${args[i]%+(/)} == ?(*/)node_modules ]]; then | |
echo "Ignoring node_modules target: ${args[i]}" >&2 | |
unset 'args[i]' | |
if [[ ${#args[@]} -eq 0 ]]; then | |
grep.fail "No more targets left. Aborting." | |
fi | |
fi | |
done | |
command grep "${opts[@]}" -- "${args[@]}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment