-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathwg
executable file
·78 lines (69 loc) · 1.59 KB
/
wg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash
#
# Replace in files. Uses `ripgrep` to find files, so all `ripgrep` arguments work.
# > Note: Use `g` command for dry-run, and then replace it with `wg` command.
#
# - Replace a pattern in a file:
#
# `wg {{pattern}} {{filename}} --replace {{replacement}}`
#
# - Replace a pattern in all files:
#
# `wg {{pattern}} --replace {{replacement}}`
#
# ---
# Based on: https://github.com/sapegin/dotfiles/blob/master/bin/wg
#
# Author: Nick Plekhanov, https://nikkhan.com/
# License: MIT
# https://github.com/nicksp/dotfiles
RED="$(tput setaf 1)"
UNDERLINE="$(tput sgr 0 1)"
RESET="$(tput sgr0)"
error() {
echo -e "$UNDERLINE$RED$1$RESET\n"
}
command -v rg &> /dev/null || {
error "ripgrep is not installed: brew install ripgrep"
exit 1
}
seenReplace=''
for arg in "$@"; do
if test "$arg" == '--replace' -o "$arg" == '-r'; then
seenReplace='true'
break
fi
done
if test -z "$seenReplace"; then
error 'You should run wg with --replace or -r argument'
exit 1
fi
currentFile=''
didChange=''
(
rg \
--context 999999 \
--with-filename \
--heading \
--null \
--color never \
--no-line-number \
--max-columns 0 \
"$@"
echo -e '\n\0'
) \
| {
while IFS= read -r -d '' part; do
if test -n "$currentFile"; then
echo "$currentFile"
# Write file without last two lines
perl -ne 'push(@buf,$_);END{print @buf[0 ... $#buf-2]}' <<< "$part" > "$currentFile"
didChange='true'
fi
currentFile="$(tail -n 1 <<< "$part")"
done
if test -z "$didChange"; then
echo "No files were changed"
exit 1
fi
}