Coverage for sel_tools/gitlab_api/add_user.py: 76%
25 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-04 21:22 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-04 21:22 +0000
1"""Add users to projects."""
3import json
4from pathlib import Path
6import gitlab
8from sel_tools.config import GITLAB_SERVER_URL
9from sel_tools.file_parsing.student_group_parser import (
10 Student,
11 get_student_groups_from_file,
12)
15def add_users(student_repos_file: Path, student_group_file: Path, gitlab_token: str) -> None:
16 """Add all students to repositories."""
17 gitlab_instance = gitlab.Gitlab(GITLAB_SERVER_URL, private_token=gitlab_token)
18 students = get_student_groups_from_file(student_group_file)
19 students_found = find_gitlab_users_of_students(gitlab_instance, students)
20 student_repos = json.loads(student_repos_file.read_text())
21 repo_from_group_id = {
22 int(repo["name"].split("_")[-1]): gitlab_instance.projects.get(repo["id"]) for repo in student_repos
23 }
24 add_students_to_repos(students_found, repo_from_group_id)
27def find_gitlab_users_of_students(gitlab_instance: gitlab.Gitlab, students: list[Student]) -> list[Student]:
28 """Return list of students with their Gitlab users."""
29 for student in students:
30 try:
31 student.gitlab_user = gitlab_instance.users.list(search=student.mail_addr)[0]
32 except IndexError:
33 student.gitlab_user = None
34 print(f"Student {student.name} with {student.mail_addr} not found!")
35 return [student for student in students if student.gitlab_user is not None]
38def add_students_to_repos(students: list[Student], repo_from_group_id: dict) -> None:
39 """Add students to repositories."""
40 print(f"Adding {len(students)} to their projects!")
41 for student in students:
42 repo = repo_from_group_id[student.group_id]
43 repo.members.create(
44 {
45 "user_id": student.gitlab_user.id,
46 "access_level": gitlab.const.DEVELOPER_ACCESS,
47 }
48 )