-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathread_gitmodules.py
More file actions
68 lines (58 loc) · 2.21 KB
/
read_gitmodules.py
File metadata and controls
68 lines (58 loc) · 2.21 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
import configparser
import re
from typing import Iterable, List, Optional, Union
from gitlab.v4.objects import Project
from gitlab_submodule.objects import Submodule
def list_project_submodules(
project: Project,
ref: Optional[str] = None) -> List[Submodule]:
return list(iterate_project_submodules(project, ref))
def iterate_project_submodules(
project: Project,
ref: Optional[str] = None) -> Iterable[Submodule]:
gitmodules_file_content = _get_gitmodules_file_content(project, ref)
if not gitmodules_file_content:
raise StopIteration
for kwargs in _read_gitmodules_file_content(
gitmodules_file_content):
yield Submodule(
parent_project=project,
parent_ref=ref if ref else project.default_branch,
**kwargs)
def _get_gitmodules_file_content(project: Project,
ref: Optional[str] = None) -> Optional[str]:
try:
gitmodules = project.files.get(
'.gitmodules',
ref=ref if ref else project.default_branch)
return gitmodules.decode().decode('utf-8')
except Exception:
return None
def _read_gitmodules_file_content(
gitmodules_file_content: str
) -> Iterable[dict[str, Union[None, bool, str]]]:
"""Parses contents of .gitmodule file using configparser"""
config = configparser.ConfigParser()
config.optionxform = str
config.read_string(gitmodules_file_content)
stropts = ('branch', 'ignore', 'update')
boolopts = ('recurse', 'shallow')
name_regex = r'submodule "([a-zA-Z0-9\.\-/_]+)"'
for section in config.sections():
try:
kwargs = {
'name': re.match(name_regex, section).group(1),
'path': config.get(section, 'path'),
'url': config.get(section, 'url')
}
except (AttributeError, KeyError):
raise RuntimeError('Failed parsing the .gitmodules contnet')
kwargs.update(
(opt, config.get(section, opt, fallback=None))
for opt in stropts
)
kwargs.update(
(opt, config.getboolean(section, opt, fallback=False))
for opt in boolopts
)
yield kwargs