Sobes.tech
Middle

What protective measures can be applied to branches to prevent incorrect pushes?

sobes.tech AI

Answer from AI

  • Access restriction by users/groups: Allow pushes only for specific users or groups.
  • Test passing requirement (CI): Set up a CI pipeline that runs tests on each push and blocks merging if tests fail.
  • Code Review: Require passing a code review before merging. A branch cannot be merged until approved by a specified number of other developers.
  • Branch naming rules: Establish rules for naming branches (e.g., feature/, bugfix/, release/).
  • Force push prohibition: Disable the use of git push --force to prevent overwriting branch history.
  • Main branch protection (main/master): Make the main branch (or branches) protected, allowing pushes only through pull requests/merge requests after all checks pass.
  • Use of hooks: Server-side or client-side Git hooks to check commits, commit messages, or perform other checks before pushing.
#!/bin/bash

# Example post-receive hook on the server blocking direct push to master

TARGET_BRANCH="refs/heads/master"

while read oldrev newrev refname
do
  if [ "$refname" == "$TARGET_BRANCH" ]; then
    # Check if the push is a merge commit or a direct commit
    # More reliable checks can use git rev-list to determine history
    MERGE_POINT=$(git merge-base $oldrev $newrev)
    if [ "$MERGE_POINT" == "$oldrev" ]; then
      # This is a non-merge push, block it
      echo "Error: Direct push to '$TARGET_BRANCH' is not allowed. Please use pull requests."
      exit 1
    fi
  fi
done

exit 0
  • Commit signatures (GPG): Require commits to be signed to verify authorship.
  • Static analyzers and linters checks: Automatic code checks for standards compliance and potential errors.
  • Push size limit: Set a maximum push size to prevent large files or binaries from being uploaded directly to the repository.
  • Branching strategy: Implement a clear branching strategy (e.g., Gitflow) to organize work and reduce errors.
Protection Measure Advantages Disadvantages
Access restriction Simple and basic protection Does not guarantee code quality
CI passing requirement Ensures code functionality Depends on test quality
Code Review Improves code quality, knowledge sharing Requires participant time
Main branch protection Control over critical branches Requires proper setup
Force push prohibition Maintains history integrity Can be inconvenient for error correction
Git hooks Flexibility, custom checks Requires scripting and maintenance