3
  7   ˆl–äY>”Ên-ji@¿pB¸ÈÅ£�þDür,à„ãñŒBy÷�üÿÔ„y¿Ó¿Ð )½    #!/usr/bin/python3
# Copyright (c) 2020 Jelmer VernooÄ³ <jelmer@debian.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# See file /usr/share/common-licenses/GPL-3 for more details.
#
# pylint: disable=invalid-name
# pylint: enable=invalid-name

"""
Command-line interface for the Debian Janitor.

See https://janitor.debian.net/
"""

import argparse
import json
import logging
import subprocess
import sys
from typing import Any, Optional
from urllib.error import HTTPError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

from debian.changelog import Changelog

import devscripts

DEFAULT_API_URL = "https://janitor.debian.net/api/"
USER_AGENT = f"devscripts janitor cli ({devscripts.__version__})"
DEFAULT_URLLIB_TIMEOUT = 30


def _get_json_url(http_url: str, timeout: int = DEFAULT_URLLIB_TIMEOUT) -> Any:
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    logging.debug("Retrieving %s", http_url)
    with urlopen(Request(http_url, headers=headers), timeout=timeout) as resp:
        http_contents = resp.read()
    return json.loads(http_contents)


def schedule(source, campaign, api_url=DEFAULT_API_URL):
    """Schedule a new run for a package.

    Args:
      source: the source package name
      campaign: the campaign to schedule for
    """
    url = f"{api_url}{quote(campaign)}/pkg/{quote(source)}/schedule"
    headers = {"User-Agent": USER_AGENT}
    req = Request(url, headers=headers, method="POST")
    try:
        with urlopen(req) as resp:
            resp = json.load(resp)
    except HTTPError as err:
        if err.code == 404:
            raise NoSuchSource(json.loads(err.read())["reason"]) from err
        raise
    estimated_duration = resp["estimated_duration_seconds"]
    queue_position = resp["queue_position"]
    queue_wait_time = resp["queue_wait_time"]
    return (estimated_duration, queue_position, queue_wait_time)


class MissingDiffError(Exception):
    """There is no diff for the specified package/campaign combination."""


class NoSuchSource(Exception):
    """There is no source package known with the specified name."""


def diff(source, campaign, api_url=DEFAULT_API_URL):
    """Retrieve the source diff for a package/campaign.

    Args:
      source: the source package name
      campaign: the campaign to retrieve
    Returns:
      the diff as a bytestring
    Raises:
      MissingDiffError: If the diff was missing
        (source not valid, campaign not valid, no runs yet, etc)
    """
    url = f"{api_url}{quote(campaign)}/pkg/{quote(source)}/diff"
    headers = {"User-Agent": USER_AGENT, "Accept": "text/plain"}
    req = Request(url, headers=headers)
    try:
        with urlopen(req) as resp:
            data = resp.read()
    except HTTPError as err:
        if err.code == 404:
            raise MissingDiffError(err.read().decode()) from err
        raise err
    return data


def merge(
    source: str, campaign: str, api_url: str = DEFAULT_API_URL, force: bool = False
):  # pylint: disable=R0915
    """Merge changes from a campaign.

    Args:
      source: the source package name
      campaign: applicable campaign
      api_url: API URL
    """
    url = f"{api_url}{quote(campaign)}/pkg/{quote(source)}"
    try:
        result = _get_json_url(url)
    except HTTPError as err:
        if err.code == 404:
            logging.warning("No runs for %s/%s", source, campaign)
            return 1
        raise

    if result["result_code"] != "success":
        if force:
            logging.fatal(
                "Last 