def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False):
with tokenize.open(src) as src_buffer:<EOL><INDENT>src_encoding = src_buffer.encoding<EOL>src_node = lib2to3_parse(src_buffer.read())<EOL><DEDENT>try:<EOL><INDENT>with open((pyi_dir / src.name).with_suffix('<STR_LIT>')) as pyi_file:<EOL><INDENT>pyi_txt = pyi_file.read()<EOL><DEDENT><DEDENT>except FileNotFoundError:<EOL><INDENT>if not quiet:<EOL><INDENT>print(<EOL>f'<STR_LIT>',<EOL>file=sys.stderr,<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pyi_ast = ast3.parse(pyi_txt)<EOL>assert isinstance(pyi_ast, ast3.Module)<EOL>reapply_all(pyi_ast.body, src_node)<EOL><DEDENT>fix_remaining_type_comments(src_node)<EOL>targets.mkdir(parents=True, exist_ok=True)<EOL>with open(targets / src.name, '<STR_LIT:w>', encoding=src_encoding) as target_file:<EOL><INDENT>target_file.write(lib2to3_unparse(src_node, hg=hg))<EOL><DEDENT>return targets / src.name<EOL>
Retype `src`, finding types in `pyi_dir`. Save in `targets`.

    The file should remain formatted exactly as it was before, save for:
    - annotations
    - additional imports needed to satisfy annotations
    - additional module-level names needed to satisfy annotations

    Type comments in sources are normalized to type annotations.