Last active
January 16, 2024 14:33
-
-
Save cGuille/b7e13c0c880758bc76e3a280beb8b592 to your computer and use it in GitHub Desktop.
A simple Bash script to automatically git fetch (with delay), to be called in combination with __git_ps1 for your prompt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -eu | |
MIN_INTERVAL="${AUTOGITFETCH_MIN_INTERVAL:-300}" # seconds | |
TIMESTAMP_STORE_ROOT="${HOME}/.cache/autogitfetch/" | |
RESET='\e[0m' | |
GREY='\e[0;90m' | |
OUTPUT_TEXT_COLOR="$GREY" | |
# Note: | |
# Display every cached "last fetched" timestamp with: | |
# for f in ~/.cache/autogitfetch/*; do echo "$(date -d @$(cat "$f")) ($(basename "$f" | cut --delimiter=- --fields=4- | basenc --base64url --decode))"; done | |
# Will fail and therefore stop the while script if not in a git repository: | |
worktrees="$(git worktree list --porcelain 2>/dev/null)" | |
main_repo_root="$(echo "$worktrees" | head -n1 | cut --delimiter=' ' --fields=2)" | |
mkdir -p "$TIMESTAMP_STORE_ROOT" | |
enc_repo_ref="$(echo "$main_repo_root" | basenc --base64url)" | |
timestamp_file="${TIMESTAMP_STORE_ROOT}/${enc_repo_ref}" | |
timestamp="$(date +%s)" | |
if ! last_timestamp="$(cat "$timestamp_file" 2>/dev/null)" | |
then | |
last_timestamp=0 | |
fi | |
if (( $timestamp - $last_timestamp < $MIN_INTERVAL )) | |
then | |
exit | |
fi | |
echo -n "$timestamp" > "$timestamp_file" | |
echo -en "${OUTPUT_TEXT_COLOR}Fetching git branches…${RESET}" | |
OUTPUT="$(git fetch --prune --progress 2>&1)" | |
if [[ $OUTPUT = '' ]] | |
then | |
echo -e "${OUTPUT_TEXT_COLOR} done.${RESET}" | |
else | |
echo -e "${OUTPUT_TEXT_COLOR} done:\n${OUTPUT}${RESET}" | |
fi | |
find "$TIMESTAMP_STORE_ROOT" -type f -name 'git-last-fetch-*' -mtime +30 -delete # clean old cache entries |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment