-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfunctions
More file actions
357 lines (296 loc) · 9.78 KB
/
functions
File metadata and controls
357 lines (296 loc) · 9.78 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/bin/bash -eu
# Create properties easily for PekWM.
propstring () {
echo -n 'Property '
xprop WM_CLASS | sed 's/.*"\(.*\)", "\(.*\)".*/= "\1,\2" {/g'
echo '}'
}
# Back up an entire domain very quickly.
quick-warc() {
if [ -f "$1".warc.gz ]; then
echo "$1.warc.gz already exists"
else
wget --warc-file="$1" --warc-cdx --mirror --page-requisites \
--no-check-certificate --restrict-file-names=windows \
-e robots=off --waitretry 5 --timeout 60 --tries 5 --wait 1 \
-U "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27" \
"http://$1/"
fi
}
# Backup one directory to another with rsync.
backup() {
if [ -z "$1" ] || [ -z "$2" ]; then
echo 'Usage: backup <src> <dest>' 1>&2
return 1
fi
if [ ! -d "$1" ]; then
echo "Not a source directory: $1" 1>&2
return 1
fi
if [ ! -d "$2" ]; then
echo "Not a destination directory: $2" 1>&2
return 1
fi
if [ -n "$3" ]; then
echo 'You supplied a third argument. Something is probably wrong.' 1>&2
return 1
fi
rsync -auv --delete "$1/" "$2"
}
validate_transcoding_filenames() {
if [ -z "$1" ]; then
echo "Not input filename was given!"
return 1
fi
if ! [ -f "$1" ]; then
echo "Input file does not exist: $1" 1>&2
return 1
fi
if [ -z "$2" ]; then
echo "Not output filename was given!"
return 1
fi
if [ -d "$2" ]; then
echo "The output filename is a directory: $2"
return 1
fi
}
# Download an MP3 from YouTube, or other sources.
download-mp3() {
local cookies_args=''
if [ -f ~/Downloads/youtube/cookies.txt ]; then
cookies_args='--cookies cookies.txt'
fi
# shellcheck disable=SC2086
yt-dlp --extract-audio --audio-format mp3 $cookies_args "$1"
}
# Download an AAC file from YouTube, or other sources.
download-aac() {
yt-dlp --extract-audio --audio-format aac "$1"
}
# Archive a YouTube video, preserving as much as possible.
archive-youtube() {
yt-dlp -f 'bestvideo[ext!=webm]+bestaudio[ext!=webm]/best[ext!=webm]' \
--write-info-json --write-thumbnail --add-metadata \
"$1" \
-o "./%(uploader)s/%(title)s {%(id)s}.%(ext)s"
}
to_x264_1080p_aac_192k() {
validate_transcoding_filenames "$1" "$2" && \
ffmpeg -i "$1" \
-vcodec libx264 -profile:v high -preset slow \
-b:v 2000k -maxrate 2000k -bufsize 4000k -vf \
scale=-1:1080 -threads 0 \
-acodec aac -b:a 192k -strict -2 \
"$2"
}
to_x264_720p_aac_128k() {
validate_transcoding_filenames "$1" "$2" && \
ffmpeg -i "$1" \
-codec:v libx264 -profile:v high -preset slow \
-b:v 1000k -maxrate 1000k -bufsize 2000k -vf \
scale=-1:720 -threads 0 \
-codec:a aac -b:a 128k -strict -2 \
"$2"
}
to_mp4() {
validate_transcoding_filenames "$1" "$2" && \
ffmpeg -hwaccel cuda -i "$1" -c:v h264_nvenc -preset p4 -c:a aac -b:a 192k "$2"
}
# A function for producing very small .mp4 files
smol_mp4() {
validate_transcoding_filenames "$1" "$2" && \
# Scale video resolution by 1/7
# Keep bitrate low
ffmpeg -hwaccel cuda -i "$1" -vf scale=iw/7:ih/7 \
-c:v h264_nvenc -preset p4 -b:v 250k -maxrate 250k -bufsize 500k \
-c:a aac -b:a 64k "$2"
}
to_wav() {
validate_transcoding_filenames "$1" "$2" && \
ffmpeg -i "$1" -acodec pcm_s16le -ar 44100 "$2"
}
to_mp3() {
validate_transcoding_filenames "$1" "$2" && \
ffmpeg -i "$1" -vn -acodec libmp3lame -ar 44100 -q:a 2 "$2"
}
adfs_xml_url() {
domain=$(echo "$1" | sed -e 's/^\([a-zA-Z0-9]\+:\/\/\|\)\([^\/]\+\).*/\2/')
echo "https://$domain/FederationMetadata/2007-06/FederationMetadata.xml"
}
download_adfs_xml() {
local domain
domain=$(echo "$1" | sed -e 's/^\([a-zA-Z0-9]\+:\/\/\|\)\([^\/]\+\).*/\2/')
local url="https://$domain/FederationMetadata/2007-06/FederationMetadata.xml"
wget --no-check-certificate "$url" -O "${domain}-metadata.xml" || rm -f "${domain}-metadata.xml"
}
# A function for conveniently adding remotes for GitHub forks.
add-github-remote() {
local new_remote="$1"
local remote
for remote in $(git remote -v | awk '{print $1;}'); do
if [ "$new_remote" == "$remote" ]; then
echo -n 'We already have: ' 1>&2
git remote get-url origin 1>&2
return 1
fi
done
local basename
basename="$(basename "$(git config --get remote.origin.url)")"
git remote add "$new_remote" "[email protected]:${new_remote}/${basename}"
}
# A function for killing processes with confirmation.
killit() {
if pgrep -af "$1"; then
echo
read -p 'Kill these processes? (y/N): ' -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
pkill -f "$1"
fi
else
echo 'No processes found.'
fi
}
generate-clickhouse-password() {
# Prints the password and the XML for ClickHouse configuration.
head -c 8 /dev/urandom \
| base64 \
| tee /dev/tty \
| tr -d '\n' \
| sha256sum \
| awk '{print "<password_sha256_hex>" $1 "</password_sha256_hex>"}'
}
wgo() {
local command="$1"
case $command in
list)
curl -s https://go.dev/dl/ | grep -Eo 'go[0-9]+\.[0-9]+\.[0-9]+' | sort -t "." -k1,1n -k2,2n -k3,3n -u
;;
install)
if [ $# -ne 2 ]; then
echo 'Usage: wgo install <version>' 1>&2
return 1
fi
local version="$2"
if ! [[ "$version" =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then
echo "Invalid version: $version" 1>&2
return 1
fi
go install "golang.org/dl/go$version@latest"
"go$version" download
;;
esac
}
# Completion for the wgo function.
_wgo() {
# shellcheck disable=SC2034
local cur prev words cword split
_init_completion -s || return
local commands
commands='list install'
if [[ $cword -eq 1 ]] ; then # if one argument given
# shellcheck disable=SC2207
COMPREPLY=( $( compgen -W "$commands" -- "$cur" ) )
fi
# shellcheck disable=SC2128
[[ $COMPREPLY == *= ]] && compopt -o nospace
return
}
complete -F _wgo wgo
# A wrapper for Python programs that automatically uses virtualenv.
wrap-python-executable() {
local basename="$1"
shift 1
local executable=''
local home_executable="$HOME/.local/bin/$basename"
# Search for possible venv locations.
for env_dir in .venv venv env ve; do
if [ -f "$env_dir/bin/$basename" ]; then
local executable="$env_dir/bin/$basename"
break
fi
done
# Fall back on home executable.
if [ -z "$executable" ] && [ -f "$home_executable" ]; then
local executable="$home_executable"
fi
# Do nothing if we cannot find it.
if [ -z "$executable" ]; then
echo "Cannot find $basename!" 1>&2
return 1
fi
"$executable" "$@"
}
# Specific wrappers.
# Using aliases makes them only available to interactive shells.
alias pytest='wrap-python-executable pytest'
alias flake8='wrap-python-executable flake8'
alias ruff='wrap-python-executable ruff'
alias isort='wrap-python-executable isort'
alias pre-commit='wrap-python-executable pre-commit'
alias mypy='wrap-python-executable mypy'
alias pyright='wrap-python-executable pyright'
# Django wrappers
alias runserver='wrap-python-executable python manage.py runserver'
alias shell='wrap-python-executable python manage.py shell_plus'
alias dbshell='wrap-python-executable python manage.py dbshell'
# A wrapper for JS programs that automatically use node_modules versions.
wrap-js-executable() {
local basename="$1"
shift 1
local executable=''
if [ -f "node_modules/.bin/$basename" ]; then
local executable="node_modules/.bin/$basename"
fi
# Do nothing if we cannot find it.
if [ -z "$executable" ]; then
echo "Cannot find $basename!" 1>&2
return 1
fi
"$executable" "$@"
}
alias biome='wrap-js-executable biome'
alias eslint='wrap-js-executable eslint'
alias tsc='wrap-js-executable tsc'
# A function to serve an HTML file to localhost via a relatively random port
# Written with ChatGPT vibe coding.
serve-html() {
local file="$1"
local port=54999
python3 -c "
import http.server, socketserver, sys, os, urllib, mimetypes
html_file = sys.argv[1]
html_name = os.path.basename(html_file)
resource_dir = os.path.splitext(html_name)[0] + '_files'
allowed_ext = {'.html', '.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.ico'}
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = urllib.parse.unquote(self.path)
if path in ['/', '/index.html']:
with open(html_file, 'rb') as f:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
elif path.startswith(f'/{resource_dir}/'):
rel = path.lstrip('/')
local_path = os.path.normpath(rel)
ext = os.path.splitext(local_path)[1].lower()
if ext in allowed_ext and os.path.isfile(local_path):
mime = mimetypes.guess_type(local_path)[0] or 'application/octet-stream'
self.send_response(200)
self.send_header('Content-type', mime)
self.end_headers()
with open(local_path, 'rb') as f:
self.wfile.write(f.read())
return
self.send_response(404)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
with socketserver.TCPServer(('localhost', $port), Handler) as httpd:
print('http://localhost:$port/')
httpd.serve_forever()
" "$file"
}