Home > Back-end >  How to check if upstream's HEAD/latest commit is present in forked repo?
How to check if upstream's HEAD/latest commit is present in forked repo?

Time:01-25

My thought is that, in order to automatically fetch updates only if upstream has pushed some commits, I should check its hashes.

2 ways, I could do is that to check the logs or use rev-list something like below:

# this fetches top 30 commits from forked repo
git rev-list -n 30 main

# this also does the same but not limited to 30
git log --format='%H'

I'm finding it difficult to compare the hashes as I'm failing to fetch more than 1 commit from forked repo.

Explained my approach below:

git remote add upstream https://github.com/upstream/upstream.git
git fetch upstream --tags

upstream_commit="$(git rev-parse upstream/main)"
echo "Upstream commit: ${upstream_commit}"

# This should store 30 recent commit hashes as an array AFAIK
forked_commits=($(git rev-list -n 30 main))
# another I tried to put forloop is this:
# for forked_commit in "$forked_commits[@]"; do
for forked_commit in $(git log --format='%H'); do
  # but prints only the top most element and exits the loop
  echo "$forked_commit"
  if [ "$upstream_commit" == "$forked_commit" ]; then
    has_new_commits=false
  else
    # since I've added my commits on top, if condition fails and this always returns true
    has_new_commits=true
  fi
done
          
if [ "${has_new_commits}" ]; then
  git checkout main
  git rebase upstream/main
  git push -f origin main
  echo "Rebase successful!"
else
  echo "No commits to be synced!"
fi

CodePudding user response:

Ok, I did many mistake that were minor.

  • Array stuff didn't work. I was supposed to put them directly within the forloop.
  • Next mistake I never validated them properly. i.e., even if the hash was found, it never exited.
  • Using [ $has_new_commits ]; then is wrong. I should be using [ $has_new_commits == "true"]; then instead.

Corrected code:

git remote add upstream https://github.com/upstream_repo/upstream.git
git fetch upstream --tags

upstream_commit="$(git rev-parse upstream/main)"

for forked_commit in $(git rev-list -n 20 main); do
  if [ $upstream_commit != $forked_commit ]; then
    has_new_commits=true
    continue
  else
    has_new_commits=false
    break
  fi
done

if [ $has_new_commits == "true" ]; then
  echo "New commits found!"
else
  echo "No commits to be synced!"
fi
  • Related