From 8d429259e3fb9c22bc3a3935bc3d41417dadedf5 Mon Sep 17 00:00:00 2001 From: Matt Hunter Date: Fri, 6 Mar 2026 15:08:05 -0500 Subject: Refactor autofetch logic Code for handling the auto background fetch is merged down to 1 function, and various changes are made to improve portability and POSIX compliance. The "lastupdatetime" file now stores the unix timestamp in its content, rather than the mtime timestamp. This will provide better platform cross-compatibility, and allows us to drop some code which trys to handle different styles of the stat command. Furthermore, the path to this file (or the .git directory) is no longer cached, since it only needs to be obtained by the script once in this spot. The `[ "$timestamp" -eq "$timestamp" ]` syntax is used to confirm that the content of the "lastupdatetime" file is an integer. This will fail on first encounter with a repository, or if migrating from the old timestamp-based format, or if the file was just mucked with, in which case $timestamp is forced to 0, and a fetch will very likely just occur on the spot. This will fixup the file by writing a new timestamp out to it. Signed-off-by: Matt Hunter --- git-sonar | 52 +++++++--------------------------------------------- 1 file changed, 7 insertions(+), 45 deletions(-) diff --git a/git-sonar b/git-sonar index 2ff238f..1f7b7e8 100755 --- a/git-sonar +++ b/git-sonar @@ -6,8 +6,6 @@ GIT_SONAR_VERSION="v0.8.1" -dot_git="" - prepare_colors() { PRINT_F_OPTION="" @@ -43,58 +41,22 @@ prepare_colors() { } -dot_git() { - if [ -n "$dot_git" ]; then - # cache dot_git to save calls to rev-parse - printf '%s' "$dot_git" - elif [ -d .git ]; then - dot_git=".git" - printf '%s' $dot_git - else - dot_git="$(git rev-parse --git-dir 2>/dev/null)" - printf '%s' "$dot_git" - fi -} - is_repo() { git-precheck --quiet [ $? -lt 4 ] } -record_timestamp() { - touch "$(dot_git)/lastupdatetime" -} - -timestamp() { - if [[ $OSTYPE == darwin* ]]; then - printf '%s' "$(stat -f%m "$(dot_git)/lastupdatetime" 2>/dev/null || printf '%s' "0")" - else - printf '%s' "$(stat -c %Y "$(dot_git)/lastupdatetime" 2>/dev/null || printf '%s' "0")" - fi -} - -time_now() { - printf '%s' "$(date +%s)" -} - -time_to_update() { - last_time_updated="${1:-$FETCH_TIME}" - local timesincelastupdate="$(($(time_now) - $(timestamp)))" - if (( $timesincelastupdate > $last_time_updated )); then - # time to update return 0 (which is true) - return 0 - else - # not time to update return 1 (which is false) - return 1 - fi -} - fetch() { FETCH_TIME="${GIT_RADAR_FETCH_TIME:-"$((5 * 60))"}" + TS_FILE="$(git rev-parse --git-path lastupdatetime 2>/dev/null)" + + now="$(date '+%s')" + timestamp="$(cat "$TS_FILE" 2>/dev/null)" + [ "$timestamp" -eq "$timestamp" ] >/dev/null 2>&1 || timestamp="0" - if time_to_update "$FETCH_TIME"; then - record_timestamp + if [ "$((now - timestamp))" -ge "$FETCH_TIME" ]; then nohup git fetch --quiet >/dev/null 2>&1 & + echo "$now" >"$TS_FILE" fi } -- cgit v1.2.3