-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrfsn
More file actions
executable file
·112 lines (90 loc) · 2.8 KB
/
rfsn
File metadata and controls
executable file
·112 lines (90 loc) · 2.8 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/bin/bash
set -euo pipefail
# `Right File System Naming` renames files and directories to have a
# standardised way `for me =)` to name stuff.
# Dependencies:
# mv
# NOTE: There is no correlation that DT made a video about this.
#
# NOTE: Was planning to call it `rn`, but the last thing that I want is to
# mistyped with `rm` :/.
# -------------------------------- Functions -------------------------------- #
Usage()
{
while read -r; do
printf '%s\n' "$REPLY"
done <<-EOF
Usage: rfsn [OPTS] FILES_OR_DIRS
-h, --help - Display this help information.
-f, --force - Force the file renaming (default). Overrides '-i'
-H, --force-hyphen - Replaces ' ' and '_' with '-'.
-i, --interactive - Prompts before any action.
-U, --force-underscore - Replaces ' ' and '-' with '_'.
The use of '--' to ignore proceeding options is supported.
EOF
}
Err()
{
printf "Err: %s\n" "$2" 1>&2
# shellcheck disable=2086
(($1 > 0)) && exit $1
}
# ----------------------------- Input Processing ----------------------------- #
(($# == 0)) && Err 1 "Arguments(s) required."
Sep="-"
ForceHyphen=false
ForceUnderscore=false
Interactive=false
Force=true
while [[ -n $1 ]]; do
case $1 in
--) break ;;
--help | -h)
Usage
exit 0
;;
--force | -f)
Force=true
;;
--force-hyphen | -H)
Sep="-"
ForceHyphen=true
;;
--interactive | -i)
Interactive=true
Force=false
;;
--force-underscore | -U)
Sep="_"
ForceUnderscore=true
;;
-*) Err 1 "Incorrect option(s) specified." ;;
*) break ;;
esac
shift
done
# ----------------------------------- Main ----------------------------------- #
# Based from get_valid_filename @ https://github.com/django/django/blob/main/django/utils/text.py
for Argument in "$@"; do
Source=$Argument
ArgumentDir=${Argument%/*}
BaseName=${Argument##*/}
BaseName=${BaseName,,}
BaseName=${BaseName/" "/$Sep}
BaseName=${BaseName/":"/$Sep}
if [[ $ForceHyphen == true ]]; then
BaseName=${BaseName/"-"/$Sep}
elif [[ $ForceUnderscore == true ]]; then
BaseName=${BaseName/"_"/$Sep}
fi
BaseName=${BaseName//[^a-z0-9._-]/}
Destination="$ArgumentDir/$BaseName"
[[ -z $BaseName ]] || [[ $BaseName == "." ]] || [[ $BaseName == ".." ]] \
&& Err 1 "Could not derive file name from '$BaseName'."
if [[ $Force == false ]] && [[ $Interactive == true ]]; then
read -rp "Are you sure that you want to rename $Source to $Destination? (y/N) "
[[ $REPLY =~ ^[Yy] ]] || return 0
fi
# Using `-i` just in case.
mv -i "$Source" "$Destination"
done