|
| 1 | +""" |
| 2 | +Owner: José Lorente López | joselorente1105@gmail.com | Linkedin: www.linkedin.com/in/josé-lorente-lópez-0121b7148 |
| 3 | +
|
| 4 | +Description: CLI capable of interacting with Git and Github from the terminal. |
| 5 | +
|
| 6 | +Coding: UTF-8 |
| 7 | +""" |
| 8 | + |
| 9 | +import os |
| 10 | +import subprocess |
| 11 | + |
| 12 | +class CLI(): |
| 13 | + def __init__(self) -> None: |
| 14 | + pass |
| 15 | + |
| 16 | +class Git_CLI(CLI): |
| 17 | + def __init__(self): |
| 18 | + super().__init__() |
| 19 | + |
| 20 | + @staticmethod |
| 21 | + def set_working_directory(): |
| 22 | + path_ = input("Enter the working directory: ").strip() |
| 23 | + try: |
| 24 | + os.chdir(path_) |
| 25 | + print(f"\nWorking directory changed to: {os.getcwd()}\n") |
| 26 | + except FileNotFoundError: |
| 27 | + print(f"\nError: The directory '{path_}' does not exist.\n") |
| 28 | + except Exception as e: |
| 29 | + print(f"\nError {e}: An unexpected error occurred while setting the working directory.\n") |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def create_new_repo(): |
| 33 | + try: |
| 34 | + subprocess.run(["git", "init"], check=True) |
| 35 | + print(f"\nNew repository generated in {os.getcwd()}\n") |
| 36 | + except subprocess.CalledProcessError as e: # CalledProcessError means that a subprocess started by Python exited with an error |
| 37 | + print(f"\nError {e}: Failed to create the new repository.\n") |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def create_new_branch(): |
| 41 | + branch_name = input("Enter the new branch name: ").strip() |
| 42 | + if not branch_name: |
| 43 | + print("Branch name cannot be empty.") |
| 44 | + return |
| 45 | + |
| 46 | + # Check if the repository has an initial branch |
| 47 | + result = subprocess.run(["git", "branch"], capture_output=True, text=True) |
| 48 | + branches = result.stdout.splitlines() |
| 49 | + |
| 50 | + if not branches: |
| 51 | + # If there are no branches, create 'main' as the initial branch |
| 52 | + try: |
| 53 | + subprocess.run(["git", "checkout", "-b", "main"], check=True) |
| 54 | + print("No initial branch found. 'main' created as the default branch.") |
| 55 | + |
| 56 | + # Make an initial commit to avoid further issues |
| 57 | + with open("README.md", "w") as f: |
| 58 | + f.write("# Initial Commit\n") |
| 59 | + |
| 60 | + subprocess.run(["git", "add", "README.md"], check=True) |
| 61 | + subprocess.run(["git", "commit", "-m", "Initial commit"], check=True) |
| 62 | + print("Initial commit created in 'main'.") |
| 63 | + except subprocess.CalledProcessError as e: |
| 64 | + print(f"\nError {e}: Failed to create the 'main' branch and initial commit.\n") |
| 65 | + return |
| 66 | + |
| 67 | + # Proceed with creating the new branch |
| 68 | + try: |
| 69 | + subprocess.run(["git", "checkout", "main"], check=True) |
| 70 | + subprocess.run(["git", "branch", branch_name], check=True) |
| 71 | + print(f"\nNew branch '{branch_name}' created.\n") |
| 72 | + except subprocess.CalledProcessError as e: |
| 73 | + print(f"\nError {e}: Failed to create the new branch '{branch_name}'.\n") |
| 74 | + |
| 75 | + @staticmethod |
| 76 | + def show_branch_list(): |
| 77 | + try: |
| 78 | + subprocess.run(["git", "branch", "-a"], check=True) |
| 79 | + print("\nList of available branches:") |
| 80 | + except subprocess.CalledProcessError as e: |
| 81 | + print(f"\nError {e}: Failed to display the branch list.\n") |
| 82 | + |
| 83 | + @staticmethod |
| 84 | + def change_branch(): |
| 85 | + branch_name = input("Enter the name of the branch you wish to move to: ").strip() |
| 86 | + if not branch_name: |
| 87 | + print("Branch name cannot be empty.") |
| 88 | + return |
| 89 | + |
| 90 | + # Comprobar si es una rama remota |
| 91 | + if branch_name.startswith("origin/"): |
| 92 | + local_branch_name = branch_name.split("/")[1] # Extraer el nombre de la rama local |
| 93 | + |
| 94 | + try: |
| 95 | + subprocess.run(["git", "checkout", "-b", local_branch_name, branch_name], check=True) |
| 96 | + print(f"\nCreated and switched to local branch '{local_branch_name}' from remote '{branch_name}'.\n") |
| 97 | + except subprocess.CalledProcessError as e: |
| 98 | + print(f"\nError {e}: Failed to create and switch to local branch '{local_branch_name}'.\n") |
| 99 | + return |
| 100 | + |
| 101 | + try: |
| 102 | + subprocess.run(["git", "checkout", branch_name], check=True) |
| 103 | + print(f"\nMoved to branch '{branch_name}'.\n") |
| 104 | + except subprocess.CalledProcessError as e: |
| 105 | + print(f"\nError {e}: Failed to move to branch '{branch_name}'.\n") |
| 106 | + |
| 107 | + |
| 108 | + @staticmethod |
| 109 | + def show_pending_files(): |
| 110 | + try: |
| 111 | + subprocess.run(["git", "status"], check=True) |
| 112 | + except subprocess.CalledProcessError as e: |
| 113 | + print(f"\nError {e}: Failed to show pending files.\n") |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def commit_changes(): |
| 117 | + commit_message = input("Enter the commit message: ").strip() |
| 118 | + if not commit_message: |
| 119 | + print("Commit message cannot be empty.") |
| 120 | + return |
| 121 | + try: |
| 122 | + subprocess.run(["git", "add", "."], check=True) |
| 123 | + subprocess.run(["git", "commit", "-m", commit_message], check=True) |
| 124 | + print(f"\nCommit made successfully.\n") |
| 125 | + except subprocess.CalledProcessError as e: |
| 126 | + print(f"\nError {e}: Failed to commit changes.\n") |
| 127 | + |
| 128 | + @staticmethod |
| 129 | + def show_commit_history(): |
| 130 | + try: |
| 131 | + subprocess.run(["git", "log", "--oneline"], check=True) |
| 132 | + except subprocess.CalledProcessError as e: |
| 133 | + print(f"\nError {e}: Failed to show commit history.\n") |
| 134 | + |
| 135 | + @staticmethod |
| 136 | + def delete_branch(): |
| 137 | + branch_name = input("Enter the name of the branch you wish to delete: ").strip() |
| 138 | + if not branch_name: |
| 139 | + print("Branch name cannot be empty.") |
| 140 | + return |
| 141 | + try: |
| 142 | + subprocess.run(["git", "branch", "-d", branch_name], check=True) |
| 143 | + print(f"\nBranch '{branch_name}' deleted.\n") |
| 144 | + except subprocess.CalledProcessError as e: |
| 145 | + print(f"\nError {e}: Failed to delete branch '{branch_name}'.\n") |
| 146 | + |
| 147 | + @staticmethod |
| 148 | + def set_remote_repository(): |
| 149 | + remote_url = input("Enter the remote repository URL: ").strip() |
| 150 | + if not remote_url: |
| 151 | + print("Remote repository URL cannot be empty.") |
| 152 | + return |
| 153 | + try: |
| 154 | + subprocess.run(["git", "remote", "add", "origin", remote_url], check=True) |
| 155 | + print(f"Remote repository '{remote_url}' set correctly.\n") |
| 156 | + except subprocess.CalledProcessError as e: |
| 157 | + print(f"\nError {e}: Failed to connect to remote repository '{remote_url}'.\n") |
| 158 | + |
| 159 | + @staticmethod |
| 160 | + def pull_changes(): # recommended pre push |
| 161 | + try: |
| 162 | + subprocess.run(["git", "pull"], check=True) # download and integrate changes from the server to your local repository |
| 163 | + print("Changes pulled successfully.\n") |
| 164 | + except subprocess.CalledProcessError as e: |
| 165 | + print(f"\nError {e}: Failed to pull changes.\n") |
| 166 | + |
| 167 | + @staticmethod |
| 168 | + def push_changes(): |
| 169 | + # Verificar si hay commits en el repositorio |
| 170 | + result = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True) |
| 171 | + |
| 172 | + if result.returncode != 0: |
| 173 | + print("Not a valid Git repository. Please ensure you are in a valid Git directory.") |
| 174 | + return |
| 175 | + |
| 176 | + # Obtener el nombre de la rama actual |
| 177 | + result = subprocess.run(["git", "branch", "--show-current"], capture_output=True, text=True) |
| 178 | + current_branch = result.stdout.strip() |
| 179 | + |
| 180 | + if not current_branch: |
| 181 | + print("No branch detected. Please ensure you have a branch checked out before pushing.") |
| 182 | + return |
| 183 | + |
| 184 | + # Asegurarse de que la rama actual tiene commits |
| 185 | + commit_result = subprocess.run(["git", "rev-parse", current_branch], capture_output=True, text=True) |
| 186 | + |
| 187 | + if commit_result.returncode != 0: |
| 188 | + print(f"The branch '{current_branch}' has no commits. Please make an initial commit before pushing.") |
| 189 | + return |
| 190 | + |
| 191 | + # Realizar el push de la rama actual |
| 192 | + try: |
| 193 | + subprocess.run(["git", "push", "-u", "origin", current_branch], check=True) |
| 194 | + print(f"Changes pushed successfully to branch '{current_branch}'.\n") |
| 195 | + except subprocess.CalledProcessError as e: |
| 196 | + print(f"Error {e}: Failed trying to push changes to branch '{current_branch}'.\n") |
| 197 | + |
| 198 | +def main(): |
| 199 | + """ |
| 200 | + Runs the main function of the project. |
| 201 | + """ |
| 202 | + |
| 203 | + git_cli = Git_CLI() |
| 204 | + |
| 205 | + while True: |
| 206 | + print("\nOptions:") |
| 207 | + print("1. Set the working directory") |
| 208 | + print("2. Create a new repository") |
| 209 | + print("3. Create a new branch") |
| 210 | + print("4. Switch branches") |
| 211 | + print("5. Show branch list") |
| 212 | + print("6. Show files pending commit") |
| 213 | + print("7. Commit (along with adding all files)") |
| 214 | + print("8. Show commit history") |
| 215 | + print("9. Delete branch") |
| 216 | + print("10. Set remote repository") |
| 217 | + print("11. Pull") |
| 218 | + print("12. Push") |
| 219 | + print("13. Exit") |
| 220 | + |
| 221 | + choice = input("Choose an option: ").strip() |
| 222 | + print(" ") |
| 223 | + |
| 224 | + if choice == '1': |
| 225 | + git_cli.set_working_directory() |
| 226 | + elif choice == '2': |
| 227 | + git_cli.create_new_repo() |
| 228 | + elif choice == '3': |
| 229 | + git_cli.create_new_branch() |
| 230 | + elif choice == '4': |
| 231 | + git_cli.change_branch() |
| 232 | + elif choice == '5': |
| 233 | + git_cli.show_branch_list() |
| 234 | + elif choice == '6': |
| 235 | + git_cli.show_pending_files() |
| 236 | + elif choice == '7': |
| 237 | + git_cli.commit_changes() |
| 238 | + elif choice == '8': |
| 239 | + git_cli.show_commit_history() |
| 240 | + elif choice == '9': |
| 241 | + git_cli.delete_branch() |
| 242 | + elif choice == '10': |
| 243 | + git_cli.set_remote_repository() |
| 244 | + elif choice == '11': |
| 245 | + git_cli.pull_changes() |
| 246 | + elif choice == '12': |
| 247 | + git_cli.push_changes() |
| 248 | + elif choice == '13': |
| 249 | + print("See you later!") |
| 250 | + break |
| 251 | + else: |
| 252 | + print("Invalid option. Please try again.") |
| 253 | + |
| 254 | +if __name__ == "__main__": |
| 255 | + main() |
0 commit comments