gitpush-tool 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gitpush-tool
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A CLI tool to simplify Git push operations with intelligent defaults and options.
5
5
  Home-page: https://github.com/inevitablegs/gitpush
6
6
  Author: Ganesh Sonawane
@@ -0,0 +1 @@
1
+ __version__ = "0.2.1"
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import argparse
4
+ import sys
5
+ import subprocess
6
+ from datetime import datetime
7
+ import requests
8
+
9
+ def check_gh_installed():
10
+ """Check if GitHub CLI is installed"""
11
+ try:
12
+ subprocess.run(["gh", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
13
+ return True
14
+ except:
15
+ return False
16
+
17
+ def gh_authenticated():
18
+ """Check if user is authenticated with GitHub CLI"""
19
+ try:
20
+ result = subprocess.run(["gh", "auth", "status"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
21
+ return result.returncode == 0
22
+ except:
23
+ return False
24
+
25
+ def authenticate_with_gh():
26
+ """Authenticate user with GitHub CLI"""
27
+ print("\n🔑 GitHub authentication required")
28
+ print("We'll use the GitHub CLI (gh) for authentication")
29
+ print("This will open your browser for secure login")
30
+
31
+ try:
32
+ subprocess.run(["gh", "auth", "login", "--web", "-h", "github.com"], check=True)
33
+ return True
34
+ except subprocess.CalledProcessError:
35
+ print("❌ Authentication failed")
36
+ return False
37
+ except FileNotFoundError:
38
+ print("❌ GitHub CLI not found")
39
+ return False
40
+
41
+ def create_with_gh_cli(repo_name, private=False, description="", commit_message="Initial commit"):
42
+ """Create and push to new repository using GitHub CLI"""
43
+ try:
44
+ private_flag = "--private" if private else "--public"
45
+ cmd = [
46
+ "gh", "repo", "create", repo_name,
47
+ private_flag,
48
+ "--source=.",
49
+ "--remote=origin",
50
+ "--push"
51
+ ]
52
+
53
+ if description:
54
+ cmd.extend(["--description", description])
55
+
56
+ # Run the command
57
+ result = subprocess.run(cmd, check=True)
58
+
59
+ if result.returncode == 0:
60
+ # Get the repo URL
61
+ url_result = subprocess.run(
62
+ ["gh", "repo", "view", "--json", "url", "--jq", ".url"],
63
+ stdout=subprocess.PIPE,
64
+ text=True,
65
+ check=True
66
+ )
67
+ repo_url = url_result.stdout.strip()
68
+ print(f"✅ Successfully created repository: {repo_url}")
69
+ return True
70
+ return False
71
+ except subprocess.CalledProcessError as e:
72
+ print(f"❌ Failed to create repository: {e.stderr}")
73
+ return False
74
+
75
+ def initialize_repository(remote_url=None):
76
+ """Initialize git repository with sensible defaults"""
77
+ if not os.path.exists(".git"):
78
+ print("🛠 Initializing git repository")
79
+ subprocess.run(["git", "init"], check=True)
80
+ subprocess.run(["git", "branch", "-M", "main"], check=True)
81
+
82
+ if remote_url:
83
+ subprocess.run(["git", "remote", "add", "origin", remote_url], check=True)
84
+
85
+ # Create basic .gitignore if doesn't exist
86
+ if not os.path.exists(".gitignore"):
87
+ with open(".gitignore", "w") as f:
88
+ f.write("""# Python
89
+ __pycache__/
90
+ *.py[cod]
91
+ *.so
92
+ .Python
93
+ env/
94
+ venv/
95
+ .env
96
+
97
+ # IDE
98
+ .vscode/
99
+ .idea/
100
+ *.swp
101
+ *.swo
102
+
103
+ # System
104
+ .DS_Store
105
+ Thumbs.db
106
+
107
+ # Project specific
108
+ *.log
109
+ *.tmp
110
+ *.bak
111
+ """)
112
+ print("📁 Created .gitignore file")
113
+
114
+ def check_for_updates():
115
+ """Check for newer versions on PyPI"""
116
+ try:
117
+ current_version = "0.2.1" # Should match your setup.py
118
+ response = requests.get("https://pypi.org/pypi/gitpush-tool/json", timeout=2)
119
+ latest_version = response.json()["info"]["version"]
120
+ if latest_version != current_version:
121
+ print(f"ℹ️ New version available: {latest_version} (you have {current_version})")
122
+ print(" Run 'pip install --upgrade gitpush-tool' to update")
123
+ except:
124
+ pass
125
+
126
+ def run():
127
+ parser = argparse.ArgumentParser(
128
+ description="🚀 Supercharged Git push tool with GitHub repo creation",
129
+ formatter_class=argparse.RawDescriptionHelpFormatter,
130
+ epilog="""Examples:
131
+ Basic push: gitpush_tool "Commit message"
132
+ Create new repo: gitpush_tool "Initial commit" --new-repo project-name
133
+ Private repository: gitpush_tool --new-repo private-project --private
134
+ Force push: gitpush_tool "Fix critical bug" --force
135
+ Push specific branch: gitpush_tool "Update feature" feature-branch upstream
136
+ """
137
+ )
138
+ parser.add_argument("commit", nargs="?", help="Commit message")
139
+ parser.add_argument("branch", nargs="?", default="main", help="Branch name (default: main)")
140
+ parser.add_argument("remote", nargs="?", default="origin", help="Remote name (default: origin)")
141
+ parser.add_argument("--force", action="store_true", help="Force push with --force-with-lease")
142
+ parser.add_argument("--tags", action="store_true", help="Push tags")
143
+ parser.add_argument("--init", action="store_true", help="Initialize git repo")
144
+ parser.add_argument("--new-repo", metavar="NAME", help="Create new GitHub repository")
145
+ parser.add_argument("--private", action="store_true", help="Make repository private")
146
+ parser.add_argument("--description", help="Repository description")
147
+
148
+ args = parser.parse_args()
149
+
150
+ if args.new_repo:
151
+ print(f"🆕 Creating repository: {args.new_repo}")
152
+
153
+ # Check if GitHub CLI is installed
154
+ if not check_gh_installed():
155
+ print("❌ GitHub CLI (gh) is not installed")
156
+ print("Please install it first:")
157
+ print(" Mac (Homebrew): brew install gh")
158
+ print(" Windows (Winget): winget install --id GitHub.cli")
159
+ print(" Linux: See https://github.com/cli/cli#installation")
160
+ sys.exit(1)
161
+
162
+ # Check if authenticated
163
+ if not gh_authenticated():
164
+ if not authenticate_with_gh():
165
+ sys.exit(1)
166
+
167
+ # Create repository
168
+ if not create_with_gh_cli(
169
+ args.new_repo,
170
+ private=args.private,
171
+ description=args.description or "",
172
+ commit_message=args.commit or "Initial commit"
173
+ ):
174
+ sys.exit(1)
175
+
176
+ if args.init:
177
+ initialize_repository()
178
+
179
+ # Stage all changes
180
+ subprocess.run(["git", "add", "."], check=True)
181
+
182
+ if args.commit:
183
+ print(f"📦 Committing: '{args.commit}'")
184
+ try:
185
+ subprocess.run(['git', 'commit', '-m', args.commit], check=True)
186
+ except subprocess.CalledProcessError:
187
+ print("❌ Commit failed")
188
+ sys.exit(1)
189
+ else:
190
+ print("⚠️ Skipping commit (no message provided)")
191
+
192
+ # Build push command
193
+ push_cmd = ["git", "push"]
194
+ if args.force:
195
+ push_cmd.append("--force-with-lease")
196
+ if args.tags:
197
+ push_cmd.append("--tags")
198
+ if args.remote and args.branch:
199
+ push_cmd.extend([args.remote, args.branch])
200
+
201
+ print(f"🚀 Executing: {' '.join(push_cmd)}")
202
+ try:
203
+ subprocess.run(push_cmd, check=True)
204
+ print("✅ Successfully pushed changes")
205
+ except subprocess.CalledProcessError:
206
+ print("❌ Push failed")
207
+ sys.exit(1)
208
+
209
+ if __name__ == "__main__":
210
+ check_for_updates()
211
+ run()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gitpush-tool
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: A CLI tool to simplify Git push operations with intelligent defaults and options.
5
5
  Home-page: https://github.com/inevitablegs/gitpush
6
6
  Author: Ganesh Sonawane
@@ -3,7 +3,7 @@ from pathlib import Path
3
3
 
4
4
  setup(
5
5
  name="gitpush-tool",
6
- version="0.2.0",
6
+ version="0.2.1",
7
7
  packages=find_packages(),
8
8
  install_requires=[
9
9
  'requests>=2.25.0',
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"
@@ -1,285 +0,0 @@
1
- #!/usr/bin/env python3
2
- import os
3
- import argparse
4
- import sys
5
- import requests
6
- from getpass import getpass
7
- import json
8
- from datetime import datetime
9
-
10
- def get_github_token():
11
- """Get GitHub token from various sources with priority order"""
12
- # 1. Check environment variable
13
- token = os.getenv("GITHUB_TOKEN")
14
-
15
- # 2. Check token file
16
- if not token:
17
- token_path = os.path.join(os.path.dirname(__file__), '..', 'token')
18
- if os.path.exists(token_path):
19
- with open(token_path, 'r') as f:
20
- token = f.read().strip()
21
-
22
- # 3. Prompt user if still not found
23
- if not token:
24
- print("\n🔑 GitHub personal access token is required to create repositories.")
25
- print("Create one at: https://github.com/settings/tokens (with 'repo' scope)")
26
- token = getpass("Enter your GitHub token: ")
27
-
28
- return token
29
-
30
- def get_github_username():
31
- """Get GitHub username from config or API"""
32
- try:
33
- # Try git config first
34
- username = os.popen("git config github.user").read().strip()
35
- if username:
36
- return username
37
-
38
- # Fallback to API if token exists
39
- token = get_github_token()
40
- if token:
41
- headers = {
42
- "Authorization": f"token {token}",
43
- "Accept": "application/vnd.github+json"
44
- }
45
- response = requests.get("https://api.github.com/user", headers=headers)
46
- if response.status_code == 200:
47
- return response.json().get("login")
48
- except:
49
- pass
50
- return None
51
-
52
- def create_github_repo(repo_name, private=False, description=""):
53
- """Create a new GitHub repository using the GitHub API"""
54
- token = get_github_token()
55
-
56
- if not token:
57
- print("❌ GitHub token is required to create a repository")
58
- return None
59
-
60
- headers = {
61
- "Authorization": f"token {token}",
62
- "Accept": "application/vnd.github+json",
63
- "X-GitHub-Api-Version": "2022-11-28"
64
- }
65
-
66
- data = {
67
- "name": repo_name,
68
- "description": description,
69
- "private": private,
70
- "auto_init": False,
71
- "has_issues": True,
72
- "has_projects": False,
73
- "has_wiki": False
74
- }
75
-
76
- try:
77
- response = requests.post(
78
- "https://api.github.com/user/repos",
79
- headers=headers,
80
- json=data,
81
- timeout=10
82
- )
83
-
84
- # Detailed error handling
85
- if response.status_code == 401:
86
- print("❌ Authentication failed. Invalid or expired token.")
87
- print("Please create a new token with 'repo' scope at:")
88
- print("https://github.com/settings/tokens")
89
- return None
90
-
91
- elif response.status_code == 403:
92
- print("❌ Permission denied (403 Forbidden). Possible reasons:")
93
- print("- Token doesn't have 'repo' scope")
94
- print("- Token is restricted to specific repositories")
95
- print("- GitHub API rate limit exceeded")
96
-
97
- # Try to get rate limit info
98
- try:
99
- limits = requests.get(
100
- "https://api.github.com/rate_limit",
101
- headers=headers
102
- ).json()
103
- remaining = limits['resources']['core']['remaining']
104
- reset_time = datetime.fromtimestamp(limits['resources']['core']['reset']).strftime('%Y-%m-%d %H:%M:%S')
105
- print(f"⏳ API calls remaining: {remaining}")
106
- print(f"🔄 Rate limit resets at: {reset_time}")
107
- except:
108
- pass
109
-
110
- return None
111
-
112
- elif response.status_code == 422:
113
- error_data = response.json()
114
- if 'errors' in error_data:
115
- for error in error_data['errors']:
116
- if error.get('field') == 'name' and 'already exists' in error.get('message', ''):
117
- print(f"❌ Repository '{repo_name}' already exists")
118
- return None
119
- print(f"❌ Validation error: {error_data.get('message', 'Unknown error')}")
120
- return None
121
-
122
- elif response.status_code != 201:
123
- print(f"❌ Failed to create repository (HTTP {response.status_code}): {response.text}")
124
- return None
125
-
126
- repo_url = response.json()["html_url"]
127
- print(f"✅ Successfully created repository: {repo_url}")
128
- return repo_url
129
-
130
- except requests.exceptions.RequestException as e:
131
- print(f"❌ Failed to create repository: {str(e)}")
132
- if "Max retries exceeded" in str(e):
133
- print("⚠️ Network connection problem detected")
134
- return None
135
-
136
- def create_with_gh_cli(repo_name, private=False, description=""):
137
- """Alternative using GitHub CLI if installed"""
138
- try:
139
- private_flag = "--private" if private else "--public"
140
- cmd = f"gh repo create {repo_name} {private_flag} --source=. --remote=origin --push"
141
- if description:
142
- cmd += f" --description \"{description}\""
143
- return os.system(cmd) == 0
144
- except:
145
- return False
146
-
147
- def initialize_repository(remote_url=None):
148
- """Initialize git repository with sensible defaults"""
149
- if not os.path.exists(".git"):
150
- print("🛠 Initializing git repository")
151
- os.system("git init")
152
- os.system("git branch -M main")
153
-
154
- if remote_url:
155
- os.system(f"git remote add origin {remote_url}")
156
-
157
- # Create basic .gitignore if doesn't exist
158
- if not os.path.exists(".gitignore"):
159
- with open(".gitignore", "w") as f:
160
- f.write("""# Python
161
- __pycache__/
162
- *.py[cod]
163
- *.so
164
- .Python
165
- env/
166
- venv/
167
- .env
168
-
169
- # IDE
170
- .vscode/
171
- .idea/
172
- *.swp
173
- *.swo
174
-
175
- # System
176
- .DS_Store
177
- Thumbs.db
178
-
179
- # Project specific
180
- *.log
181
- *.tmp
182
- *.bak
183
- """)
184
- print("📁 Created .gitignore file")
185
-
186
- def check_for_updates():
187
- """Check for newer versions on PyPI"""
188
- try:
189
- current_version = "0.2.0" # Should match your setup.py
190
- response = requests.get("https://pypi.org/pypi/gitpush-tool/json", timeout=2)
191
- latest_version = response.json()["info"]["version"]
192
- if latest_version != current_version:
193
- print(f"ℹ️ New version available: {latest_version} (you have {current_version})")
194
- print(" Run 'pip install --upgrade gitpush-tool' to update")
195
- except:
196
- pass
197
-
198
- def run():
199
- parser = argparse.ArgumentParser(
200
- description="🚀 Supercharged Git push tool with GitHub repo creation",
201
- formatter_class=argparse.RawDescriptionHelpFormatter,
202
- epilog="""Examples:
203
- Basic push: gitpush_tool "Commit message"
204
- Create new repo: gitpush_tool "Initial commit" --new-repo project-name
205
- Private repository: gitpush_tool --new-repo private-project --private
206
- Force push: gitpush_tool "Fix critical bug" --force
207
- Push specific branch: gitpush_tool "Update feature" feature-branch upstream
208
- """
209
- )
210
- parser.add_argument("commit", nargs="?", help="Commit message")
211
- parser.add_argument("branch", nargs="?", default="main", help="Branch name (default: main)")
212
- parser.add_argument("remote", nargs="?", default="origin", help="Remote name (default: origin)")
213
- parser.add_argument("--force", action="store_true", help="Force push with --force-with-lease")
214
- parser.add_argument("--tags", action="store_true", help="Push tags")
215
- parser.add_argument("--init", action="store_true", help="Initialize git repo")
216
- parser.add_argument("--new-repo", metavar="NAME", help="Create new GitHub repository")
217
- parser.add_argument("--private", action="store_true", help="Make repository private")
218
- parser.add_argument("--description", help="Repository description")
219
-
220
- args = parser.parse_args()
221
-
222
- if args.new_repo:
223
- print(f"🆕 Creating repository: {args.new_repo}")
224
- repo_url = create_github_repo(
225
- args.new_repo,
226
- private=args.private,
227
- description=args.description or ""
228
- )
229
-
230
- # Fallback to GitHub CLI if API fails
231
- if not repo_url:
232
- print("⚠️ Falling back to GitHub CLI...")
233
- if create_with_gh_cli(args.new_repo, args.private, args.description):
234
- username = get_github_username()
235
- if username:
236
- repo_url = f"https://github.com/{username}/{args.new_repo}.git"
237
- else:
238
- repo_url = None
239
- else:
240
- print("❌ Could not create repository. Please check your credentials.")
241
- print("You can install GitHub CLI with: brew install gh (Mac) or winget install --id GitHub.cli (Windows)")
242
- sys.exit(1)
243
-
244
- if repo_url:
245
- initialize_repository(repo_url)
246
- args.init = False # Already initialized
247
- else:
248
- sys.exit(1)
249
-
250
- if args.init:
251
- initialize_repository()
252
-
253
- # Stage all changes
254
- os.system("git add .")
255
-
256
- if args.commit:
257
- print(f"📦 Committing: '{args.commit}'")
258
- commit_result = os.system(f'git commit -m "{args.commit}"')
259
- if commit_result != 0:
260
- print("❌ Commit failed")
261
- sys.exit(1)
262
- else:
263
- print("⚠️ Skipping commit (no message provided)")
264
-
265
- # Build push command
266
- push_cmd = "git push"
267
- if args.force:
268
- push_cmd += " --force-with-lease"
269
- if args.tags:
270
- push_cmd += " --tags"
271
- if args.remote and args.branch:
272
- push_cmd += f" {args.remote} {args.branch}"
273
-
274
- print(f"🚀 Executing: {push_cmd}")
275
- push_result = os.system(push_cmd)
276
-
277
- if push_result == 0:
278
- print("✅ Successfully pushed changes")
279
- else:
280
- print("❌ Push failed")
281
- sys.exit(1)
282
-
283
- if __name__ == "__main__":
284
- check_for_updates()
285
- run()
File without changes
File without changes
File without changes
File without changes