def _calculate_module_name(*, label, module_name):
    """Calculates a module name.

    Args:
        label: The `Label` of the `Target`.
        module_name: The value of the `module_name` attribute of the target.
            Can be `None`.

    Returns:
        `module_name` if not `None`, otherwise it transforms `label` into a
        valid module name (e.g. "//some/pkg:target" becomes "some_pkg_target").
    """
    if module_name:
        return module_name

    label_string = str(label)

    if label_string.startswith("//"):
        label_string = label_string[2:]

    return (label_string
        .replace("@", "")
        .replace("//", "_")
        .replace("-", "_")
        .replace("/", "_")
        .replace(":", "_")
        .replace(".", "_"))