-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGithabo.py
More file actions
3193 lines (2658 loc) · 140 KB
/
Copy pathGithabo.py
File metadata and controls
3193 lines (2658 loc) · 140 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
GitHub Data Collector (GraphQL Version)
Скрипт для сбора информации о форках и issues пользователя из GitHub GraphQL API
Эта версия использует GraphQL API вместо REST API для более эффективного сбора данных.
Требования:
- Python 3.6+
- requests library
- GitHub Personal Access Token (PAT)
Установка зависимостей:
pip install requests
Использование:
1. Создайте PAT токен в GitHub (Settings → Developer settings → Personal access tokens)
2. Установите переменную окружения GITHUB_TOKEN или измените TOKEN в скрипте
3. Запустите скрипт: python github_data_collector_graphql.py
Преимущества GraphQL версии:
- Один запрос для получения всех данных
- Более эффективное использование API (меньше запросов)
- Точные поля данных без лишней информации
- Лучшая производительность для больших объемов данных
"""
import os
import json
import csv
import time
import sys
import base64
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass
import requests
@dataclass
class LicenseResult:
repo_name: str
success: bool
license_type: str
message: str
already_had_license: bool = False
error: Optional[str] = None
class GitHubLicenseBatchManager:
"""Менеджер для массового добавления лицензий в GitHub репозитории"""
def __init__(self, token: str):
self.token = token
self.headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
}
self.base_url = 'https://api.github.com'
self.session = requests.Session()
self.session.headers.update(self.headers)
# Доступные лицензии
self.available_licenses = [
'MIT', 'Apache-2.0', 'GPL-3.0', 'GPL-2.0', 'BSD-3-Clause',
'BSD-2-Clause', 'ISC', 'LGPL-3.0', 'LGPL-2.1', 'Unlicense'
]
def get_authenticated_user(self) -> Optional[str]:
"""Получение имени текущего пользователя"""
url = f'{self.base_url}/user'
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
user_data = response.json()
return user_data.get('login')
return None
def get_user_info(self) -> Optional[Dict]:
"""Получение информации о пользователе"""
url = f'{self.base_url}/user'
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.json()
return None
def get_my_repos(self, include_forks: bool = False) -> List[Tuple[str, str, Dict]]:
"""Получение всех репозиториев пользователя"""
url = f'{self.base_url}/user/repos'
params = {
'type': 'all',
'per_page': 100,
'sort': 'updated',
'direction': 'desc'
}
all_repos = []
page = 1
print("🔍 Получаем список ваших репозиториев...")
while True:
params['page'] = page
response = requests.get(url, headers=self.headers, params=params)
if response.status_code != 200:
print(f"❌ Ошибка при получении репозиториев: {response.status_code}")
break
repos = response.json()
if not repos:
break
for repo in repos:
# Фильтрация форков если нужно
if not include_forks and repo.get('fork', False):
continue
all_repos.append((repo['owner']['login'], repo['name'], repo))
print(f"📄 Обработана страница {page}, найдено {len(repos)} репозиториев")
page += 1
if page > 100:
break
print(f"✅ Всего найдено {len(all_repos)} репозиториев")
return all_repos
def check_existing_license(self, owner: str, repo: str) -> Optional[Dict]:
"""Проверка наличия лицензии в репозитории"""
# Проверка через API
url = f'{self.base_url}/repos/{owner}/{repo}'
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
repo_data = response.json()
api_license = repo_data.get('license')
if api_license:
return {
'source': 'api',
'license': api_license.get('name', 'Unknown'),
'key': api_license.get('key', '')
}
# Проверка файлов лицензий
license_files = ['LICENSE', 'LICENSE.txt', 'LICENSE.md', 'LICENCE', 'COPYING']
for license_file in license_files:
file_url = f'{self.base_url}/repos/{owner}/{repo}/contents/{license_file}'
file_response = requests.get(file_url, headers=self.headers)
if file_response.status_code == 200:
return {
'source': 'file',
'license': 'Unknown (file exists)',
'file': license_file
}
return None
def get_license_template(self, license_key: str) -> Optional[str]:
"""Получение шаблона лицензии"""
url = f'{self.base_url}/licenses/{license_key}'
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.json()['body']
return None
def prepare_license_content(self, license_key: str, author_name: str = None,
author_email: str = None, year: int = None) -> Optional[str]:
"""Подготовка содержимого лицензии с заменой placeholders"""
license_content = self.get_license_template(license_key)
if not license_content:
return None
# Замена placeholders
current_year = year or datetime.now().year
replacements = {
'[year]': str(current_year),
'[yyyy]': str(current_year),
'[fullname]': author_name or 'Author',
'[name of copyright owner]': author_name or 'Author',
'[email]': author_email or 'author@example.com'
}
for placeholder, replacement in replacements.items():
license_content = license_content.replace(placeholder, replacement)
return license_content
def add_license_to_repo(self, owner: str, repo: str, license_key: str,
author_name: str = None, author_email: str = None,
force: bool = False) -> LicenseResult:
"""Добавление лицензии в репозиторий"""
repo_full_name = f"{owner}/{repo}"
# Проверка существующей лицензии
existing_license = self.check_existing_license(owner, repo)
if existing_license and not force:
return LicenseResult(
repo_name=repo_full_name,
success=False,
license_type=existing_license['license'],
message=f"Лицензия уже существует: {existing_license['license']}",
already_had_license=True
)
# Подготовка содержимого лицензии
license_content = self.prepare_license_content(license_key, author_name, author_email)
if not license_content:
return LicenseResult(
repo_name=repo_full_name,
success=False,
license_type=license_key,
message="Не удалось получить шаблон лицензии",
error="Template not found"
)
# Создание файла LICENSE
url = f'{self.base_url}/repos/{owner}/{repo}/contents/LICENSE'
content_encoded = base64.b64encode(license_content.encode('utf-8')).decode('utf-8')
data = {
'message': f'Add {license_key} license',
'content': content_encoded,
'committer': {
'name': author_name or 'GitHub API',
'email': author_email or 'noreply@github.com'
}
}
response = requests.put(url, headers=self.headers, json=data)
if response.status_code == 201:
return LicenseResult(
repo_name=repo_full_name,
success=True,
license_type=license_key,
message="Лицензия успешно добавлена"
)
else:
error_msg = "Unknown error"
if response.status_code == 409:
error_msg = "Файл LICENSE уже существует"
elif response.status_code == 403:
error_msg = "Нет прав на запись в репозиторий"
elif response.status_code == 404:
error_msg = "Репозиторий не найден"
return LicenseResult(
repo_name=repo_full_name,
success=False,
license_type=license_key,
message=f"Ошибка добавления лицензии: {error_msg}",
error=f"HTTP {response.status_code}"
)
def batch_add_licenses(self, license_key: str, author_name: str = None,
author_email: str = None, include_forks: bool = False,
force: bool = False, exclude_repos: List[str] = None,
include_only: List[str] = None) -> List[LicenseResult]:
"""Массовое добавление лицензий во все репозитории"""
exclude_repos = exclude_repos or []
# Получение информации о пользователе
user_info = self.get_user_info()
if user_info and not author_name:
author_name = user_info.get('name') or user_info.get('login')
if user_info and not author_email:
author_email = user_info.get('email')
# Получение списка репозиториев
repos = self.get_my_repos(include_forks=include_forks)
# Фильтрация репозиториев
if include_only:
repos = [(o, r, d) for o, r, d in repos if f"{o}/{r}" in include_only]
repos = [(o, r, d) for o, r, d in repos if f"{o}/{r}" not in exclude_repos]
if not repos:
print("❌ Нет репозиториев для обработки")
return []
print(f"\n🚀 Начинаем добавление лицензии {license_key} в {len(repos)} репозиториев")
print(f"👤 Автор: {author_name}")
print(f"📧 Email: {author_email}")
print(f"🔄 Принудительное обновление: {'Да' if force else 'Нет'}")
results = []
for i, (owner, repo, repo_data) in enumerate(repos, 1):
print(f"\n[{i}/{len(repos)}] Обработка {owner}/{repo}...")
# Задержка для избежания rate limiting
if i > 1:
time.sleep(1)
result = self.add_license_to_repo(
owner, repo, license_key, author_name, author_email, force
)
results.append(result)
# Вывод результата
if result.success:
print(f"✅ {result.message}")
elif result.already_had_license:
print(f"⚠️ {result.message}")
else:
print(f"❌ {result.message}")
return results
def interactive_batch_setup(self):
"""Интерактивная настройка batch добавления лицензий"""
print("🎯 Интерактивная настройка добавления лицензий")
print("=" * 50)
# Получение информации о пользователе
user_info = self.get_user_info()
if not user_info:
print("❌ Не удалось получить информацию о пользователе")
return
username = user_info.get('login')
user_name = user_info.get('name') or username
user_email = user_info.get('email')
print(f"👤 Пользователь: {username}")
print(f"📝 Имя: {user_name}")
print(f"📧 Email: {user_email or 'Не указан'}")
# Выбор лицензии
print("\n📋 Доступные лицензии:")
for i, license_type in enumerate(self.available_licenses, 1):
print(f"{i}. {license_type}")
while True:
try:
choice = input(f"\nВыберите лицензию (1-{len(self.available_licenses)}): ").strip()
license_index = int(choice) - 1
if 0 <= license_index < len(self.available_licenses):
selected_license = self.available_licenses[license_index]
break
else:
print("❌ Неверный выбор")
except ValueError:
print("❌ Введите число")
# Настройка автора
custom_name = input(f"\nИмя автора [{user_name}]: ").strip()
author_name = custom_name if custom_name else user_name
custom_email = input(f"Email автора [{user_email or 'noreply@github.com'}]: ").strip()
author_email = custom_email if custom_email else (user_email or 'noreply@github.com')
# Дополнительные опции
include_forks = input("\nВключить форки? (y/n) [n]: ").strip().lower() in ['y', 'yes']
force = input("Принудительно обновить существующие лицензии? (y/n) [n]: ").strip().lower() in ['y', 'yes']
# Исключения
exclude_input = input("\nРепозитории для исключения (через запятую): ").strip()
exclude_repos = [repo.strip() for repo in exclude_input.split(',') if repo.strip()]
# Подтверждение
print("\n📊 Настройки:")
print(f" Лицензия: {selected_license}")
print(f" Автор: {author_name}")
print(f" Email: {author_email}")
print(f" Включить форки: {'Да' if include_forks else 'Нет'}")
print(f" Принудительное обновление: {'Да' if force else 'Нет'}")
print(f" Исключить: {', '.join(exclude_repos) if exclude_repos else 'Нет'}")
confirm = input("\nПродолжить? (y/n): ").strip().lower()
if confirm not in ['y', 'yes']:
print("❌ Отменено")
return
# Запуск batch обработки
results = self.batch_add_licenses(
license_key=selected_license,
author_name=author_name,
author_email=author_email,
include_forks=include_forks,
force=force,
exclude_repos=exclude_repos
)
# Отчет
self.print_batch_report(results)
# Сохранение отчета
save_report = input("\n💾 Сохранить отчет в файл? (y/n): ").strip().lower()
if save_report in ['y', 'yes']:
self.save_batch_report(results, selected_license)
def print_batch_report(self, results: List[LicenseResult]):
"""Вывод отчета о batch операции"""
print("\n" + "=" * 80)
print("📊 ОТЧЕТ О ДОБАВЛЕНИИ ЛИЦЕНЗИЙ")
print("=" * 80)
successful = [r for r in results if r.success]
already_licensed = [r for r in results if r.already_had_license]
failed = [r for r in results if not r.success and not r.already_had_license]
print(f"\n✅ Успешно добавлено: {len(successful)}")
print(f"⚠️ Уже имели лицензию: {len(already_licensed)}")
print(f"❌ Ошибки: {len(failed)}")
print(".1f")
if successful:
print("\n{'='*20} УСПЕШНО ДОБАВЛЕНО {'='*20}")
for result in successful:
print(f"✅ {result.repo_name} - {result.license_type}")
if already_licensed:
print("\n{'='*20} УЖЕ ИМЕЛИ ЛИЦЕНЗИЮ {'='*20}")
for result in already_licensed:
print(f"⚠️ {result.repo_name} - {result.license_type}")
if failed:
print("\n{'='*20} ОШИБКИ {'='*20}")
for result in failed:
print(f"❌ {result.repo_name} - {result.message}")
def save_batch_report(self, results: List[LicenseResult], license_type: str):
"""Сохранение отчета в файл"""
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f"license_batch_report_{license_type}_{timestamp}.json"
report_data = {
'timestamp': datetime.now().isoformat(),
'license_type': license_type,
'total_repos': len(results),
'successful': len([r for r in results if r.success]),
'already_licensed': len([r for r in results if r.already_had_license]),
'failed': len([r for r in results if not r.success and not r.already_had_license]),
'results': [
{
'repo_name': r.repo_name,
'success': r.success,
'license_type': r.license_type,
'message': r.message,
'already_had_license': r.already_had_license,
'error': r.error
}
for r in results
]
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(report_data, f, ensure_ascii=False, indent=2)
print(f"💾 Отчет сохранен в {filename}")
def check_topics_presence(self) -> Dict[str, Any]:
"""
Проверяет наличие тегов (топиков) во всех репозиториях пользователя
"""
print("🏷️ Проверяем наличие тегов (топиков) во всех репозиториях...")
# Создаем экземпляр GitHubDataCollector для получения данных с топиками через GraphQL
collector = GitHubDataCollector(self.token)
repos = collector.get_user_repositories()
if not repos:
return {"error": "Не удалось получить репозитории"}
topics_status = {
"with_topics": [],
"without_topics": [],
"errors": []
}
print(f"Анализируем {len(repos)} репозиториев...")
for i, repo_data in enumerate(repos, 1):
repo_full_name = repo_data.get("nameWithOwner", "unknown/unknown")
print(f" {i}/{len(repos)}: {repo_full_name}")
try:
# Проверяем топики через GraphQL
repository_topics = repo_data.get("repositoryTopics", {}).get("nodes", [])
has_topics_graphql = bool(repository_topics and len(repository_topics) > 0)
current_topics = []
if has_topics_graphql:
current_topics = [node.get("topic", {}).get("name", "") for node in repository_topics]
if has_topics_graphql:
topics_status["with_topics"].append({
"repo": repo_full_name,
"topics": current_topics,
"topics_count": len(current_topics),
"url": f"https://github.com/{repo_full_name}",
"stars": repo_data.get("stargazerCount", 0)
})
else:
topics_status["without_topics"].append({
"repo": repo_full_name,
"url": f"https://github.com/{repo_full_name}",
"stars": repo_data.get("stargazerCount", 0),
"description": repo_data.get("description", "")
})
except Exception as e:
topics_status["errors"].append({
"repo": repo_full_name,
"error": str(e)
})
result = {
"total_repos": len(repos),
"with_topics_count": len(topics_status["with_topics"]),
"without_topics_count": len(topics_status["without_topics"]),
"errors_count": len(topics_status["errors"]),
"topics_percentage": round(len(topics_status["with_topics"]) / len(repos) * 100, 1) if repos else 0,
"details": topics_status
}
print("\n🏷️ РЕЗУЛЬТАТЫ ПРОВЕРКИ ТЕГОВ:")
print(f"Всего репозиториев: {result['total_repos']}")
print(f"С тегами: {result['with_topics_count']} ({result['topics_percentage']}%)")
print(f"Без тегов: {result['without_topics_count']}")
print(f"Ошибки проверки: {result['errors_count']}")
return result
def save_topics_check_to_csv(self, topics_data: Dict[str, Any], filename: str):
"""Сохранить результаты проверки тегов в CSV"""
if not topics_data or "details" not in topics_data:
print("Нет данных для сохранения")
return
details = topics_data["details"]
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Заголовок
writer.writerow(["Анализ наличия тегов (топиков)"])
writer.writerow([])
# Общая статистика
writer.writerow(["Общая статистика"])
writer.writerow(["Показатель", "Значение"])
writer.writerow(["Всего репозиториев", topics_data.get("total_repos", 0)])
writer.writerow(["С тегами", f"{topics_data.get('with_topics_count', 0)} ({topics_data.get('topics_percentage', 0)}%)"])
writer.writerow(["Без тегов", topics_data.get("without_topics_count", 0)])
writer.writerow(["Ошибки", topics_data.get("errors_count", 0)])
writer.writerow([])
# Репозитории с тегами
if details.get("with_topics"):
writer.writerow(["Репозитории С ТЕГАМИ"])
writer.writerow(["Репозиторий", "Количество тегов", "Теги", "Звезды", "URL"])
for repo in sorted(details["with_topics"], key=lambda x: x.get("topics_count", 0), reverse=True):
topics_str = ", ".join(repo.get("topics", [])[:5]) # Ограничим до 5 тегов для читаемости
if len(repo.get("topics", [])) > 5:
topics_str += f" (+{len(repo.get('topics', [])) - 5} ещё)"
writer.writerow([
repo.get("repo", ""),
repo.get("topics_count", 0),
topics_str,
repo.get("stars", 0),
repo.get("url", "")
])
writer.writerow([])
# Репозитории без тегов
if details.get("without_topics"):
writer.writerow(["Репозитории БЕЗ ТЕГОВ"])
writer.writerow(["Репозиторий", "Звезды", "Описание", "URL"])
for repo in sorted(details["without_topics"], key=lambda x: x.get("stars", 0), reverse=True):
writer.writerow([
repo.get("repo", ""),
repo.get("stars", 0),
repo.get("description", "")[:50] if repo.get("description") else "",
repo.get("url", "")
])
writer.writerow([])
# Ошибки
if details.get("errors"):
writer.writerow(["ОШИБКИ ПРОВЕРКИ"])
writer.writerow(["Репозиторий", "Ошибка"])
for error in details["errors"]:
writer.writerow([
error.get("repo", ""),
error.get("error", "")
])
print(f"Результаты проверки тегов сохранены в {filename}")
def check_readme_presence(self, include_forks: bool = False) -> Dict[str, Any]:
"""
Проверяет наличие README файлов во всех репозиториях пользователя
"""
print("🔍 Проверяем наличие README файлов во всех репозиториях...")
# Получаем список репозиториев
repos = self.get_my_repos(include_forks=include_forks)
if not repos:
return {"error": "Не удалось получить репозитории"}
readme_status = {
"with_readme": [],
"without_readme": [],
"errors": []
}
print(f"Анализируем {len(repos)} репозиториев...")
for i, (owner, repo, repo_data) in enumerate(repos, 1):
repo_full_name = f"{owner}/{repo}"
print(f" {i}/{len(repos)}: {repo_full_name}")
try:
# Проверяем README файлы через API
readme_files = ["README.md", "README.rst", "README.txt", "README", "readme.md", "Readme.md"]
has_readme = False
readme_found = None
for readme_file in readme_files:
readme_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{readme_file}"
readme_response = self.session.get(readme_url)
if readme_response.status_code == 200:
has_readme = True
readme_found = readme_file
break
if has_readme:
readme_status["with_readme"].append({
"repo": repo_full_name,
"readme_file": readme_found,
"url": f"https://github.com/{repo_full_name}",
"stars": repo_data.get("stargazerCount", 0)
})
else:
readme_status["without_readme"].append({
"repo": repo_full_name,
"url": f"https://github.com/{repo_full_name}",
"stars": repo_data.get("stargazerCount", 0),
"description": repo_data.get("description", "")
})
except Exception as e:
readme_status["errors"].append({
"repo": repo_full_name,
"error": str(e)
})
result = {
"total_repos": len(repos),
"with_readme_count": len(readme_status["with_readme"]),
"without_readme_count": len(readme_status["without_readme"]),
"errors_count": len(readme_status["errors"]),
"readme_percentage": round(len(readme_status["with_readme"]) / len(repos) * 100, 1) if repos else 0,
"details": readme_status
}
print("\n📊 РЕЗУЛЬТАТЫ ПРОВЕРКИ README:")
print(f"Всего репозиториев: {result['total_repos']}")
print(f"С README: {result['with_readme_count']} ({result['readme_percentage']}%)")
print(f"Без README: {result['without_readme_count']}")
print(f"Ошибки проверки: {result['errors_count']}")
return result
def save_readme_check_to_csv(self, readme_data: Dict[str, Any], filename: str):
"""Сохранить результаты проверки README в CSV"""
if not readme_data or "details" not in readme_data:
print("Нет данных для сохранения")
return
details = readme_data["details"]
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# Заголовок
writer.writerow(["Анализ наличия README файлов"])
writer.writerow([])
# Общая статистика
writer.writerow(["Общая статистика"])
writer.writerow(["Показатель", "Значение"])
writer.writerow(["Всего репозиториев", readme_data.get("total_repos", 0)])
writer.writerow(["С README", f"{readme_data.get('with_readme_count', 0)} ({readme_data.get('readme_percentage', 0)}%)"])
writer.writerow(["Без README", readme_data.get("without_readme_count", 0)])
writer.writerow(["Ошибки", readme_data.get("errors_count", 0)])
writer.writerow([])
# Репозитории с README
if details.get("with_readme"):
writer.writerow(["Репозитории С README"])
writer.writerow(["Репозиторий", "Файл README", "Звезды", "URL"])
for repo in sorted(details["with_readme"], key=lambda x: x.get("stars", 0), reverse=True):
writer.writerow([
repo.get("repo", ""),
repo.get("readme_file", ""),
repo.get("stars", 0),
repo.get("url", "")
])
writer.writerow([])
# Репозитории без README
if details.get("without_readme"):
writer.writerow(["Репозитории БЕЗ README"])
writer.writerow(["Репозиторий", "Звезды", "Описание", "URL"])
for repo in sorted(details["without_readme"], key=lambda x: x.get("stars", 0), reverse=True):
writer.writerow([
repo.get("repo", ""),
repo.get("stars", 0),
repo.get("description", "")[:50] if repo.get("description") else "",
repo.get("url", "")
])
writer.writerow([])
# Ошибки
if details.get("errors"):
writer.writerow(["ОШИБКИ ПРОВЕРКИ"])
writer.writerow(["Репозиторий", "Ошибка"])
for error in details["errors"]:
writer.writerow([
error.get("repo", ""),
error.get("error", "")
])
print(f"Результаты проверки README сохранены в {filename}")
class GitHubDataCollector:
"""Класс для сбора данных из GitHub API"""
def __init__(self, token: str, username: str = None):
"""
Инициализация коллектора
Args:
token: GitHub Personal Access Token
username: Имя пользователя GitHub (если None, будет получено автоматически)
"""
self.token = token
self.username = username
self.base_url = "https://api.github.com"
self.session = requests.Session()
# Настройка сессии
self.session.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "GitHub-Data-Collector-GraphQL/1.0"
})
# Получаем username если не указан
if not self.username:
self.username = self._get_current_user()
def _get_current_user(self) -> str:
"""Получить имя текущего пользователя"""
response = self.session.get(f"{self.base_url}/user")
response.raise_for_status()
return response.json()["login"]
def _make_request(self, url: str, params: Dict = None) -> Dict:
"""
Сделать запрос к API с обработкой ошибок и rate limiting
Args:
url: URL для запроса
params: Параметры запроса
Returns:
JSON ответ от API
"""
while True:
response = self.session.get(url, params=params)
if response.status_code == 200:
return response.json()
elif response.status_code == 403:
# Rate limit или другие ограничения
reset_time = int(response.headers.get("X-RateLimit-Reset", 0))
wait_time = max(reset_time - time.time(), 60) # Минимум 60 секунд
print(f"Rate limit exceeded. Waiting {wait_time:.0f} seconds...")
time.sleep(wait_time)
continue
else:
response.raise_for_status()
def _make_graphql_request(self, query: str, variables: Dict = None) -> Dict:
"""
Сделать GraphQL запрос с обработкой ошибок и rate limiting
Args:
query: GraphQL запрос
variables: Переменные для запроса
Returns:
JSON ответ от GraphQL API
"""
while True:
payload = {"query": query}
if variables:
payload["variables"] = variables
response = self.session.post(
f"{self.base_url}/graphql",
json=payload
)
if response.status_code == 200:
result = response.json()
if "errors" in result:
raise Exception(f"GraphQL errors: {result['errors']}")
return result["data"]
elif response.status_code == 403:
# Rate limit или другие ограничения
reset_time = int(response.headers.get("X-RateLimit-Reset", 0))
wait_time = max(reset_time - time.time(), 60) # Минимум 60 секунд
print(f"Rate limit exceeded. Waiting {wait_time:.0f} seconds...")
time.sleep(wait_time)
continue
else:
response.raise_for_status()
def get_all_forks(self) -> List[Dict[str, Any]]:
"""
Получить все форки пользователя через GraphQL
Returns:
Список форков с информацией о каждом
"""
print("Получение списка форков через GraphQL...")
forks = []
cursor = None
while True:
query = """
query($username: String!, $after: String) {
user(login: $username) {
repositories(
first: 100,
isFork: true,
orderBy: {field: CREATED_AT, direction: ASC},
after: $after
) {
nodes {
name
nameWithOwner
url
createdAt
pushedAt
updatedAt
description
primaryLanguage {
name
}
forkCount
stargazerCount
parent {
nameWithOwner
url
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
"""
variables = {
"username": self.username,
"after": cursor
}
result = self._make_graphql_request(query, variables)
if not result.get("user") or not result["user"].get("repositories"):
break
repos = result["user"]["repositories"]
page_forks = repos["nodes"]
forks.extend(page_forks)
print(f"Порция: найдено {len(page_forks)} форков (всего: {len(forks)})")
# Проверяем, есть ли еще страницы
if not repos["pageInfo"]["hasNextPage"]:
break
cursor = repos["pageInfo"]["endCursor"]
print(f"Всего найдено форков: {len(forks)}")
return forks
def get_all_issues(self) -> List[Dict[str, Any]]:
"""
Получить все issues пользователя через GraphQL (включая закрытые)
Returns:
Список issues с информацией о каждом
"""
print("Получение списка issues через GraphQL...")
issues = []
cursor = None
while True:
query = """
query($username: String!, $after: String) {
user(login: $username) {
issues(
first: 100,
orderBy: {field: CREATED_AT, direction: ASC},
states: [OPEN, CLOSED],
after: $after
) {
nodes {
title
url
state
createdAt
closedAt
updatedAt
comments {
totalCount
}
labels(first: 10) {
nodes {
name
}
}
repository {
nameWithOwner
url
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
"""
variables = {
"username": self.username,
"after": cursor
}
result = self._make_graphql_request(query, variables)
if not result.get("user") or not result["user"].get("issues"):
break
user_issues = result["user"]["issues"]
page_issues = user_issues["nodes"]
issues.extend(page_issues)
print(f"Порция: найдено {len(page_issues)} issues (всего: {len(issues)})")
# Проверяем, есть ли еще страницы
if not user_issues["pageInfo"]["hasNextPage"]:
break
cursor = user_issues["pageInfo"]["endCursor"]
print(f"Всего найдено issues: {len(issues)}")
return issues
def save_to_json(self, data: Dict[str, Any], filename: str):
"""Сохранить данные в JSON файл"""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"Данные сохранены в {filename}")
def save_forks_to_csv(self, forks: List[Dict[str, Any]], filename: str):
"""Сохранить форки в CSV файл (GraphQL формат)"""
if not forks:
print("Нет форков для сохранения")
return
fieldnames = [