#!/bin/bash # Define colors GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[0;33m' NC='\033[0m' # No Color # Define GitHub username github_username="mauvehed" # Define the directory path directory_path=~/gitwork/github/*/* # Check if the directory contains subdirectories check_directory_exists() { shopt -s nullglob local files=($directory_path) shopt -u nullglob if [[ ${#files[@]} -eq 0 ]]; then echo -e "${RED}No directories found in $directory_path.${NC}" exit 1 fi } # Verify if the repository is a fork and has upstream defined validate_repository() { if ! git remote -v | grep -q "origin.*fetch"; then echo -e "${YELLOW}This repository is not a fork. Skipping.${NC}" return 1 fi if ! git remote -v | grep -q "upstream"; then echo -e "${YELLOW}No upstream remote defined. Skipping.${NC}" return 1 fi # Check if origin repository belongs to the user local owner owner=$(git remote get-url origin | sed -E 's/.*[:/]([^/]+)\/[^/]+\.git/\1/') if [[ "$owner" != "$github_username" ]]; then echo -e "${YELLOW}Repository does not belong to $github_username. Skipping.${NC}" return 1 fi return 0 } # Switch to main or master branch switch_to_main_or_master() { local current_branch current_branch=$(git rev-parse --abbrev-ref HEAD) if [[ "$current_branch" != "main" && "$current_branch" != "master" ]]; then echo -e "${YELLOW}Switching to main branch...${NC}" git checkout main 2>/dev/null || { echo -e "${YELLOW}Main branch not found. Trying master...${NC}" git checkout master || { echo -e "${RED}Failed to switch to main or master branch.${NC}" return 1 } } fi return 0 } # Pull and reset branch with upstream sync_with_upstream() { local branch branch=$(git rev-parse --abbrev-ref HEAD) echo -e "${YELLOW}Pulling new commits from upstream/$branch...${NC}" git pull upstream "$branch" || { echo -e "${RED}Failed to pull upstream/$branch.${NC}" return 1 } echo -e "${YELLOW}Resetting local $branch branch to match upstream/$branch...${NC}" git reset --hard upstream/"$branch" || { echo -e "${RED}Failed to reset local $branch.${NC}" return 1 } echo -e "${YELLOW}Force pushing changes to origin $branch...${NC}" git push origin "$branch" --force || { echo -e "${RED}Failed to force push to origin $branch.${NC}" return 1 } return 0 } # Main script execution check_directory_exists for directory in $directory_path; do cd "$directory" || { echo -e "${RED}Failed to access directory: $directory.${NC}" continue } echo -e "${GREEN}Processing repository: $(pwd)${NC}" if validate_repository; then if switch_to_main_or_master; then sync_with_upstream fi fi echo -e "\n${YELLOW}--------------------------------------------------${NC}\n" done echo -e "${GREEN}Script executed successfully.${NC}"