-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.functions
571 lines (492 loc) · 18 KB
/
.functions
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#!/usr/bin/env bash
# log_message - Logs a message to a specified log file with a timestamp.
# Parameters:
# $1 - The message to log (string)
# $2 - The log file where the message should be appended (string, path to the log file)
# Output:
# Logs the message to the specified log file in the format:
# "YYYY-MM-DD HH:MM:SS - <message>"
# Example:
# log_message "Operation successful" "/path/to/logfile.log"
# This will append a line like:
# "2024-10-11 14:00:00 - Operation successful" to /path/to/logfile.log
log_message() {
local MESSAGE="$1"
local LOG_FILE="$2"
printf "%s - %s\n" "$(date +"%Y-%m-%d %H:%M:%S")" "$MESSAGE" >> "$LOG_FILE"
}
file_exists() {
# Using argument expansion to capture all files provided as arguments.
for FILE in "${@}"
do
if [[ ! -f $FILE ]]
then
echo "The file ${FILE} does not exist!"
fi
done
}
list() {
echo "ls in color with -F designations"
ls -F
}
go_home() {
echo "Welcome ~ \$HOME"
cd ~ || exit
pwd
}
show_aliases() {
mapfile -t my_array < <( compgen -A alias );
printf "%s\n" "${my_array[@]}" | sort
}
show_functions() {
local all=false
local my_array=()
# Check if the user passed the '-all' flag
if [[ "$1" == "-all" ]]; then
all=true
fi
mapfile -t my_array < <(compgen -A function)
# Filter out functions starting with an underscore unless '-all' is passed
if [[ "$all" == false ]]; then
local temp_array
temp_array=$(printf "%s\n" "${my_array[@]}" | grep -v '^_')
mapfile -t my_array <<<"$temp_array"
fi
printf "%s\n" "${my_array[@]}" | grep --color=auto -v '^$' | sort
}
findAndReplaceBsd() {
echo "
OK ---> FIND '$1' and
REPLACE WITH '$2' (on a BSD system like macOS or FreeBSD)...";
foo="$1";
bar="$2";
echo "
--- AFTER CHANGES --- RIPGREP '$2' ---"
rg --files-with-matches "$foo" | xargs sed -i '' "s|$foo|$bar|g";
rg "$2";
echo "";
}
findAndReplaceBsdF() {
echo "
OK ---> FIND Fixed String '$1' and
REPLACE WITH '$2' (on a BSD system like macOS or FreeBSD)...";
foo="$1";
bar="$2";
echo "
--- AFTER CHANGES --- RIPGREP '$2' ---"
rg --files-with-matches -F "$foo" | xargs sed -i '' "s|$foo|$bar|g";
rg -F "$2";
echo "";
}
# sometimes used as prepush script in certain projects
# examine file for logic details
# requires local package.json leaves a local file named
# a_semantic_version.js with same version as the one in package.json
injectSemver(){
bun -b run ~/inject_semantic_version.mjs;
}
# Lists the semver prefixed with 'v' from the local package.json
# and copies it to the clipboard.
# Example output: v1.0.0
# Uses pbcopy on macOS and xclip on Linux.
version() {
version=$(jq -r ".version" package.json | awk '{print "v"$1}')
echo "$version" | tee >(
if [[ "$OSTYPE" == "darwin"* ]]; then
pbcopy
else
xclip -selection clipboard
fi
)
}
# assumes version alias and tries two ways to find local date in files
semver() {
echo "Checking package.json's version...";
jq -r .version package.json;
echo "Running ./a_semantic_version.js directly...";
bun -b run ./a_semantic_version.js;
version;
}
# initiates a FaceTime call to a phone number using the open command
# with the tel protocol.
#
# The open command opens a file or URL with the default
# application associated with it
# The -a option specifies the application to open the file or URL with.
# In this case, we're specifying FaceTime as the application to open.
# The tel protocol followed by the phone number is passed as the argument
# to the open command.
# When the call function is called with a phone number,
# it opens FaceTime and initiates a call to the phone number specified.
# calls with iphone if setup or to person if they are a messages user
call() {
open -a FaceTime "tel://$1"
}
crypto() {
echo "Checking my favorite crypto using api.coingecko.com..."
curl -s -H 'Accept: application/json' 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,cardano&vs_currencies=usd' | jq .
}
md() {
pandoc "$1" --highlight-style=tango -o "/tmp/${1%.md}.html"
xdg-open "/tmp/${1%.md}.html"
}
# increments or sets the prerelease version and copies it to the clipboard
# eg. v1.0.0-beta.0
# uses pbcopy on macOS and xclip on Linux
vp() {
# Check if preid is provided
if [ -n "$1" ]; then
preid="$1"
new_version=$(npm --no-git-tag-version version prerelease --preid="$preid" 2>/dev/null)
else
new_version=$(npm --no-git-tag-version version prerelease 2>/dev/null)
fi
# Prefix with 'v' and remove the 'v' added by npm
new_version="v${new_version#v}"
# Output the new version and copy it to the clipboard
echo "$new_version" | tee >(if [[ "$OSTYPE" == "darwin"* ]]; then pbcopy; else xclip -selection clipboard; fi)
}
# directly sets the version string (you must dictate a valid semver string)
# and copies it to the clipboard with a prefix v
v() {
if [ -z "$1" ]; then
echo "Usage: v <version>"
return 1
fi
# Set the version using npm
new_version=$(npm --no-git-tag-version version "$1" 2>/dev/null)
# Prefix with 'v' and remove the 'v' added by npm
new_version="v${new_version#v}"
# Output the new version and copy it to the clipboard
echo "$new_version" | tee >(if [[ "$OSTYPE" == "darwin"* ]]; then pbcopy; else xclip -selection clipboard; fi)
}
# Function: cfgstash
# Description:
# - Stashes current changes in the configured Git repository with a predefined message.
# - Creates a timestamped backup of the `.extra` file by copying it to `.extra.backup.YYYYMMDD_HHMMSS`.
# - Logs all operations, including successes and errors, to ~/cfgstash.log.
# - Provides feedback on the success or failure of each operation.
#
# Usage:
# Simply type `cfgstash` in the terminal to execute the stash and backup operations.
cfgstash() {
# ----------------------------
# Configuration Variables
# ----------------------------
# Stash Message
local STASH_MESSAGE="dot_wip"
# Paths for .extra and its backup
local EXTRA_FILE="$HOME/.extra"
# Timestamp format: YYYYMMDD_HHMMSS
local TIMESTAMP
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# Backup File with Timestamp
local BACKUP_FILE="$HOME/.extra.backup.$TIMESTAMP"
# Log File Path
local LOG_FILE="$HOME/cfgstash.log"
# ----------------------------
# Start of cfgstash Operations
# ----------------------------
# Log the start of the operation
log_message "Starting cfgstash operation." "$LOG_FILE"
# ----------------------------
# Stash Operations
# ----------------------------
# Attempt to stash changes with the specified message using the cfg alias
cfg stash push -m "$STASH_MESSAGE" 2>&1
local STASH_STATUS=$?
# Analyze stash outcome
if [ $STASH_STATUS -eq 0 ]; then
log_message "Git stash successful with message: \"$STASH_MESSAGE\"." "$LOG_FILE"
echo "Git stash successful."
elif [ $STASH_STATUS -eq 1 ]; then
# Exit status 1 typically means there were no changes to stash
log_message "Git stash: No local changes to save." "$LOG_FILE"
echo "No local changes to stash."
else
# Any other exit status indicates an error
log_message "Git stash failed with exit status $STASH_STATUS." "$LOG_FILE"
echo "Error: Git stash failed with exit status $STASH_STATUS."
fi
# ----------------------------
# Backup Operations
# ----------------------------
# Check if .extra exists before attempting to copy
if [ -f "$EXTRA_FILE" ]; then
# Attempt to copy .extra to the time stamped backup file
cp "$EXTRA_FILE" "$BACKUP_FILE" 2>&1
local COPY_STATUS=$?
if [ $COPY_STATUS -eq 0 ]; then
echo ".extra has been successfully backed up to $BACKUP_FILE."
log_message "Successfully backed up .extra to $BACKUP_FILE." "$LOG_FILE"
else
echo "Error: Failed to create backup of .extra. Please check file permissions and paths."
log_message "Error: Failed to create backup of .extra to $BACKUP_FILE." "$LOG_FILE"
fi
else
echo "Warning: .extra file does not exist. No backup created."
log_message "Warning: .extra file does not exist at $EXTRA_FILE. No backup created." "$LOG_FILE"
fi
# ----------------------------
# Final Logging and Feedback
# ----------------------------
if [ "$STASH_STATUS" -eq 0 ] && [ "$COPY_STATUS" -eq 0 ]; then
echo "cfgstash operation completed successfully."
log_message "cfgstash operation completed successfully." "$LOG_FILE"
elif [ "$STASH_STATUS" -eq 0 ] && [ "$COPY_STATUS" -ne 0 ]; then
echo "cfgstash operation completed with errors during backup."
log_message "cfgstash operation completed with errors during backup." "$LOG_FILE"
elif [ "$STASH_STATUS" -eq 1 ] && [ "$COPY_STATUS" -eq 0 ]; then
echo "cfgstash operation completed successfully (no changes to stash)."
log_message "cfgstash operation completed successfully (no changes to stash)." "$LOG_FILE"
elif [ "$STASH_STATUS" -eq 1 ] && [ "$COPY_STATUS" -ne 0 ]; then
echo "cfgstash operation had no changes to stash and encountered errors during backup."
log_message "cfgstash operation had no changes to stash and encountered errors during backup." "$LOG_FILE"
elif [ "$STASH_STATUS" -ne 0 ] && [ "$COPY_STATUS" -eq 0 ]; then
echo "cfgstash operation failed during stash but backup was successful."
log_message "cfgstash operation failed during stash but backup was successful." "$LOG_FILE"
else
echo "cfgstash operation failed during stash and backup."
log_message "cfgstash operation failed during stash and backup." "$LOG_FILE"
fi
}
# Print sorted environment variables
print_sorted_env() {
bun --print process.env | sort
}
# Assumes you have .cfg AND in configDotFiles locally
# Pulls and updates both configDotFiles and .cfg
# Call from anywhere is fine
update_dotfiles() {
printf "Pulling latest changes from remote for .cfg/ ...updating working directory HOME directory.\n"
# First, run cfg pull
cfg pull
cfgl -3
printf "Done.\nNow cd to ~/configDotFiles and pull latest changes\n"
cd "$HOME/configDotFiles" ||
{ echo "Failed to change directory to $HOME/configDotFiles"; return 1; }
# Pull the latest changes from the repository
git pull
# Run 'gl -3' after pulling (assuming 'gl' is a custom alias/function)
gl -3
}
# Outputs a sorted, combined list of functions and aliases
# Can be used to pipe to fzf to quickly find bash functions and aliases.
function fna() {
local show_all_entries=false
local alias_list=()
local function_list=()
# Check if the user passed the '-all' flag
if [[ "$1" == "-all" ]]; then
show_all_entries=true
fi
# Retrieve aliases
mapfile -t alias_list < <(show_aliases)
# Retrieve functions
if [[ "$show_all_entries" == true ]]; then
mapfile -t function_list < <(show_functions -all)
else
mapfile -t function_list < <(show_functions)
fi
# Print the combined list of aliases and functions
{
printf "%s\n" "${alias_list[@]}"
printf "%s\n" "${function_list[@]}"
} | grep --color=auto -v '^$' | sort | column
# Print the source information
echo -e "\nThese entries are based on the current shell environment."
}
# Ensure the SSH agent is running and add the SSH key (so users don't have to enter their password each time)
# works in conjunction with git settings set in .extra
prime_ssh() {
# Check if SSH_IDENTITY_FILE is set
if [ -z "$SSH_IDENTITY_FILE" ]; then
echo "Error: SSH_IDENTITY_FILE is not set."
echo "Please declare the SSH_IDENTITY_FILE in this computer's .extra file."
echo "This setting is not included in the configDotFiles repository."
echo "See the configDotFiles repository's README for instructions."
return 1
fi
# Check if the SSH agent is already running
if [ -z "$SSH_AUTH_SOCK" ]; then
echo "Starting SSH agent..."
eval "$(ssh-agent -s)"
else
echo "SSH agent is already running."
fi
# Detect OS and add SSH key accordingly
if [[ "$(uname)" == "Darwin" ]]; then
echo "Running on macOS, adding SSH key to macOS keychain..."
if ! ssh-add --apple-use-keychain "$SSH_IDENTITY_FILE"; then
echo "Error: Failed to add SSH key to macOS keychain."
fi
elif [[ -f /etc/os-release ]]; then
if ! source /etc/os-release 2>/dev/null; then
echo "Error: Failed to source /etc/os-release."
return 1
fi
case "$ID" in
"fedora-asahi-remix")
echo "Running on Fedora Asahi Remix, adding SSH key..."
if ! ssh-add "$SSH_IDENTITY_FILE"; then
echo "Error: Failed to add SSH key on Fedora."
fi
;;
"ubuntu"|"debian")
echo "Running on $ID, adding SSH key..."
if ! ssh-add "$SSH_IDENTITY_FILE"; then
echo "Error: Failed to add SSH key on $ID."
fi
;;
*)
echo "Unrecognized Linux distribution, manual SSH setup may be required."
;;
esac
else
echo "/etc/os-release not found. Unrecognized OS, manual SSH setup may be required."
fi
}
# Debug using bun using selected set of files (one or more)
# temp file is destroyed after bun completes
# during debut click on link to open browser in debug mode break at first line
debug() {
# Check if at least one file is provided
if [[ $# -eq 0 ]]; then
echo "Please provide one or more files to debug."
return 1
fi
# Define the path to a fixed temporary file
local temp_file="/tmp/combined_code_debug.js"
# Concatenate the provided files into the temporary file, overwriting if it exists
cat "$@" > "$temp_file"
# Run Bun with --inspect-brk on the temporary file
bun --inspect-brk "$temp_file"
}
# better than type function name do this to see syntax highlighted function
batfunc() {
# Check if a function name was provided
if [[ -z $1 ]]; then
echo "Usage: showfunc function_name"
return 1
fi
# Check if the function exists
if declare -F "$1" > /dev/null; then
# Output the function definition with syntax highlighting using bat
declare -f "$1" | bat -l bash
else
echo "Function '$1' not found."
return 1
fi
}
# Function to display alias with syntax highlighting
batalias ()
{
if [[ -z $1 ]]; then
echo "Usage: batalias alias_name";
return 1;
fi;
if alias "$1" &> /dev/null; then
alias "$1" | bat -l bash;
else
echo "Alias '$1' not found.";
return 1;
fi
}
# Function to display syntax-highlighted content of a shell script file
batshell ()
{
if [[ -z $1 ]]; then
echo "Usage: batshell file_path";
return 1;
fi;
if [[ -f $1 ]]; then
bat -l bash "$1";
else
echo "File '$1' not found.";
return 1;
fi
}
# Function to display syntax-highlighted content of a text file
# Usage: batl language file_path
batl ()
{
if [[ -z $1 || -z $2 ]]; then
echo "Usage: batl language file_path";
return 1;
fi;
if [[ -f $2 ]]; then
bat -l "$1" "$2";
else
echo "File '$2' not found.";
return 1;
fi
}
# Function to sync ~/.git-completion.bash with the one in the git-source directory
# Usage: sync_git_completion
# assumes you have clone git to ~/project/git
sync_git_completion() {
# Variables
local GIT_SOURCE_DIR=~/project/git
local TARGET_FILE=~/.git-completion
local CURRENT_GIT_VERSION
CURRENT_GIT_VERSION=$(git --version | awk '{print $3}')
# Pre-check
printf "Running precheck...\n"
# Check if the Git source directory exists
if [ ! -d "$GIT_SOURCE_DIR" ]; then
printf "⚠️ Missing Git source directory: %s\n" "$GIT_SOURCE_DIR"
return 1
fi
# Check if the destination file exists or its directory is valid
if [ ! -f "$TARGET_FILE" ]; then
if [ ! -d "$(dirname "$TARGET_FILE")" ]; then
printf "⚠️ Destination directory does not exist: %s\n" "$(dirname "$TARGET_FILE")"
return 1
fi
printf "⚠️ Target file does not exist: %s\n" "$TARGET_FILE"
else
printf "✅ Target file exists: %s\n" "$TARGET_FILE"
fi
# Report paths
printf "Confirmed paths:\n"
printf " Git Source Directory: %s\n" "$GIT_SOURCE_DIR"
printf " Destination File: %s\n" "$TARGET_FILE"
# Prompt user to continue
printf "Do you want to continue syncing git-completion for Git version %s? [y/N]: " "$CURRENT_GIT_VERSION"
read -r response
case "$response" in
[yY][eE][sS]|[yY]) ;;
*) printf "Sync aborted by user.\n"; return 0 ;;
esac
# Sync Process
printf "Starting sync...\n"
# Navigate to Git source directory and fetch updates
cd "$GIT_SOURCE_DIR" || {
printf "⚠️ Failed to navigate to Git source directory.\n"
return 1
}
git fetch --tags
if ! git checkout "v$CURRENT_GIT_VERSION"; then
printf "⚠️ Version v%s not found in %s\n" "$CURRENT_GIT_VERSION" "$GIT_SOURCE_DIR"
return 1
fi
# Copy the git-completion script to the target location
if cp contrib/completion/git-completion.bash "$TARGET_FILE"; then
printf "✅ git-completion.bash synced successfully to %s\n" "$TARGET_FILE"
else
printf "⚠️ Failed to copy git-completion.bash to %s\n" "$TARGET_FILE"
return 1
fi
# Switch back to the main branch to avoid detached HEAD
printf "Restoring branch to avoid detached HEAD on subequent pulls...\n"
if git rev-parse --verify main &>/dev/null; then
git switch main
elif git rev-parse --verify master &>/dev/null; then
git switch master
else
printf "⚠️ Unable to determine the main branch (main or master). Please manually resolve.\n"
return 1
fi
# Final message
printf "Sync complete for Git version %s.\n" "$CURRENT_GIT_VERSION"
}