Skip to content

Commit 529d259

Browse files
authored
Merge pull request mouredev#6733 from joselorentelopez/main
mouredev#43 - Python
2 parents 062a514 + 3920d4b commit 529d259

File tree

1 file changed

+252
-0
lines changed

1 file changed

+252
-0
lines changed
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
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+
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+
result = subprocess.run(["git", "branch", "--show-current"], capture_output=True, text=True)
177+
current_branch = result.stdout.strip()
178+
179+
if not current_branch:
180+
print("No branch detected. Please ensure you have a branch checked out before pushing.")
181+
return
182+
183+
commit_result = subprocess.run(["git", "rev-parse", current_branch], capture_output=True, text=True)
184+
185+
if commit_result.returncode != 0:
186+
print(f"The branch '{current_branch}' has no commits. Please make an initial commit before pushing.")
187+
return
188+
189+
try:
190+
subprocess.run(["git", "push", "-u", "origin", current_branch], check=True)
191+
print(f"Changes pushed successfully to branch '{current_branch}'.\n")
192+
except subprocess.CalledProcessError as e:
193+
print(f"Error {e}: Failed trying to push changes to branch '{current_branch}'.\n")
194+
195+
def main():
196+
"""
197+
Runs the main function of the project.
198+
"""
199+
200+
git_cli = Git_CLI()
201+
202+
while True:
203+
print("\nOptions:")
204+
print("1. Set the working directory")
205+
print("2. Create a new repository")
206+
print("3. Create a new branch")
207+
print("4. Switch branches")
208+
print("5. Show branch list")
209+
print("6. Show files pending commit")
210+
print("7. Commit (along with adding all files)")
211+
print("8. Show commit history")
212+
print("9. Delete branch")
213+
print("10. Set remote repository")
214+
print("11. Pull")
215+
print("12. Push")
216+
print("13. Exit")
217+
218+
choice = input("Choose an option: ").strip()
219+
print(" ")
220+
221+
if choice == '1':
222+
git_cli.set_working_directory()
223+
elif choice == '2':
224+
git_cli.create_new_repo()
225+
elif choice == '3':
226+
git_cli.create_new_branch()
227+
elif choice == '4':
228+
git_cli.change_branch()
229+
elif choice == '5':
230+
git_cli.show_branch_list()
231+
elif choice == '6':
232+
git_cli.show_pending_files()
233+
elif choice == '7':
234+
git_cli.commit_changes()
235+
elif choice == '8':
236+
git_cli.show_commit_history()
237+
elif choice == '9':
238+
git_cli.delete_branch()
239+
elif choice == '10':
240+
git_cli.set_remote_repository()
241+
elif choice == '11':
242+
git_cli.pull_changes()
243+
elif choice == '12':
244+
git_cli.push_changes()
245+
elif choice == '13':
246+
print("See you later!")
247+
break
248+
else:
249+
print("Invalid option. Please try again.")
250+
251+
if __name__ == "__main__":
252+
main()

0 commit comments

Comments
 (0)