refactor: improve bash code (#125)
* refactor: extract guard_path to utils/guard_path.sh * add utils/guard_operation.sh
This commit is contained in:
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Guard an operation with a confirmation prompt.
|
||||
|
||||
main() {
|
||||
if [ -t 1 ]; then
|
||||
confirmation_prompt="${1:-"Are you sure you want to continue?"}"
|
||||
read -r -p "$confirmation_prompt [Y/n] " ans
|
||||
if [[ "$ans" == "N" || "$ans" == "n" ]]; then
|
||||
echo "error: aborted!" 2>&1
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
main() {
|
||||
if [[ "$#" -ne 2 ]]; then
|
||||
echo "Usage: guard_path.sh <path> <confirmation_prompt>" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -t 1 ]; then
|
||||
path="$(_to_realpath "$1")"
|
||||
confirmation_prompt="$2"
|
||||
if [[ ! "$path" == "$(pwd)"* ]]; then
|
||||
read -r -p "$confirmation_prompt [Y/n] " ans
|
||||
if [[ "$ans" == "N" || "$ans" == "n" ]]; then
|
||||
echo "error: aborted!" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
_to_realpath() {
|
||||
path="$1"
|
||||
if [[ $OS == "Windows_NT" ]]; then
|
||||
path="$(cygpath -u "$path")"
|
||||
fi
|
||||
awk -v path="$path" -v pwd="$PWD" '
|
||||
BEGIN {
|
||||
if (path !~ /^\//) {
|
||||
path = pwd "/" path
|
||||
}
|
||||
if (path ~ /\/\.{1,2}?$/) {
|
||||
isDir = 1
|
||||
}
|
||||
split(path, parts, "/")
|
||||
newPartsLength = 0
|
||||
for (i = 1; i <= length(parts); i++) {
|
||||
part = parts[i]
|
||||
if (part == "..") {
|
||||
if (newPartsLength > 0) {
|
||||
delete newParts[newPartsLength--]
|
||||
}
|
||||
} else if (part != "." && part != "") {
|
||||
newParts[++newPartsLength] = part
|
||||
}
|
||||
}
|
||||
if (isDir == 1 || newPartsLength == 0) {
|
||||
newParts[++newPartsLength] = ""
|
||||
}
|
||||
printf "/"
|
||||
for (i = 1; i <= newPartsLength; i++) {
|
||||
newPart = newParts[i]
|
||||
printf newPart
|
||||
if (i < newPartsLength) {
|
||||
printf "/"
|
||||
}
|
||||
}
|
||||
}'
|
||||
}
|
||||
|
||||
main "$@"
|
||||
+2
-2
@@ -55,7 +55,7 @@ END {
|
||||
}
|
||||
|
||||
if (hunkIndex == 0) {
|
||||
print "No patch" > "/dev/stderr"
|
||||
print "error: no patch" > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ END {
|
||||
}
|
||||
|
||||
if (hunkIndex != totalHunks + 1) {
|
||||
print "Failed to patch the file" > "/dev/stderr"
|
||||
print "error: unable to apply patch" > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user