Coverage for sel_tools/gitlab_api/create_repo.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-04 21:22 +0000

1"""Create gitlab repos with contents of source folder.""" 

2 

3import json 

4from pathlib import Path 

5 

6import gitlab 

7from gitlab.v4.objects.projects import Project 

8from tqdm import tqdm 

9 

10from sel_tools.config import AVATAR_PATH, GIT_MAIN_BRANCH, GITLAB_SERVER_URL, RUNNER_ID 

11from sel_tools.gitlab_api.create_commit import create_commit 

12 

13 

14def create_repos( 

15 source_folder: Path, 

16 repo_base_name: str, 

17 group_id: int, 

18 number_of_repos: int, 

19 gitlab_token: str, 

20) -> tuple[list[dict], str]: 

21 """Create gitlab repos with contents of source folder.""" 

22 gitlab_instance = gitlab.Gitlab(GITLAB_SERVER_URL, private_token=gitlab_token) 

23 

24 student_repos = [] 

25 for repo_number in tqdm(range(1, number_of_repos + 1), desc="Creating Student Repos"): 

26 project = gitlab_instance.projects.create(get_repo_settings(group_id, repo_base_name, repo_number)) 

27 configure_project(project) 

28 configure_main_branch(project) 

29 create_commit(source_folder, "Initial commit", project) 

30 student_repos.append({"name": project.name, "id": project.id, "branch": project.default_branch}) 

31 

32 group = gitlab_instance.groups.get(group_id) 

33 return student_repos, group.path 

34 

35 

36def configure_project(gitlab_project: Project) -> None: 

37 """Configure gitlab project.""" 

38 gitlab_project.runners.create({"runner_id": RUNNER_ID}) 

39 gitlab_project.avatar = AVATAR_PATH.read_bytes() 

40 gitlab_project.save() 

41 

42 

43def configure_main_branch(gitlab_project: Project) -> None: 

44 """Configure main branch.""" 

45 gitlab_project.protectedbranches.create( 

46 { 

47 "name": GIT_MAIN_BRANCH, 

48 "merge_access_level": gitlab.const.DEVELOPER_ACCESS, 

49 "push_access_level": gitlab.const.MAINTAINER_ACCESS, 

50 } 

51 ) 

52 

53 

54def get_repo_settings(group_id: int, repo_base_name: str, repo_number: int) -> dict: 

55 """Get gitlab repo settings dictionary.""" 

56 return { 

57 "name": f"{repo_base_name}_{repo_number}", 

58 "description": f"Software Engineering Lab Homework Group {repo_number}", 

59 "namespace_id": group_id, 

60 "jobs_enabled": True, 

61 } 

62 

63 

64def store_student_repo_info_to_config_file( 

65 repo_info_dir: Path, group_name: str, student_repo_infos: list[dict] 

66) -> None: 

67 """Store repo infos into config file created from repo info dir and repo_base_name. 

68 

69 Existing config files will be overwritten. 

70 """ 

71 student_repos_file = repo_info_dir.joinpath(group_name).with_suffix(".json") 

72 student_repos_file.write_text(json.dumps(student_repo_infos, sort_keys=True, indent=2))