116 lines
2.2 KiB
Bash
Executable File
116 lines
2.2 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
set -euo pipefail
|
|
|
|
|
|
GITIGNORE=".gitignore"
|
|
|
|
|
|
function print_help() {
|
|
cat <<EOF
|
|
Usage: $(basename "$0") <command> [pattern]
|
|
|
|
Commands:
|
|
add <pattern> Add a pattern to $GITIGNORE, if not present
|
|
remove <pattern> Remove a pattern from $GITIGNORE, if present
|
|
has <pattern> Check if a pattern is present in $GITIGNORE
|
|
show Print $GITIGNORE
|
|
list Print sorted $GITIGNORE, skipping blanks and comments
|
|
-h, --help Show this help message
|
|
EOF
|
|
}
|
|
|
|
|
|
function add_pattern() {
|
|
local pat="$1"
|
|
if pattern_exists "$pat"; then
|
|
echo "Already present: $pat"
|
|
return 1
|
|
fi
|
|
echo "$pat" >> "$GITIGNORE"
|
|
echo "Added: $pat"
|
|
}
|
|
|
|
function remove_pattern() {
|
|
local pat="$1"
|
|
if ! pattern_exists "$pat"; then
|
|
echo "Not present: $pat"
|
|
return 1
|
|
fi
|
|
grep -Fxv "$pat" "$GITIGNORE" > "$GITIGNORE.tmp"
|
|
mv "$GITIGNORE.tmp" "$GITIGNORE"
|
|
echo "Removed: $pat"
|
|
}
|
|
|
|
function has_pattern() {
|
|
local pat="$1"
|
|
if pattern_exists "$pat"; then
|
|
echo "yes"
|
|
return 0
|
|
else
|
|
echo "no"
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
function show_patterns() {
|
|
cat "$GITIGNORE"
|
|
}
|
|
|
|
function list_patterns() {
|
|
grep -v -e '^\s*#' -e '^\s*$' "$GITIGNORE" | sort -u
|
|
}
|
|
|
|
function pattern_exists() {
|
|
local pat="$1"
|
|
grep -Fxq "$pat" "$GITIGNORE"
|
|
}
|
|
|
|
|
|
# Check if -h or --help is anywhere in the arguments
|
|
if [[ " $* " == *" -h "* ]] || [[ " $* " == *" --help "* ]]; then
|
|
print_help
|
|
exit
|
|
fi
|
|
|
|
|
|
cmd="${1:-}"
|
|
pat="${2:-}"
|
|
|
|
|
|
# validate number of arguments
|
|
case "$cmd" in
|
|
add|remove|has)
|
|
if [[ $# -ne 2 ]]; then
|
|
echo "Usage: gitignore $cmd <pattern>"
|
|
exit 1
|
|
fi
|
|
;;
|
|
show|list)
|
|
if [[ $# -ne 1 ]]; then
|
|
echo "Usage: gitignore $cmd"
|
|
exit 1
|
|
fi
|
|
;;
|
|
*)
|
|
print_help
|
|
exit 1
|
|
;;
|
|
esac
|
|
|
|
|
|
# ensure .gitignore exists
|
|
touch "$GITIGNORE"
|
|
|
|
# dispatch command
|
|
case "$cmd" in
|
|
add) add_pattern "$pat" ;;
|
|
remove) remove_pattern "$pat" ;;
|
|
has) has_pattern "$pat" ;;
|
|
show) show_patterns ;;
|
|
list) list_patterns ;;
|
|
esac
|
|
|
|
|
|
|