from typing import Optional
import ast


def get_version_using_ast(contents: bytes) -> Optional[str]:
    """Extract the version from the given file, using the Python AST."""
    tree = ast.parse(contents)

    # Only need to check the top-level nodes, and not recurse deeper.
    version: Optional[str] = None
    for child in tree.body:
        # Look for a simple string assignment to __version__
        if (
            isinstance(child, ast.Assign)
            and len(child.targets) == 1
            and isinstance(child.targets[0], ast.Name)
            and child.targets[0].id == "__version__"
            and isinstance(child.value, ast.Str)
        ):
            version = child.value.s
            break

    return version