Skip to content

Commit 828964c

Browse files
authored
Merge branch 'master' into 79-Calls-changed
2 parents e1bf13c + d416547 commit 828964c

17 files changed

+281
-260
lines changed

.DS_Store

-6 KB
Binary file not shown.

75-CreatedDocker/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Инструкция по разворачиванию Forgejo с использованием Docker
2+
Чтобы запустить в Docker контейнере Forgejo необходимо выполнить команду:
3+
```docker-compose up -d```
4+
5+
На localhost:3000 открывается Forgejo, необходимо пройти регистрацию и создать репозиторий.
6+
7+
Для подключения простейшего клиента к данному localhost необходимо передать ему ссылку на репозиторий и API токен.
8+
9+
Получить токен можно через "Settings" -> "Generate Token":
10+
![](forgejo0.png)
11+
![](forgejo1.png)
12+
13+
14+
Далее необходимо отредактировать файл `pyforgejo/.env`, и изменить `API_TOKEN`, `BASE_URL`, `REPO_OWNER` и `REPO_NAME`.
15+
16+
Например:
17+
```
18+
API_TOKEN=b3b55b3a469171bfe2105863332e23d89523d8af
19+
BASE_URL=http://localhost:3000
20+
REPO_OWNER=cyb3rc001
21+
REPO_NAME=test123
22+
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
version: '3'
2+
3+
services:
4+
forgejo:
5+
image: codeberg.org/forgejo/forgejo:1.18
6+
container_name: forgejo
7+
environment:
8+
- USER_UID=1000
9+
- USER_GID=1000
10+
volumes:
11+
- ./forgejo-data:/data
12+
ports:
13+
- "3000:3000"
14+
- "2222:22"
15+
restart: unless-stopped

75-CreatedDocker/forgejo0.png

63.1 KB
Loading

75-CreatedDocker/forgejo1.png

103 KB
Loading

GitHubRepoAPI.py

Lines changed: 6 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,20 @@
1010
IRepositoryAPI,
1111
User,
1212
Comment,
13-
Invite
13+
Invite,
1414
)
1515
from github import Github
1616

1717

1818
class GitHubRepoAPI(IRepositoryAPI):
1919

2020
def __init__(self, client):
21-
self.client = Github(client)
21+
self.client = client
2222

2323
def get_repository(self, id: str) -> Repository | None:
2424
try:
2525
repo = self.client.get_repo(id)
26-
return Repository(_id=repo.full_name, name=repo.name, url=repo.html_url, default_branch=Branch(name=repo.default_branch, last_commit=None), owner=User(login=repo.owner.login,username=repo.owner.name,email=repo.owner.email))
26+
return Repository(_id=repo.full_name, name=repo.name, url=repo.html_url)
2727
except Exception as e:
2828
logging.error(f"Failed to get repository {id} from GitHub: {e}")
2929
return None
@@ -42,10 +42,6 @@ def get_commits(self, repo: Repository) -> list[Commit]:
4242
login=c.author.login,username=c.author.name,email=c.author.email
4343
),
4444
date=c.commit.author.date,
45-
files=[
46-
f.filename
47-
for f in c.files
48-
]
4945
)
5046
for c in commits
5147
]
@@ -72,17 +68,8 @@ def get_issues(self, repo: Repository) -> list[Issue]:
7268
Issue(
7369
_id=i.number,
7470
title=i.title,
71+
author=Contributor(i.user.login, i.user.email or ""),
7572
state=i.state,
76-
created_at=i.created_at,
77-
closed_at=i.closed_at,
78-
closed_by=User(login=i.closed_by.login,username=i.closed_by.name,email=i.closed_by.email) if i.closed_by else None,
79-
body=i.body,
80-
user=User(login=i.user.login,username=i.user.name,email=i.user.email),
81-
labels= [
82-
l.name
83-
for l in i.labels
84-
],
85-
milestone=i.milestone.title if i.milestone else None
8673
)
8774
for i in issues
8875
]
@@ -97,24 +84,8 @@ def get_pull_requests(self, repo: Repository) -> list[PullRequest]:
9784
PullRequest(
9885
_id=p.number,
9986
title=p.title,
100-
author=User(login=p.user.login, username=p.user.name, email=p.user.email),
87+
author=Contributor(p.user.login, p.user.email or ""),
10188
state=p.state,
102-
created_at=p.created_at,
103-
head_label=p.head.label,
104-
base_label=p.base.label,
105-
head_ref=p.head.ref,
106-
base_ref=p.base.ref,
107-
merged_by=User(login=p.merged_by.login, username=p.merged_by.name, email=p.merged_by.email) if p.merged_by else None,
108-
files=[
109-
f.filename
110-
for f in p.get_files()
111-
],
112-
issue_url=p.issue_url,
113-
labels= [
114-
l.name
115-
for l in p.labels
116-
],
117-
milestone=p.milestone.title if p.milestone else None
11889
)
11990
for p in pulls
12091
]
@@ -157,39 +128,7 @@ def get_branches(self, repo: Repository) -> list[Branch]:
157128
return []
158129

159130
def get_wiki_pages(self, repo: Repository) -> list[WikiPage]:
160-
return
161-
162-
def get_forks(self, repo: Repository) -> list[Repository]:
163-
repo_client = self.client.get_repo(repo._id)
164-
result = []
165-
for r in repo_client.get_forks():
166-
result.append(Repository(_id=repo.full_name, name=repo.name, url=repo.html_url))
167-
return result
168-
169-
def get_comments(self, repo, obj) -> list[Comment]:
170-
result = []
171-
if type(obj) == Issue:
172-
# TODO оптимизировать
173-
issues = self.client.get_repo(repo._id).get_issues(state='all')
174-
issue = None
175-
for i in issues:
176-
if i.number == obj._id:
177-
issue = i
178-
break
179-
for c in issue.get_comments():
180-
result.append(Comment(body=c.body,created_at=c.created_at,author=User(login=c.user.login,username=c.user.name,email=c.user.email)))
181-
elif type(obj) == PullRequest:
182-
# TODO оптимизировать
183-
pulls = self.client.get_repo(repo._id).get_pulls(state='all')
184-
pull = None
185-
for p in pulls:
186-
if p.number == obj._id:
187-
pull = p
188-
break
189-
for c in pull.get_comments():
190-
result.append(Comment(body=c.body,created_at=c.created_at,author=User(login=c.user.login,username=c.user.name,email=c.user.email)))
191-
192-
return result
131+
pass
193132

194133
def get_invites(self, repo: Repository) -> list[Invite]:
195134
try:

README.md

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,25 +24,28 @@ docker run -v $(pwd)/output:/app/output checking_repo [--invites] [--commites] [
2424
## Запуск приложения:
2525
1. Логирование commits
2626
```commandline
27-
python3 main.py [-c, --commits] [-t, --token] token (github токен вместо token) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [-b, --branch] branch (branch - название конкретной ветки, откуда брать коммиты или all - логгировать все коммиты изо всех веток)
27+
python3 main.py [-c, --commits] (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [-b, --branch] branch (branch - название конкретной ветки, откуда брать коммиты или all - логгировать все коммиты изо всех веток)
2828
```
2929
2. Логирование issues
3030
```commandline
31-
python3 main.py [-i, --issues] [-t, --token] token (github токен вместо token) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
31+
python3 main.py [-i, --issues] (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
3232
```
3333
3. Логирование pull requests
3434
```commandline
35-
python3 main.py [-p, --pull_requests] [-t, --token] token (github токен вместо token) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [--pr_comments] (если установлен - также выгружаются комментарии к PR)
35+
python3 main.py [-p, --pull_requests] (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [--pr_comments] (если установлен - также выгружаются комментарии к PR)
3636
```
3737
4. Логирование непринятых приглашений в репо
3838
```commandline
39-
python3 main.py --invites [-t, --token] token (github токен вместо token) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
39+
python3 main.py --invites (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
4040
```
4141
5. Логирование вики-репозиториев
4242
```commandline
43-
python3 main.py [-w, --wikis] [-t, --token] token (github токен вместо token) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) --dowland_repos path_drepo (path_drepo - строка пути к директории, где сохраняются вики-репозитории) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
43+
python3 main.py [-w, --wikis] (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) --dowland_repos path_drepo (path_drepo - строка пути к директории, где сохраняются вики-репозитории) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
44+
```
45+
6. Логирование контрибьюторов
46+
```commandline
47+
python3 main.py --contributors (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l, --list] list (list - строка пути к txt файлу со списком репозиториев) --dowland_repos path_drepo (path_drepo - строка пути к директории, где сохраняются вики-репозитории) [-o, --out] out (out - название csv файла, в который будут помещены все логи)
4448
```
45-
4649

4750

4851
## Получение токена для работы с Google таблицей:
@@ -60,10 +63,15 @@ python3 main.py [-w, --wikis] [-t, --token] token (github токен вмест
6063
## Экспорт таблицы в Google Sheets:
6164

6265
``` commandline
63-
python3 main.py [-p, --pull_requests] [-t, --token] token (github токен вместо token) [-l,--list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [--google_token] token.json (файл с google токеном) [--table_id] table_id (id таблицы, указанной в url пути до таблицы) [--sheet_id] sheet_id (id конкретного листа в таблице google)
66+
python3 main.py [-p, --pull_requests] (-t token (github токен вместо token) | --tokens tokens (путь до файла с токенами вместо tokens)) [-l,--list] list (list - строка пути к txt файлу со списком репозиториев) [-o, --out] out (out - название csv файла, в который будут помещены все логи) [--google_token] token.json (файл с google токеном) [--table_id] table_id (id таблицы, указанной в url пути до таблицы) [--sheet_id] sheet_id (id конкретного листа в таблице google)
6467
```
6568

6669
## Файл со списком репозиториев:
6770

6871
Репозитории хранятся в txt файле. Каждый репозиторий записывается в отдельную строку.
6972
Должно быть указано полное имя репозитория. (Название организации/название репозитория)
73+
74+
## Файл со списком токенов:
75+
76+
Каждый токен записывается в отдельную строку.
77+
Токены должны быть привзязаны к разным github аккаунтам. Токены, привязанные к одному аккаунту имеют общий rate_limit.

commits_parser.py

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from utils import logger
22
import pytz
33
from time import sleep
4-
from interface_wrapper import IRepositoryAPI
4+
from github import Github, Repository, GithubException, PullRequest
55

66
EMPTY_FIELD = 'Empty field'
77
TIMEDELTA = 0.05
@@ -17,12 +17,12 @@
1717
'branch',
1818
)
1919

20-
def log_repository_commits(client: IRepositoryAPI, repository, csv_name, start, finish, branch):
20+
21+
def log_repository_commits(repository: Repository, csv_name, start, finish, branch):
2122
branches = []
2223
match branch:
2324
case 'all':
24-
branches = client.get_branches(repository)
25-
for branch in branches:
25+
for branch in repository.get_branches():
2626
branches.append(branch.name)
2727
case None:
2828
branches.append(repository.default_branch)
@@ -31,44 +31,44 @@ def log_repository_commits(client: IRepositoryAPI, repository, csv_name, start,
3131

3232
for branch in branches:
3333
print(f'Processing branch {branch}')
34-
# Используем обёртку для получения коммитов
35-
commits = client.get_commits(repository)
36-
for commit in commits:
34+
# TODO add support of since and until in https://pygithub.readthedocs.io/en/stable/github_objects/Repository.html#github.Repository.Repository.get_commits
35+
for commit in repository.get_commits(sha=branch):
3736
if (
38-
commit.date.astimezone(pytz.timezone(TIMEZONE)) < start
39-
or commit.date.astimezone(pytz.timezone(TIMEZONE)) > finish
37+
commit.commit.author.date.astimezone(pytz.timezone(TIMEZONE)) < start
38+
or commit.commit.author.date.astimezone(pytz.timezone(TIMEZONE))
39+
> finish
4040
):
4141
continue
42-
commit_data = [
43-
repository.name,
44-
commit.author.username,
45-
commit.author.email or EMPTY_FIELD,
46-
commit.date,
47-
'; '.join([file for file in commit.files]),
48-
commit._id,
49-
branch,
50-
]
51-
info = dict(zip(FIELDNAMES, commit_data))
42+
if commit.commit is not None:
43+
nvl = lambda val: val or EMPTY_FIELD
44+
commit_data = [
45+
repository.full_name,
46+
commit.commit.author.name,
47+
nvl(commit.author.login if commit.author else None),
48+
nvl(commit.commit.author.email),
49+
commit.commit.author.date,
50+
'; '.join([file.filename for file in commit.files]),
51+
commit.commit.sha,
52+
branch,
53+
]
54+
info = dict(zip(FIELDNAMES, commit_data))
5255

53-
logger.log_to_csv(csv_name, FIELDNAMES, info)
54-
logger.log_to_stdout(info)
56+
logger.log_to_csv(csv_name, FIELDNAMES, info)
57+
logger.log_to_stdout(info)
58+
59+
sleep(TIMEDELTA)
5560

56-
sleep(TIMEDELTA)
5761

58-
def log_commits(
59-
client: IRepositoryAPI, working_repos, csv_name, start, finish, branch, fork_flag
60-
):
62+
def log_commits(working_repos, csv_name, start, finish, branch, fork_flag):
6163
logger.log_to_csv(csv_name, FIELDNAMES)
6264

63-
for repo in working_repos:
65+
for repo, token in working_repos:
6466
try:
65-
logger.log_title(repo.name)
66-
log_repository_commits(client, repo, csv_name, start, finish, branch)
67+
logger.log_title(repo.full_name)
68+
log_repository_commits(repo, csv_name, start, finish, branch)
6769
if fork_flag:
68-
# TODO
69-
forked_repos = client.get_forks(repo)
70-
for forked_repo in forked_repos:
71-
logger.log_title("FORKED:", forked_repo.name)
70+
for forked_repo in repo.get_forks():
71+
logger.log_title("FORKED:", forked_repo.full_name)
7272
log_repository_commits(forked_repo, csv_name, start, finish, branch)
7373
sleep(TIMEDELTA)
7474
sleep(TIMEDELTA)

0 commit comments

Comments
 (0)