|
| 1 | +import csv |
| 2 | +import pytz |
| 3 | +from time import sleep |
| 4 | +from github import Github, Repository, GithubException, PullRequest |
| 5 | + |
| 6 | +EMPTY_FIELD = 'Empty field' |
| 7 | +TIMEDELTA = 0.05 |
| 8 | +TIMEZONE = 'Europe/Moscow' |
| 9 | +FIELDNAMES = ('repository name', 'author name', 'author login', 'author email', 'date and time', 'changed files', 'commit id', 'branch') |
| 10 | + |
| 11 | +def log_commit_to_csv(info, csv_name): |
| 12 | + with open(csv_name, 'a', newline='') as file: |
| 13 | + writer = csv.DictWriter(file, fieldnames=FIELDNAMES) |
| 14 | + writer.writerow(info) |
| 15 | + |
| 16 | + |
| 17 | +def log_commit_to_stdout(info): |
| 18 | + print(info) |
| 19 | + |
| 20 | + |
| 21 | +def log_repository_commits(repository: Repository, csv_name, start, finish, branch): |
| 22 | + branches = [] |
| 23 | + match branch: |
| 24 | + case 'all': |
| 25 | + for branch in repository.get_branches(): |
| 26 | + branches.append(branch.name) |
| 27 | + case None: |
| 28 | + branches.append(repository.default_branch) |
| 29 | + case _: |
| 30 | + branches.append(branch) |
| 31 | + |
| 32 | + for branch in branches: |
| 33 | + print(f'Processing branch {branch}') |
| 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): |
| 36 | + if commit.commit.author.date.astimezone( |
| 37 | + pytz.timezone(TIMEZONE)) < start or commit.commit.author.date.astimezone( |
| 38 | + pytz.timezone(TIMEZONE)) > finish: |
| 39 | + continue |
| 40 | + if commit.commit is not None: |
| 41 | + nvl = lambda val: val or EMPTY_FIELD |
| 42 | + commit_data = [repository.full_name, commit.commit.author.name, nvl(commit.author.login), nvl(commit.commit.author.email), |
| 43 | + commit.commit.author.date, '; '.join([file.filename for file in commit.files]), commit.commit.sha, branch] |
| 44 | + info = dict(zip(FIELDNAMES, commit_data)) |
| 45 | + |
| 46 | + log_commit_to_csv(info, csv_name) |
| 47 | + log_commit_to_stdout(info) |
| 48 | + sleep(TIMEDELTA) |
| 49 | + |
| 50 | + |
| 51 | +def log_commits(client: Github, working_repos, csv_name, start, finish, branch, fork_flag): |
| 52 | + with open(csv_name, 'w', newline='') as file: |
| 53 | + writer = csv.writer(file) |
| 54 | + writer.writerow(FIELDNAMES) |
| 55 | + |
| 56 | + |
| 57 | + for repo in working_repos: |
| 58 | + try: |
| 59 | + print('=' * 20, repo.full_name, '=' * 20) |
| 60 | + log_repository_commits(repo, csv_name, start, finish, branch) |
| 61 | + if fork_flag: |
| 62 | + for forked_repo in repo.get_forks(): |
| 63 | + print('=' * 20, "FORKED:", forked_repo.full_name, '=' * 20) |
| 64 | + log_repository_commits(forked_repo, csv_name, start, finish, branch) |
| 65 | + sleep(TIMEDELTA) |
| 66 | + sleep(TIMEDELTA) |
| 67 | + except Exception as e: |
| 68 | + print(e) |
0 commit comments