# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import getpass
import glob
import re
import shutil
import subprocess

import click

import releasetool.commands.common
from releasetool.commands.tag import python


def get_release_notes(ctx: python.Context) -> None:
    click.secho("> Grabbing the release notes.")
    changelog = ctx.github.get_contents(
        ctx.upstream_repo, f"CHANGELOG.md", ref=ctx.release_pr["merge_commit_sha"]
    ).decode("utf-8")

    match = re.search(
        rf"## {ctx.release_version}\n(?P<notes>.+?)(\n##\s|\Z)",
        changelog,
        re.DOTALL | re.MULTILINE,
    )
    if match is not None:
        ctx.release_notes = match.group("notes").strip()
    else:
        ctx.release_notes = ""


def create_release(ctx: python.Context) -> None:
    click.secho("> Creating the release.")

    ctx.github_release = ctx.github.create_release(
        repository=ctx.upstream_repo,
        tag_name=ctx.release_tag,
        target_committish=ctx.release_pr["merge_commit_sha"],
        name=f"{ctx.package_name} {ctx.release_version}",
        body=ctx.release_notes,
    )

    release_location_string = f"Release is at {ctx.github_release['html_url']}"
    click.secho(release_location_string)

    ctx.github.create_pull_request_comment(
        ctx.upstream_repo, ctx.release_pr["number"], release_location_string
    )


def publish_to_pypi(ctx: python.Context) -> None:
    # TODO: Replace this with Kokoro!
    click.secho("> Publishing to PyPI.")
    shutil.rmtree("build", ignore_errors=True)
    shutil.rmtree("dist", ignore_errors=True)
    for path in glob.glob("*.egg-info"):
        shutil.rmtree("path", ignore_errors=True)
    subprocess.check_output(["python3", "setup.py", "sdist", "bdist_wheel"])
    dists = glob.glob("dist/*")
    subprocess.check_call(["twine", "upload"] + dists)


def tag() -> None:
    ctx = python.Context()

    click.secho(f"o/ Hey, {getpass.getuser()}, let's tag a release!", fg="magenta")

    releasetool.commands.common.setup_github_context(ctx)

    python.determine_release_pr(ctx)
    python.determine_release_tag(ctx)
    python.determine_package_name_and_version(ctx)
    get_release_notes(ctx)

    create_release(ctx)

    publish_to_pypi(ctx)

    click.secho(f"\o/ All done!", fg="magenta")

@@ -637,16 +637,41 @@
 bprocess
+%0Afrom urllib import parse
 %0A%0Aimport
@@ -1965,429 +1965,612 @@
     
-# TODO: Replace this with Kokoro!%0A    click.secho(%22%3E Publishing to PyPI.%22)%0A    shutil.rmtree(%22build%22, ignore_errors=True)%0A    shutil.rmtree(%22dist%22, ignore_errors=True)%0A    for path in glob.glob(%22*.egg-info%22):
+kokoro_url = %22https://fusion.corp.google.com/projectanalysis/current/KOKORO/%22%0A    project = f%22prod:cloud-devrel/client-libraries/%7Bctx.package_name%7D/release%22%0A    project_url = parse.urljoin(kokoro_url, parse.quote_plus(project))%0A%0A    click.secho(%0A        f%22%3E Trigger the Kokoro build with the commitish below to publish to PyPI.%22,%0A        fg=%22cyan%22,
 %0A    
+)%0A
     
-shutil.rmtree(%22path%22, ignore_errors
+click.secho(f%22Build:%5Ct%5Ct%7Bclick.style(project_url, underline
 =True)
+%7D%22)
 %0A    
-subprocess.check_output(%5B%22python3%22, %22setup.py%22, %22sdist%22, %22bdist_wheel%22%5D
+click.secho(f%22Commitish:%5Ct%7Bclick.style(ctx.release_tag, bold=True)%7D%22
 )%0A
+%0A
     
-dists = glob.glob(%22dist/*%22)%0A    subprocess.check_call(%5B%22twine%22, %22upload%22%5D + dists
+if click.confirm(%22Would you like to go the Kokoro build page?%22):%0A        click.launch(project_url
 )%0A%0A%0A

Add link to Kokoro release job for python tools (#55)