This commit is contained in:
2026-02-11 07:32:06 +02:00
parent 540b18e6e8
commit 49dd72c170
4 changed files with 83 additions and 31 deletions

View File

@@ -3,7 +3,7 @@
set -euo pipefail
usage() {
echo "Usage: $0 -c COMMENT_SYMBOL [-e EXCLUDE_PATTERN]... TARGET"
echo "Usage: $(basename "$0") -c COMMENT_SYMBOL [-e EXCLUDE_PATTERN]... TARGET"
echo " -c Comment symbol (e.g., '#' or '//')"
echo " -e Exclude pattern (can be specified multiple times)"
echo " TARGET File or directory to process"
@@ -29,21 +29,10 @@ shift $((OPTIND - 1))
target="$(realpath "$1")"
base_dir="$(pwd)"
should_exclude() {
local path="$1"
for pattern in "${excludes[@]}"; do
if [[ "$path" == *"$pattern"* ]]; then
return 0
fi
done
return 1
}
process_file() {
local file="$1"
local rel_path="${file#"$base_dir"/}"
should_exclude "$rel_path" && return
# shellcheck disable=SC2295
local rel_path="${file#$base_dir/}"
local path_comment="$comment_sym path: $rel_path"
@@ -52,22 +41,37 @@ process_file() {
IFS= read -r line1 <"$file" 2>/dev/null || line1=""
IFS= read -r line2 < <(tail -n +2 "$file") 2>/dev/null || line2=""
# Check if path comment exists in first or second line
[[ "$line1" == *"path: "* ]] && return
[[ "$line2" == *"path: "* ]] && return
# Insert after shebang if present, otherwise at top
# Handle shebang case
if [[ "$line1" =~ ^#! ]]; then
{
echo "$line1"
echo "$path_comment"
tail -n +2 "$file"
} >"$file.tmp"
if [[ "$line2" == *"path: "* ]]; then
# Replace existing path comment on line 2
{
echo "$line1"
echo "$path_comment"
tail -n +3 "$file"
} >"$file.tmp"
else
# Insert new path comment after shebang
{
echo "$line1"
echo "$path_comment"
tail -n +2 "$file"
} >"$file.tmp"
fi
else
{
echo "$path_comment"
cat "$file"
} >"$file.tmp"
if [[ "$line1" == *"path: "* ]]; then
# Replace existing path comment on line 1
{
echo "$path_comment"
tail -n +2 "$file"
} >"$file.tmp"
else
# Insert new path comment at top
{
echo "$path_comment"
cat "$file"
} >"$file.tmp"
fi
fi
mv "$file.tmp" "$file"
@@ -76,9 +80,26 @@ process_file() {
if [[ -f "$target" ]]; then
process_file "$target"
elif [[ -d "$target" ]]; then
find_cmd=(find "$target")
# Always exclude hidden files and directories
find_cmd+=(\( -name ".*" -prune \))
if [[ ${#excludes[@]} -gt 0 ]]; then
find_cmd+=(-o \()
for i in "${!excludes[@]}"; do
[[ $i -gt 0 ]] && find_cmd+=(-o)
find_cmd+=(-path "*/${excludes[$i]}" -prune)
find_cmd+=(-o -path "*/${excludes[$i]}/*" -prune)
done
find_cmd+=(\))
fi
find_cmd+=(-o -type f -print0)
while IFS= read -r -d '' file; do
process_file "$file"
done < <(find "$target" -type f -print0)
done < <("${find_cmd[@]}")
else
echo "Error: $target is not a file or directory" >&2
exit 1