Skip to content

Commit

Permalink
typing: fully annotate tools
Browse files Browse the repository at this point in the history
  • Loading branch information
mensinda committed Sep 8, 2020
1 parent 449dd8e commit 0d57e30
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 21 deletions.
1 change: 1 addition & 0 deletions run_mypy.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
'mesonbuild/ast',
'mesonbuild/wrap',
'run_mypy.py',
'tools',
]

normal_args = ['--follow-imports=skip']
Expand Down
4 changes: 2 additions & 2 deletions tools/build_website.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

from glob import glob

def purge(fname):
def purge(fname: str) -> None:
if not os.path.exists(fname):
return
if os.path.isdir(fname):
shutil.rmtree(fname)
os.unlink(fname)

def update():
def update() -> None:
webdir = 'mesonweb'
repodir = 'mesonwebbuild'
docdir = os.path.join(repodir, 'docs')
Expand Down
19 changes: 10 additions & 9 deletions tools/cmake2meson.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, name: str, args: list):
self.args = args

class Lexer:
def __init__(self):
def __init__(self) -> None:
self.token_specification = [
# Need to be sorted longest to shortest.
('ignore', re.compile(r'[ \t]')),
Expand Down Expand Up @@ -87,11 +87,11 @@ def lex(self, code: str) -> T.Iterator[Token]:
raise ValueError('Lexer got confused line %d column %d' % (lineno, col))

class Parser:
def __init__(self, code: str):
def __init__(self, code: str) -> None:
self.stream = Lexer().lex(code)
self.getsym()

def getsym(self):
def getsym(self) -> None:
try:
self.current = next(self.stream)
except StopIteration:
Expand All @@ -118,8 +118,8 @@ def statement(self) -> Statement:
self.expect('rparen')
return Statement(cur.value, args)

def arguments(self) -> list:
args = []
def arguments(self) -> T.List[T.Union[Token, T.Any]]:
args = [] # type: T.List[T.Union[Token, T.Any]]
if self.accept('lparen'):
args.append(self.arguments())
self.expect('rparen')
Expand All @@ -139,7 +139,7 @@ def parse(self) -> T.Iterator[Statement]:
while not self.accept('eof'):
yield(self.statement())

def token_or_group(arg):
def token_or_group(arg: T.Union[Token, T.List[Token]]) -> str:
if isinstance(arg, Token):
return ' ' + arg.value
elif isinstance(arg, list):
Expand All @@ -148,6 +148,7 @@ def token_or_group(arg):
line += ' ' + token_or_group(a)
line += ' )'
return line
raise RuntimeError('Conversion error in token_or_group')

class Converter:
ignored_funcs = {'cmake_minimum_required': True,
Expand Down Expand Up @@ -183,7 +184,7 @@ def convert_args(self, args: T.List[Token], as_array: bool = True) -> str:
return res[0]
return ''

def write_entry(self, outfile: T.TextIO, t: Statement):
def write_entry(self, outfile: T.TextIO, t: Statement) -> None:
if t.name in Converter.ignored_funcs:
return
preincrement = 0
Expand Down Expand Up @@ -274,7 +275,7 @@ def write_entry(self, outfile: T.TextIO, t: Statement):
outfile.write('\n')
self.indent_level += postincrement

def convert(self, subdir: Path = None):
def convert(self, subdir: Path = None) -> None:
if not subdir:
subdir = self.cmake_root
cfile = Path(subdir).expanduser() / 'CMakeLists.txt'
Expand All @@ -297,7 +298,7 @@ def convert(self, subdir: Path = None):
if subdir == self.cmake_root and len(self.options) > 0:
self.write_options()

def write_options(self):
def write_options(self) -> None:
filename = self.cmake_root / 'meson_options.txt'
with filename.open('w') as optfile:
for o in self.options:
Expand Down
4 changes: 2 additions & 2 deletions tools/dircondenser.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ def get_entries() -> T.List[T.Tuple[int, str]]:
entries.sort()
return entries

def replace_source(sourcefile: str, replacements: T.List[T.Tuple[str, str]]):
def replace_source(sourcefile: str, replacements: T.List[T.Tuple[str, str]]) -> None:
with open(sourcefile, 'r') as f:
contents = f.read()
for old_name, new_name in replacements:
contents = contents.replace(old_name, new_name)
with open(sourcefile, 'w') as f:
f.write(contents)

def condense(dirname: str):
def condense(dirname: str) -> None:
curdir = os.getcwd()
os.chdir(dirname)
entries = get_entries()
Expand Down
16 changes: 8 additions & 8 deletions tools/regenerate_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,29 @@

PathLike = T.Union[Path,str]

def _get_meson_output(root_dir: Path, args: T.List):
def _get_meson_output(root_dir: Path, args: T.List) -> str:
env = os.environ.copy()
env['COLUMNS'] = '80'
return subprocess.run([str(sys.executable), str(root_dir/'meson.py')] + args, check=True, capture_output=True, text=True, env=env).stdout.strip()

def get_commands_data(root_dir: Path):
def get_commands_data(root_dir: Path) -> T.Dict[str, T.Any]:
usage_start_pattern = re.compile(r'^usage: ', re.MULTILINE)
positional_start_pattern = re.compile(r'^positional arguments:[\t ]*[\r\n]+', re.MULTILINE)
options_start_pattern = re.compile(r'^optional arguments:[\t ]*[\r\n]+', re.MULTILINE)
commands_start_pattern = re.compile(r'^[A-Za-z ]*[Cc]ommands:[\t ]*[\r\n]+', re.MULTILINE)

def get_next_start(iterators, end):
def get_next_start(iterators: T.Sequence[T.Any], end: T.Optional[int]) -> int:
return next((i.start() for i in iterators if i), end)

def normalize_text(text):
def normalize_text(text: str) -> str:
# clean up formatting
out = text
out = re.sub(r'\r\n', r'\r', out, flags=re.MULTILINE) # replace newlines with a linux EOL
out = re.sub(r'^ +$', '', out, flags=re.MULTILINE) # remove trailing whitespace
out = re.sub(r'(?:^\n+|\n+$)', '', out) # remove trailing empty lines
return out

def parse_cmd(cmd):
def parse_cmd(cmd: str) -> T.Dict[str, str]:
cmd_len = len(cmd)
usage = usage_start_pattern.search(cmd)
positionals = positional_start_pattern.search(cmd)
Expand All @@ -72,7 +72,7 @@ def parse_cmd(cmd):
'arguments': normalize_text(cmd[arguments_start:cmd_len]),
}

def clean_dir_arguments(text):
def clean_dir_arguments(text: str) -> str:
# Remove platform specific defaults
args = [
'prefix',
Expand Down Expand Up @@ -127,7 +127,7 @@ def regenerate_docs(output_dir: PathLike,
dummy_output_file: T.Optional[PathLike]) -> None:
if not output_dir:
raise ValueError(f'Output directory value is not set')

output_dir = Path(output_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)

Expand All @@ -143,7 +143,7 @@ def regenerate_docs(output_dir: PathLike,
parser = argparse.ArgumentParser(description='Generate meson docs')
parser.add_argument('--output-dir', required=True)
parser.add_argument('--dummy-output-file', type=str)

args = parser.parse_args()

regenerate_docs(output_dir=args.output_dir,
Expand Down

0 comments on commit 0d57e30

Please sign in to comment.