github-growth-plotter 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,2 @@
1
+ # GitHub Growth Plotter
2
+ __version__ = "0.1.0"
@@ -0,0 +1,189 @@
1
+ import argparse
2
+ import subprocess
3
+ import requests
4
+ import csv
5
+ import os
6
+ import sys
7
+ from datetime import datetime
8
+ import matplotlib.pyplot as plt
9
+ import matplotlib.dates as mdates
10
+
11
+ def get_github_token():
12
+ try:
13
+ result = subprocess.run(['gh', 'auth', 'token'], capture_output=True, text=True, check=True)
14
+ return result.stdout.strip()
15
+ except subprocess.CalledProcessError:
16
+ print("Error: Could not retrieve GitHub token. Ensure you are logged in using 'gh auth login'.")
17
+ sys.exit(1)
18
+ except FileNotFoundError:
19
+ # Fallback to env var if gh not found
20
+ token = os.environ.get("GITHUB_TOKEN")
21
+ if not token:
22
+ print("Error: 'gh' CLI not found and GITHUB_TOKEN environment variable not set.")
23
+ sys.exit(1)
24
+ return token
25
+
26
+ def get_current_repo():
27
+ try:
28
+ # First try using gh CLI
29
+ result = subprocess.run(['gh', 'repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], capture_output=True, text=True, check=True)
30
+ return result.stdout.strip()
31
+ except subprocess.CalledProcessError:
32
+ try:
33
+ # Fallback to git remote parsing
34
+ result = subprocess.run(['git', 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, check=True)
35
+ url = result.stdout.strip()
36
+ # Extract owner/repo from url
37
+ if url.startswith("git@github.com:"):
38
+ return url[15:].replace('.git', '')
39
+ elif url.startswith("https://github.com/"):
40
+ return url[19:].replace('.git', '')
41
+ else:
42
+ print("Error: Could not determine current repository from git remote.")
43
+ sys.exit(1)
44
+ except Exception as e:
45
+ print("Error: Could not determine current repository. Are you in a git repository?")
46
+ sys.exit(1)
47
+ except FileNotFoundError:
48
+ print("Error: Required command line tool 'gh' or 'git' not found.")
49
+ sys.exit(1)
50
+
51
+ def fetch_stargazers(repo, token):
52
+ url = f"https://api.github.com/repos/{repo}/stargazers"
53
+ headers = {
54
+ "Accept": "application/vnd.github.v3.star+json",
55
+ "Authorization": f"Bearer {token}",
56
+ "X-GitHub-Api-Version": "2022-11-28"
57
+ }
58
+
59
+ stargazers = []
60
+ page = 1
61
+ per_page = 100
62
+
63
+ print(f"Fetching stargazers for {repo}...")
64
+ while True:
65
+ params = {"page": page, "per_page": per_page}
66
+ response = requests.get(url, headers=headers, params=params)
67
+
68
+ if response.status_code != 200:
69
+ print(f"Error fetching stargazers: {response.status_code} {response.text}")
70
+ sys.exit(1)
71
+
72
+ data = response.json()
73
+ if not data:
74
+ break
75
+
76
+ for item in data:
77
+ stargazers.append({
78
+ "user": item["user"]["login"],
79
+ "starred_at": item["starred_at"]
80
+ })
81
+
82
+ if "next" not in response.links:
83
+ break
84
+ page += 1
85
+
86
+ return stargazers
87
+
88
+ def save_to_csv(stargazers, filename):
89
+ with open(filename, mode='w', newline='', encoding='utf-8') as file:
90
+ writer = csv.DictWriter(file, fieldnames=["user", "starred_at"])
91
+ writer.writeheader()
92
+ for stargazer in stargazers:
93
+ writer.writerow(stargazer)
94
+ print(f"Saved {len(stargazers)} stargazers to {filename}")
95
+
96
+ def plot_growth(stargazers, filename, repo):
97
+ dates = [datetime.strptime(s["starred_at"], "%Y-%m-%dT%H:%M:%SZ") for s in stargazers]
98
+ dates.sort()
99
+
100
+ counts = list(range(1, len(dates) + 1))
101
+
102
+ plt.figure(figsize=(10, 6))
103
+ plt.plot(dates, counts, marker='', linestyle='-', color='b')
104
+
105
+ plt.title(f"Stargazers Growth for {repo}")
106
+ plt.xlabel("Date")
107
+ plt.ylabel("Number of Stargazers")
108
+
109
+ # Format the x-axis to show dates nicely
110
+ plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
111
+ plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
112
+ plt.gcf().autofmt_xdate()
113
+
114
+ plt.grid(True)
115
+ plt.tight_layout()
116
+ plt.savefig(filename)
117
+ print(f"Saved growth plot to {filename}")
118
+
119
+ def update_gitignore(filename):
120
+ if os.path.exists('.gitignore'):
121
+ with open('.gitignore', 'r', encoding='utf-8') as f:
122
+ content = f.read()
123
+ if filename in content.splitlines():
124
+ return
125
+ with open('.gitignore', 'a', encoding='utf-8') as f:
126
+ if content and not content.endswith('\n'):
127
+ f.write('\n')
128
+ f.write(f"{filename}\n")
129
+ else:
130
+ with open('.gitignore', 'w', encoding='utf-8') as f:
131
+ f.write(f"{filename}\n")
132
+ print(f"Added {filename} to .gitignore")
133
+
134
+ def publish_to_readme(plot_filename, repo):
135
+ readme_path = "README.md"
136
+ basename = os.path.basename(plot_filename)
137
+ img_path = f"./assets/{basename}"
138
+
139
+ html_snippet = f'\n<p align="center">\n <img src="{img_path}" alt="{repo}" width="100%" />\n</p>\n'
140
+
141
+ if os.path.exists(readme_path):
142
+ with open(readme_path, 'r', encoding='utf-8') as f:
143
+ content = f.read()
144
+ if basename not in content:
145
+ with open(readme_path, 'a', encoding='utf-8') as f:
146
+ if content and not content.endswith('\n'):
147
+ f.write('\n')
148
+ f.write(html_snippet)
149
+ print(f"Published plot to {readme_path}")
150
+ else:
151
+ print(f"Plot already seems to be published in {readme_path}")
152
+ else:
153
+ with open(readme_path, 'w', encoding='utf-8') as f:
154
+ f.write(html_snippet.lstrip())
155
+ print(f"Created {readme_path} and published plot")
156
+
157
+ def main():
158
+ parser = argparse.ArgumentParser(description="Fetch stargazers and plot growth.")
159
+ parser.add_argument("repo", nargs="?", help="GitHub repository in owner/repo format. If not provided, uses the current repository.")
160
+ parser.add_argument("--publish", action="store_true", help="Auto publish the plot to the current README.md")
161
+ args = parser.parse_args()
162
+
163
+ repo = args.repo
164
+ if not repo:
165
+ repo = get_current_repo()
166
+
167
+ token = get_github_token()
168
+
169
+ stargazers = fetch_stargazers(repo, token)
170
+
171
+ if not stargazers:
172
+ print("No stargazers found or repository does not exist.")
173
+ sys.exit(0)
174
+
175
+ safe_repo_name = repo.replace('/', '_')
176
+ csv_filename = f"{safe_repo_name}_stargazers.csv"
177
+
178
+ os.makedirs("assets", exist_ok=True)
179
+ plot_filename = os.path.join("assets", f"{safe_repo_name}_growth.svg")
180
+
181
+ save_to_csv(stargazers, csv_filename)
182
+ update_gitignore(csv_filename)
183
+ plot_growth(stargazers, plot_filename, repo)
184
+
185
+ if args.publish:
186
+ publish_to_readme(plot_filename, repo)
187
+
188
+ if __name__ == "__main__":
189
+ main()
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: github-growth-plotter
3
+ Version: 0.1.0
4
+ Summary: A tool to fetch GitHub stargazers and plot growth over time.
5
+ Author: Open Source Maintainers
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.6
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: requests
13
+ Requires-Dist: matplotlib
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: license-file
19
+ Dynamic: requires-dist
20
+ Dynamic: requires-python
21
+ Dynamic: summary
22
+
23
+ <div align="center">
24
+ <img src="./assets/banner.svg" alt="GitHub Stargazers Growth Plotter Banner" width="100%">
25
+ </div>
26
+
27
+ # 📈 GitHub Stargazers Growth Plotter
28
+
29
+ <div align="center">
30
+
31
+ [![Python](https://img.shields.io/badge/Python-3.x-blue?style=for-the-badge&logo=python&logoColor=white)](https://python.org)
32
+ [![GitHub CLI](https://img.shields.io/badge/GitHub%20CLI-Required-black?style=for-the-badge&logo=github&logoColor=white)](https://cli.github.com/)
33
+ [![Matplotlib](https://img.shields.io/badge/Matplotlib-Supported-orange?style=for-the-badge)](https://matplotlib.org/)
34
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
35
+
36
+ </div>
37
+
38
+ > **Note:** As the stargazers API for 3rd party repos gets deprecated or restricted, repository owners can use this tool to easily fetch and publish their own repository's growth charts!
39
+
40
+ 🚀 **GitHub Stargazers Growth Plotter** is an automated tool that fetches the stargazers history of any GitHub repository, caches it locally, and generates a stunning SVG growth plot. Designed for repository owners, this script can auto-publish charts directly to your `README.md` for maximum visibility and better SEO indexing of project metrics.
41
+
42
+ ## ✨ Features
43
+
44
+ - 🔐 **Automated Authentication**: Seamlessly integrates with your active GitHub CLI (`gh`) token. Zero manual token configuration required!
45
+ - 🎯 **Zero-Config Context**: Automatically detects your current repository from your git config if run without arguments.
46
+ - 🗄️ **Local Caching**: Caches historical stargazer data in a CSV file and dynamically appends it to your `.gitignore` to prevent accidental commits.
47
+ - 📊 **High-Quality Plotting**: Renders beautiful, scalable vector `.svg` plots optimized for web display, saving them cleanly in an `assets/` directory.
48
+ - 📝 **Auto-Publishing**: With a simple flag, automatically inject your latest growth chart into your `README.md` within a perfectly centered HTML block.
49
+
50
+ ## 🛠️ Prerequisites
51
+
52
+ 1. **Python 3.x**: Ensure Python is installed on your system.
53
+ 2. **GitHub CLI (`gh`)**: You must have the GitHub CLI installed and authenticated.
54
+ ```bash
55
+ gh auth login
56
+ ```
57
+ 3. **Installation**:
58
+ Install the tool via PyPI:
59
+ ```bash
60
+ pip install github-growth-plotter
61
+ ```
62
+ *(To install from source locally, clone the repo and run `pip install .`)*
63
+
64
+ ## 🚀 Usage Guide
65
+
66
+ ### 1️⃣ Run for the current repository
67
+ If you are already inside a Git repository folder, you can simply run:
68
+ ```bash
69
+ github-growth-plot
70
+ ```
71
+ This detects the repository, downloads the stargazers to a CSV, and outputs the SVG plot in the `assets/` directory.
72
+
73
+ ### 2️⃣ Run for a specific repository
74
+ You can specify any repository using the standard `owner/repo` format:
75
+ ```bash
76
+ github-growth-plot "google/jax"
77
+ ```
78
+
79
+ ### 3️⃣ Auto-publish to README
80
+ Want to display the chart on your project's main page? Pass the `--publish` flag:
81
+ ```bash
82
+ github-growth-plot --publish
83
+ ```
84
+ This automatically appends the following HTML snippet to the bottom of your `README.md`:
85
+ ```html
86
+ <p align="center">
87
+ <img src="./assets/<username>_<reponame>_growth.svg" alt="<owner>/<repo>" width="100%" />
88
+ </p>
89
+ ```
90
+
91
+ ## 📂 Generated Files
92
+
93
+ When executed, the script generates and manages the following files:
94
+ - 🖼️ **`assets/<username>_<reponame>_growth.svg`**: The generated vector graph showing star growth over time.
95
+ - 📄 **`<username>_<reponame>_stargazers.csv`**: Raw historical star data (automatically ignored via `.gitignore`).
96
+ - 🙈 **`.gitignore`**: Updated automatically to ignore the generated CSV file.
97
+
98
+ ---
99
+ *Made with ❤️ for Open Source Maintainers.*
100
+
@@ -0,0 +1,8 @@
1
+ github_growth_plotter/__init__.py,sha256=AoM7mnMJBf91xMUQD3E6hxoTD3EEteiE0gulyzIbIGw,46
2
+ github_growth_plotter/cli.py,sha256=0euDYtWC01oJt6cUcD_Yg77NQonw3Qup3rH1RnWTKbg,6832
3
+ github_growth_plotter-0.1.0.dist-info/licenses/LICENSE,sha256=aMKES33CpfnVgmxv1FVtwDajlgzhPZ695UF8-E8rsy8,1068
4
+ github_growth_plotter-0.1.0.dist-info/METADATA,sha256=EewdJYAxUm_lqa94j8jTEoFFbKAF3hHBjmpOsxYyYsw,4304
5
+ github_growth_plotter-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
6
+ github_growth_plotter-0.1.0.dist-info/entry_points.txt,sha256=Z3m0SN3KLjTnF3m7EonTWKau_fc4oZWSmyLvb9ZMMuY,70
7
+ github_growth_plotter-0.1.0.dist-info/top_level.txt,sha256=TEWCDu-4GmSdG4BfBpAum7uW9qARSqTUwxap9ztTfS0,22
8
+ github_growth_plotter-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ github-growth-plot = github_growth_plotter.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ishan Dutta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ github_growth_plotter