Skip to content

Commit

Permalink
Merge pull request #97 from felipealfonsog/development
Browse files Browse the repository at this point in the history
updates
  • Loading branch information
felipealfonsog authored Apr 25, 2024
2 parents 4fa6f26 + e4e0228 commit b0748e3
Show file tree
Hide file tree
Showing 2 changed files with 221 additions and 111 deletions.
206 changes: 95 additions & 111 deletions src/aur-dev/git_updater.py
Original file line number Diff line number Diff line change
@@ -1,126 +1,110 @@
import os
import subprocess

def welcome():
print("\033[1;32mWelcome to GitHub Repository Updater -GitSyncMaster-!\033[0m")
print("\033[1;32mThis software was developed by Computer Science Engineer Felipe Alfonso González - Github: github.com/felipealfonsog - Under the BSD 3-clause license.\033[0m")
print("\033[1;32mDeveloped from Chile with love.\033[0m")
print("\033[1;32m----------------------------------------------------\033[0m")
print("\033[1;32m\033[1mEffortlessly Automate Git Repository Updates, Including Committing and Pulling, Across Directory Structures.\033[0m")
if os.uname().sysname == "Darwin":
print("\033[1;32mWelcome to GitHub Repository Updater -GitSyncMaster-!\033[0m")
print("\033[1;32mThis software was developed by Computer Science Engineer Felipe Alfonso González - Github: github.com/felipealfonsog - Under the BSD 3-clause license.\033[0m")
print("\033[1;32mDeveloped from Chile with love.\033[0m")
print("\033[1;32m----------------------------------------------------\033[0m")
print("\033[1;32m\033[1mEffortlessly Automate Git Repository Updates, Including Committing and Pulling, Across Directory Structures.\033[0m")
else:
print("Welcome to GitHub Repository Updater -GitSyncMaster-!")
print("This software was developed by Computer Science Engineer Felipe Alfonso González - Github: github.com/felipealfonsog - Under the BSD 3-clause license.")
print("Developed from Chile with love.")
print("----------------------------------------------------")
print("Effortlessly Automate Git Repository Updates, Including Committing and Pulling, Across Directory Structures.")

def update_github_repositories(main_directory, include_aur):
print("\nUpdating GitHub repositories...\n")
found_repos = False
for root, dirs, files in os.walk(main_directory):
if '.git' in dirs:
found_repos = True
git_dir = os.path.join(root, '.git')
if os.path.isdir(git_dir):
if include_aur or not root.endswith("-aur"):
os.chdir(root)
changes = os.popen('git status --porcelain').read().strip()
if changes:
print(f"\033[1;31mRepository in {root} requires a commit before updating.\033[0m")
try:
result = os.system('git pull')
if result == 0:
print("Repository updated successfully.")
else:
print("Error updating repository.")
except Exception as e:
print(f"Error updating repository: {e}")
else:
print(f"Updating repository in {root}")
try:
result = os.system('git pull')
if result == 0:
print("Repository updated successfully.")
else:
print("Error updating repository.")
except Exception as e:
print(f"Error updating repository: {e}")
os.chdir(main_directory)
if not found_repos:
print("No GitHub repositories found in the current directory or its subdirectories. Exiting.")
exit()
def perform_git_add():
subprocess.run(["git", "add", "."])

def check_repos(main_directory):
print("\nChecking for repositories requiring actions...\n")
repos_needing_action = []
for root, dirs, _ in os.walk(main_directory):
for dir in dirs:
repo_path = os.path.join(root, dir)
git_dir = os.path.join(repo_path, '.git')
if os.path.isdir(git_dir):
os.chdir(repo_path)
changes = os.popen('git status --porcelain').read().strip()
if changes:
repos_needing_action.append(repo_path)
os.chdir(main_directory)
def perform_git_commit():
commit_message = input("Enter commit message: ")
subprocess.run(["git", "commit", "-m", commit_message])

if repos_needing_action:
print("The following repositories require actions:")
for repo in repos_needing_action:
print(repo)
return repos_needing_action
def update_repos_ssh():
ssh_agent_result = subprocess.run(["ssh-agent", "-s"], capture_output=True, text=True)
if ssh_agent_result.returncode == 0:
ssh_add_result = subprocess.run(["ssh-add", os.path.expanduser("~/.ssh/id_rsa")], capture_output=True)
if ssh_add_result.returncode == 0:
for repo in filter(lambda x: os.path.isdir(os.path.join(x, ".git")), os.listdir()):
repo_dir = os.path.join(os.getcwd(), repo)
print("\n--------------------------------")
print(f"Updating {os.path.basename(repo_dir)}...")
os.chdir(repo_dir)
git_fetch_result = subprocess.run(["git", "fetch", "origin", subprocess.run(["git", "symbolic-ref", "--short", "HEAD"], capture_output=True, text=True).stdout.strip()], capture_output=True, text=True)
if "Your branch is up to date" in git_fetch_result.stdout:
print(f"Repository {os.path.basename(repo_dir)} is already up-to-date.")
else:
subprocess.run(["git", "pull", "--quiet", "origin", subprocess.run(["git", "symbolic-ref", "--short", "HEAD"], capture_output=True, text=True).stdout.strip()])
print(f"Repository {os.path.basename(repo_dir)} has been updated.")
os.chdir("..")
print("\n--------------------------------")
print("All repositories have been checked and updated if necessary.")
else:
print("Failed to add SSH key to the agent.")
else:
print("No repositories require actions.")
return []
print("Failed to start SSH agent.")

def main():
welcome()
current_directory = os.getcwd()
if not any('.git' in root for root, _, _ in os.walk(current_directory)):
print("You need to be inside a directory with GitHub repositories to update them.")
exit()
def update_repos_https():
for repo in filter(lambda x: os.path.isdir(os.path.join(x, ".git")), os.listdir()):
repo_dir = os.path.join(os.getcwd(), repo)
print("\n--------------------------------")
print(f"Updating {os.path.basename(repo_dir)} over HTTPS...")
os.chdir(repo_dir)
subprocess.run(["git", "pull", "--quiet", "origin", subprocess.run(["git", "symbolic-ref", "--short", "HEAD"], capture_output=True, text=True).stdout.strip()])
print(f"Repository {os.path.basename(repo_dir)} has been updated.")
os.chdir("..")
print("\n--------------------------------")
print("All repositories have been checked and updated if necessary.")

choice = input("Choose an option:\n1. Check repositories requiring actions.\n2. Update repositories.\nEnter option number (default is 2): ").strip() or '2'
if choice == '1':
repos = check_repos(current_directory)
if repos:
proceed = input("Do you want to proceed with the action? (Y/n): ").lower()
if proceed not in ['', 'y']:
print("Action aborted.")
exit()

for repo_path in repos:
os.chdir(repo_path)
changes = os.popen('git status --porcelain').read().strip()
print(f"Repository: {repo_path}\nChanges:\n{changes}")
stage_choice = input("Do you want to stage these changes for commit? (Y/n): ").lower()
if stage_choice in ['', 'y']:
os.system('git add .')
commit_message = input("Enter commit message: ")
os.system(f'git commit -m "{commit_message}"')
push_choice = input("Do you want to push these changes? (Y/n): ").lower()
if push_choice in ['', 'y']:
os.system('git push')
def check_repos():
changed_dir = False
for dir in filter(os.path.isdir, os.listdir()):
if os.path.isdir(os.path.join(dir, ".git")):
os.chdir(dir)
if subprocess.run(["git", "status", "--porcelain"], capture_output=True, text=True).stdout.strip():
changed_dir = True
add_choice = input(f"Do you want to perform 'git add .' in '{dir}'? (Y/n): ").lower()
if add_choice in ["y", ""]:
perform_git_add()
elif add_choice == "n":
print(f"Skipping 'git add .' in '{dir}'.")
continue
else:
print("Invalid choice. Skipping 'git add .'.")
continue
if not subprocess.run(["git", "diff-index", "--quiet", "HEAD", "--"], capture_output=True, text=True).stdout.strip():
perform_git_commit()
subprocess.run(["git", "push"])
if subprocess.run(["git", "push"]).returncode == 0:
print(f"Changes in '{dir}' were successfully committed and pushed.")
else:
print("Push aborted.")
print(f"Failed to push changes in '{dir}'.")
else:
print("Staging aborted.")
os.chdir(current_directory)
else:
print("No repositories require actions.")
elif choice == '2':
abort_choice = input("Do you want to abort the process? (Press Enter for No, Y for Yes default is No): ").lower() or 'n'
if abort_choice == 'y':
print("Operation aborted.")
exit()
print(f"No changes to commit in '{dir}'.")
os.chdir("..")
if not changed_dir:
print("No directories require actions.")

main_directory = input("Do you want to update repositories here? (Press Enter for Yes, No for cancel, default is Yes): ")
if main_directory.lower() == '' or main_directory.lower() == 'y':
exclude_choice = input("Do you want to exclude directories with the '-aur' suffix? (Press Enter for Yes, N for No, default is Yes): ").lower() or 'y'
if exclude_choice == 'y':
include_aur = False
else:
include_aur = True
update_github_repositories(current_directory, include_aur)
else:
print("You need to be inside a directory with GitHub repositories to update them.")
exit()
else:
print("Invalid option. Exiting.")
def main_menu():
welcome()
print("1. Update all repositories over SSH")
print("2. Update all repositories over HTTPS (default)")
print("3. Check repositories for actions")
print("4. Quit")
choice = input("Enter your choice [2]: ") or "2"
if choice == "1":
update_repos_ssh()
elif choice == "2":
update_repos_https()
elif choice == "3":
check_repos()
elif choice == "4":
print("Exiting...")
exit()
else:
print("Invalid choice. Please enter a valid option.")

if __name__ == "__main__":
main()
main_menu()
126 changes: 126 additions & 0 deletions src/aur-dev/stable/v.0.0.21/git_updater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import os

def welcome():
print("\033[1;32mWelcome to GitHub Repository Updater -GitSyncMaster-!\033[0m")
print("\033[1;32mThis software was developed by Computer Science Engineer Felipe Alfonso González - Github: github.com/felipealfonsog - Under the BSD 3-clause license.\033[0m")
print("\033[1;32mDeveloped from Chile with love.\033[0m")
print("\033[1;32m----------------------------------------------------\033[0m")
print("\033[1;32m\033[1mEffortlessly Automate Git Repository Updates, Including Committing and Pulling, Across Directory Structures.\033[0m")

def update_github_repositories(main_directory, include_aur):
print("\nUpdating GitHub repositories...\n")
found_repos = False
for root, dirs, files in os.walk(main_directory):
if '.git' in dirs:
found_repos = True
git_dir = os.path.join(root, '.git')
if os.path.isdir(git_dir):
if include_aur or not root.endswith("-aur"):
os.chdir(root)
changes = os.popen('git status --porcelain').read().strip()
if changes:
print(f"\033[1;31mRepository in {root} requires a commit before updating.\033[0m")
try:
result = os.system('git pull')
if result == 0:
print("Repository updated successfully.")
else:
print("Error updating repository.")
except Exception as e:
print(f"Error updating repository: {e}")
else:
print(f"Updating repository in {root}")
try:
result = os.system('git pull')
if result == 0:
print("Repository updated successfully.")
else:
print("Error updating repository.")
except Exception as e:
print(f"Error updating repository: {e}")
os.chdir(main_directory)
if not found_repos:
print("No GitHub repositories found in the current directory or its subdirectories. Exiting.")
exit()

def check_repos(main_directory):
print("\nChecking for repositories requiring actions...\n")
repos_needing_action = []
for root, dirs, _ in os.walk(main_directory):
for dir in dirs:
repo_path = os.path.join(root, dir)
git_dir = os.path.join(repo_path, '.git')
if os.path.isdir(git_dir):
os.chdir(repo_path)
changes = os.popen('git status --porcelain').read().strip()
if changes:
repos_needing_action.append(repo_path)
os.chdir(main_directory)

if repos_needing_action:
print("The following repositories require actions:")
for repo in repos_needing_action:
print(repo)
return repos_needing_action
else:
print("No repositories require actions.")
return []

def main():
welcome()
current_directory = os.getcwd()
if not any('.git' in root for root, _, _ in os.walk(current_directory)):
print("You need to be inside a directory with GitHub repositories to update them.")
exit()

choice = input("Choose an option:\n1. Check repositories requiring actions.\n2. Update repositories.\nEnter option number (default is 2): ").strip() or '2'
if choice == '1':
repos = check_repos(current_directory)
if repos:
proceed = input("Do you want to proceed with the action? (Y/n): ").lower()
if proceed not in ['', 'y']:
print("Action aborted.")
exit()

for repo_path in repos:
os.chdir(repo_path)
changes = os.popen('git status --porcelain').read().strip()
print(f"Repository: {repo_path}\nChanges:\n{changes}")
stage_choice = input("Do you want to stage these changes for commit? (Y/n): ").lower()
if stage_choice in ['', 'y']:
os.system('git add .')
commit_message = input("Enter commit message: ")
os.system(f'git commit -m "{commit_message}"')
push_choice = input("Do you want to push these changes? (Y/n): ").lower()
if push_choice in ['', 'y']:
os.system('git push')
else:
print("Push aborted.")
else:
print("Staging aborted.")
os.chdir(current_directory)
else:
print("No repositories require actions.")
elif choice == '2':
abort_choice = input("Do you want to abort the process? (Press Enter for No, Y for Yes default is No): ").lower() or 'n'
if abort_choice == 'y':
print("Operation aborted.")
exit()

main_directory = input("Do you want to update repositories here? (Press Enter for Yes, No for cancel, default is Yes): ")
if main_directory.lower() == '' or main_directory.lower() == 'y':
exclude_choice = input("Do you want to exclude directories with the '-aur' suffix? (Press Enter for Yes, N for No, default is Yes): ").lower() or 'y'
if exclude_choice == 'y':
include_aur = False
else:
include_aur = True
update_github_repositories(current_directory, include_aur)
else:
print("You need to be inside a directory with GitHub repositories to update them.")
exit()
else:
print("Invalid option. Exiting.")
exit()

if __name__ == "__main__":
main()

0 comments on commit b0748e3

Please sign in to comment.