Skip to content

Instantly share code, notes, and snippets.

@undergroundwires
Last active May 20, 2024 07:34
Show Gist options
  • Save undergroundwires/5f5d4cdd8973a72f03c8588a2d033dbb to your computer and use it in GitHub Desktop.
Save undergroundwires/5f5d4cdd8973a72f03c8588a2d033dbb to your computer and use it in GitHub Desktop.
Helpful git aliases
#!/usr/bin/env bash
# bash: `bash ./alias.sh` (requires sudo in macOS)
# zsh: `zsh ./alias.sh`
main() {
local -ra aliases=(
# gitgo : Alias for git add, commit with amend, update commit date and force push
"alias gitgo='git add . && git commit --amend --no-edit --reset-author && git push -f'"
# gitc : Alias for counting total characters in last commi heading
"alias gitc='git log --pretty=format:%Creset%s --no-merges -1 | wc -c'"
# gita : Alias for amending to latest commit
"alias gita='git add . && git commit --amend --no-edit --allow-empty'"
)
while IFS= read -r file; do
for alias in "${aliases[@]}"; do
set_persistent_alias "$alias" "$file"
done
done < <(get_alias_files)
}
set_persistent_alias() {
local -r alias="$1"
local -r file="$2"
if ! create_file "$file"; then
log_error "Failed to create the file: $file."
return 1
fi
if grep -Fxq "$alias" "$file"; then
echo "[$file] Alias already exists: $alias"
else
command="echo \"$alias\" >> \"$file\""
if type "sudo" &> /dev/null; then # Git Bash on Windows does not have sudo
command="sudo $command"
fi
if eval "$command"; then
echo "[$file] Saved alias"
else
log_error "[$file] Failed to save alias"
fi
fi
# shellcheck disable=SC1090
source "$file"
}
get_alias_files() {
local -a files=()
if command_exists 'zsh'; then
files+=("$HOME/.zshrc")
fi
if command_exists 'bash'; then
if [ "$(uname -s)" == "Darwin" ]; then
files+=("$HOME/.bash_profile")
else # tested on Windows
files+=("$HOME/.bashrc")
fi
fi
if [ ${#files[@]} -eq 0 ]; then
log_error 'Unkown shell'
exit 1
fi
printf "%s\n" "${files[@]}"
}
create_file() {
local file_path="$1"
if [ -z "$file_path" ]; then
log_error 'Missing file path.'
return 1
fi
local parent_dir
if ! parent_dir=$(dirname "$file_path"); then
log_error "Could not determine the parent directory for the path: $file_path"
return 1
fi
if [ ! -d "$parent_dir" ]; then
echo "Creating directory: $parent_dir"
if ! mkdir -p "$parent_dir"; then
log_error "Failed to create the parent directory: $parent_dir"
return 1
fi
fi
if [ ! -f "$file_path" ]; then
echo "Creating file: $file_path"
if ! touch "$file_path"; then
log_error "Failed to create the file: $file_path"
return 1
fi
fi
}
command_exists() {
local -r command_name="$1"
command -v "$command_name" &> /dev/null
}
log_error() {
local -r message="$1"
>&2 echo "Error: $message"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment