def integrations_pr()

in detection_rules/devtools.py [0:0]


def integrations_pr(ctx: click.Context, local_repo: str, token: str, draft: bool,
                    pkg_directory: str, base_branch: str, remote: str,
                    branch_name: Optional[str], github_repo: str, assign: Tuple[str, ...], label: Tuple[str, ...]):
    """Create a pull request to publish the Fleet package to elastic/integrations."""
    github = GithubClient(token)
    github.assert_github()
    client = github.authenticated_client
    repo = client.get_repo(github_repo)

    # Use elastic-package to format and lint
    gopath = utils.gopath().strip("'\"")
    assert gopath is not None, "$GOPATH isn't set"

    err = 'elastic-package missing, run: go install github.com/elastic/elastic-package@latest and verify go bin path'
    assert subprocess.check_output(['elastic-package'], stderr=subprocess.DEVNULL), err

    local_repo = Path(local_repo).resolve()
    stack_version = Package.load_configs()["name"]
    package_version = Package.load_configs()["registry_data"]["version"]

    release_dir = RELEASE_DIR / stack_version / "fleet" / package_version
    message = f"[Security Rules] Update security rules package to v{package_version}"

    if not release_dir.exists():
        click.secho("Release directory doesn't exist.", fg="red", err=True)
        click.echo(f"Run {click.style('python -m detection_rules dev build-release', bold=True)} to populate", err=True)
        ctx.exit(1)

    if not local_repo.exists():
        click.secho(f"{github_repo} is not present at {local_repo}.", fg="red", err=True)
        ctx.exit(1)

    # Get the most recent commit hash of detection-rules
    detection_rules_git = utils.make_git()
    long_commit_hash = detection_rules_git("rev-parse", "HEAD")
    short_commit_hash = detection_rules_git("rev-parse", "--short", "HEAD")

    # refresh the local clone of the repository
    git = utils.make_git("-C", local_repo)
    git("checkout", base_branch)
    git("pull", remote, base_branch)

    # Switch to a new branch in elastic/integrations
    branch_name = branch_name or f"detection-rules/{package_version}-{short_commit_hash}"
    git("checkout", "-b", branch_name)

    # Load the changelog in memory, before it's removed. Come back for it after the PR is created
    target_directory = local_repo / pkg_directory
    changelog_path = target_directory / "changelog.yml"
    changelog_entries: list = yaml.safe_load(changelog_path.read_text(encoding="utf-8"))

    changelog_entries.insert(0, {
        "version": package_version,
        "changes": [
            # This will be changed later
            {"description": "Release security rules update", "type": "enhancement",
             "link": "https://github.com/elastic/integrations/pulls/0000"}
        ]
    })

    # Remove existing assets and replace everything
    shutil.rmtree(target_directory)
    actual_target_directory = shutil.copytree(release_dir, target_directory)
    assert Path(actual_target_directory).absolute() == Path(target_directory).absolute(), \
        f"Expected a copy to {pkg_directory}"

    # Add the changelog back
    def save_changelog():
        with changelog_path.open("wt") as f:
            # add a note for other maintainers of elastic/integrations to be careful with versions
            f.write("# newer versions go on top\n")
            f.write("# NOTE: please use pre-release versions (e.g. -beta.0) until a package is ready for production\n")
            yaml.dump(changelog_entries, f, allow_unicode=True, default_flow_style=False, indent=2, sort_keys=False)

    save_changelog()

    def elastic_pkg(*args):
        """Run a command with $GOPATH/bin/elastic-package in the package directory."""
        prev = Path.cwd()
        os.chdir(target_directory)

        try:
            elastic_pkg_cmd = [str(Path(gopath, "bin", "elastic-package"))]
            elastic_pkg_cmd.extend(list(args))
            return subprocess.check_call(elastic_pkg_cmd)
        finally:
            os.chdir(str(prev))

    elastic_pkg("format")

    # Upload the files to a branch
    git("add", pkg_directory)
    git("commit", "-m", message)
    git("push", "--set-upstream", remote, branch_name)

    # Create a pull request (not done yet, but we need the PR number)
    body = textwrap.dedent(f"""