-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunstar_repos.py
113 lines (88 loc) · 3.96 KB
/
unstar_repos.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""GitHub repository unstarring tool.
This module provides functionality to batch unstar GitHub repositories
based on a CSV input file.
"""
import csv
import time
import requests
from config import load_config
class GitHubStarRemover:
"""Handles the unstarring of GitHub repositories."""
def __init__(self):
config = load_config()
self.token = config['github']['token']
self.headers = {
'Authorization': f'token {self.token}',
'Accept': 'application/vnd.github.v3+json'
}
self.base_url = "https://api.github.com"
self.rate_limit_delay = 1
def unstar_repository(self, repo_full_name):
"""Unstar a single GitHub repository.
Args:
repo_full_name (str): Full name of repository (owner/repo)
Returns:
bool: True if unstarring was successful, False otherwise
"""
url = f"{self.base_url}/user/starred/{repo_full_name}"
response = requests.delete(url, headers=self.headers)
if response.status_code == 204: # GitHub API returns 204 for successful unstar
print(f"Successfully unstarred: {repo_full_name}")
return True
print(f"Failed to unstar {repo_full_name}: {response.status_code}")
return False
def process_csv(self, filename='starred_repos.csv', skip_rows=382):
"""Process CSV file to unstar repositories.
Args:
filename (str): Path to CSV file containing repository data
skip_rows (int): Number of initial rows to skip and mark as processed
Returns:
int: Number of repositories successfully unstarred
"""
unstarred_count = 0
processed_rows = []
try:
with open(filename, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
# Validate required columns exist
if not {'full_name', 'unstar'}.issubset(set(fieldnames)):
raise ValueError("CSV must contain 'full_name' and 'unstar' columns")
for i, row in enumerate(reader):
if i < skip_rows: # Already processed rows
row['unstar'] = '1'
processed_rows.append(row)
continue
if row['unstar'] == '0':
try:
if self.unstar_repository(row['full_name']):
unstarred_count += 1
row['unstar'] = '1'
except Exception as e:
print(f"Error processing {row['full_name']}: {str(e)}")
finally:
time.sleep(self.rate_limit_delay)
processed_rows.append(row)
# Write back all rows with updated unstar status
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(processed_rows)
return unstarred_count
except FileNotFoundError:
print(f"Error: Could not find file {filename}")
return 0
except Exception as e:
print(f"Unexpected error processing CSV: {str(e)}")
return 0
def main():
"""Entry point for the GitHub stars remover."""
try:
remover = GitHubStarRemover()
print("Starting to process unstar requests...")
unstarred_count = remover.process_csv()
print(f"Completed! Unstarred {unstarred_count} repositories")
except (requests.RequestException, IOError) as e:
print(f"Operation failed: {str(e)}")
if __name__ == "__main__":
main()