Skip to content

Instantly share code, notes, and snippets.

@chrisranderson
Last active December 6, 2023 19:06
Show Gist options
  • Select an option

  • Save chrisranderson/5c48912aecb15c7f76a66b186cb0aad0 to your computer and use it in GitHub Desktop.

Select an option

Save chrisranderson/5c48912aecb15c7f76a66b186cb0aad0 to your computer and use it in GitHub Desktop.
Offboarding: find untracked/uncommitted changes recursively
#!/bin/zsh
# Constants
DEPTH=5 # Default depth
SEARCH_PATH="." # Default search path (current directory)
# Main function
main() {
find_git_repos_with_changes "${SEARCH_PATH}" "${DEPTH}"
}
# Function to check if a directory is a Git repository
is_git_repo() {
git -C "${1}" rev-parse --is-inside-work-tree 2> /dev/null
}
# Function to check for uncommitted or untracked changes
has_changes() {
if [[ -n $(git -C "${1}" status --porcelain) ]]; then
return 0
else
return 1
fi
}
# Function to list unpushed branches
list_unpushed_branches() {
local repo="${1}"
local branches=($(git -C "${repo}" branch --list | sed 's/^\*//;s/^[[:space:]]*//'))
for branch in $branches; do
local has_remote=$(git -C "${repo}" ls-remote --heads origin "${branch}" 2> /dev/null)
local has_unpushed_commits=$(git -C "${repo}" log origin/${branch}..${branch} --oneline 2> /dev/null)
if [[ -z $has_remote ]] || [[ -n $has_unpushed_commits ]]; then
echo -e "\t Unpushed branch: ${branch}"
fi
done
}
# Recursively search for Git repositories and check for changes
find_git_repos_with_changes() {
for dir in $(find "${1}" -maxdepth "${2}" -type d -name .git 2>/dev/null); do
repo=$(dirname "${dir}")
if is_git_repo "${repo}" &> /dev/null; then
local has_repo_changes=0
local output="\n===================================================\n\n"
# Check for uncommitted/untracked changes
if has_changes "${repo}"; then
output+="Repository with uncommitted/untracked changes: ${repo}\n"
has_repo_changes=1
fi
local unpushed_branches
unpushed_branches=$(list_unpushed_branches "${repo}")
if [[ -n $unpushed_branches ]]; then
[[ $has_repo_changes -eq 0 ]] && output+="Repository with unpushed branches: ${repo}\n"
output+="${unpushed_branches}"
has_repo_changes=1
fi
if [[ $has_repo_changes -eq 1 ]]; then
echo -e "${output}"
fi
fi
done
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment