示例#1
0
 def get(self, endpoint):
     """
     Perform GET GitHub REST request
     """
     url = self._get_url(endpoint)
     LOGGER.debug("GET %s", url)
     return http_call("get", url, headers=_get_headers())
示例#2
0
def http_call(method, url, **kwargs):
    """
    Perform HTTP call

    - Check status code
    - Check JSON validity
    - Return reponse content as a dict
    """
    try:
        response = requests.request(method, url, **kwargs)
        if response:
            LOGGER.info("Response: %s", response.status_code)
        else:
            LOGGER.info("Response: %s",
                        dump.dump_all(response).decode("utf-8"))
    except requests.RequestException as exception:
        LOGGER.error(str(exception))
        raise click.ClickException(str(exception))

    LOGGER.debug(response.content[:500])
    if response.status_code == 200:
        try:
            return response.json()
        except Exception as exception:
            LOGGER.error(str(exception))
            raise click.ClickException(response.text)
    elif response.status_code == 400:
        raise click.ClickException("Bad request")
    elif response.status_code == 401:
        raise click.ClickException("Unauthorized")
    elif response.status_code == 500:
        raise click.ClickException("Internal server error")
    else:
        raise click.ClickException(response.text)
示例#3
0
 def post(self, endpoint, payload):
     """
     Perform POST Slack REST request
     """
     url = _get_slack_url(endpoint)
     LOGGER.debug("POST %s", url)
     LOGGER.debug(payload)
     return http_call("post", url, data=payload)
示例#4
0
def _exec_github_report_query(report_dt):
    try:
        query = OneDayContributionListQuery(report_dt)
        query.execute()  # pylint: disable=no-value-for-parameter
    except Exception as exception:
        LOGGER.exception(str(exception))
    finally:
        return query
示例#5
0
 def get(self, endpoint, params):
     """
     Perform GET Slack REST request
     """
     settings = Settings()
     url = _get_slack_url(endpoint)
     LOGGER.debug("GET %s", url)
     params.append(("token", settings.get_slack_token()))
     return http_call("get", url, headers=_get_headers(), params=params)
示例#6
0
 def load(self):
     """ Load YAML """
     try:
         with open(self.filename, "r") as yaml_file:
             return yaml.load(yaml_file, Loader=yaml.FullLoader) or {}
     except Exception as error:
         from yogit.yogit.logger import LOGGER  # TODO fix mutual inclusion
         LOGGER.error(str(error))
         return {}
示例#7
0
 def get(self, query):
     """
     Perform GET GitHub GraphQL request
     """
     payload = json.dumps({"query": query})
     LOGGER.debug(payload)
     return http_call("post",
                      self.url,
                      headers=_get_headers(),
                      data=payload)
示例#8
0
 def load(self):
     """ Load YAML """
     try:
         with open(self.filename, "r") as yaml_file:
             return yaml.load(yaml_file, Loader=yaml.FullLoader) or {}
     except OSError as error:
         LOGGER.error(str(error))
         return {}
     except Exception as error:
         raise click.ClickException("Cannot parse `{}`: {}".format(self.get_path(), str(error)))
         LOGGER.error(str(error))
示例#9
0
 def _is_outdated(self):
     current_version = get_version()
     try:
         self.query.execute()
         tags = sorted(self.query.get_tags(), key=cmp_to_key(compare), reverse=True)
         latest_version = tags[0]
         outdated = version.parse(current_version) < version.parse(latest_version)
     except Exception as exception:
         # Update check should never fail
         LOGGER.error(str(exception))
         return False, current_version, current_version
     return outdated, current_version, latest_version
示例#10
0
def _http_call(method, url, **kwargs):
    """
    Perform HTTP call and log around it
    """
    try:
        response = requests.request(method, url, **kwargs)
        if response:
            LOGGER.info("Response: %s", response.status_code)
        else:
            LOGGER.info("Response: %s", dump.dump_all(response).decode("utf-8"))
        return response
    except requests.RequestException as exception:
        raise click.ClickException(str(exception))
示例#11
0
 def get(self, endpoint):
     """
     Perform GET GitHub REST request
     """
     url = self._get_url(endpoint)
     LOGGER.debug("GET %s", url)
     response = _http_call("get", url, headers=_get_headers())
     LOGGER.debug(response.json())
     if response.status_code == 200:
         try:
             return response.json()
         except Exception as exception:
             LOGGER.error(str(exception))
             raise click.ClickException(response.text)
     elif response.status_code == 400:
         raise click.ClickException("Bad request")
     elif response.status_code == 401:
         raise click.ClickException("Unauthorized")
     else:
         raise click.ClickException(response.text)
示例#12
0
 def get(self, query):
     """
     Perform GET GitHub GraphQL request
     """
     payload = json.dumps({"query": query})
     LOGGER.debug(payload)
     response = _http_call("post", self.url, headers=_get_headers(), data=payload)
     LOGGER.debug(response.content[:500])
     if response.status_code == 200:
         try:
             return response.json()
         except Exception as exception:
             LOGGER.error(str(exception))
             raise click.ClickException(response.text)
     elif response.status_code == 400:
         raise click.ClickException("Bad request")
     elif response.status_code == 401:
         raise click.ClickException("Unauthorized")
     else:
         raise click.ClickException(response.text)
示例#13
0
def generate_scrum_report(report_dt):
    """
    Generate scrum report based on scrum report template

    Also copy the report in clipboard if wanted
    """
    report_settings = ScrumReportSettings()
    click.secho("Tips:", bold=True)
    click.echo("Рђб To customize report template, edit `{}`".format(
        report_settings.get_path()))
    click.echo("Рђб Begin line with an extra " +
               click.style("<space>", bold=True) + " to indent it")
    click.echo("")

    click.secho("GitHub's cheat sheet ­ЪўЈ:", bold=True)
    report_query = _exec_github_report_query(report_dt)
    if len(report_query.data) == 0:
        click.echo(
            "Рђб Sorry, nothing from GitHub may be you can ask your mum? ­ЪциРђЇ"
        )
    else:
        for contrib in report_query.get_contrib_str():
            click.echo("Рђб {}".format(contrib))
    click.echo("")

    data = {}
    questions = report_settings.get_questions()
    tpl = report_settings.get_template()
    suffix = "Рђб "

    click.secho("Report of {}".format(report_dt.date().isoformat()), bold=True)
    for idx, question in enumerate(questions):
        click.echo(
            click.style(question, bold=True) + " (empty line to move on)")
        answers = []
        while True:
            line = click.prompt("",
                                prompt_suffix=suffix,
                                default="",
                                show_default=False)
            if line == "":
                break
            line = suffix + line
            line = re.sub("^Рђб  ", "    РђБ ", line)
            answers.append(line)
        data["q{}".format(idx)] = question
        data["a{}".format(idx)] = "\n".join(answers)

    report_sections = []
    for section in tpl.get("sections", []):
        template = Template("\n".join(section))
        data["date"] = report_dt.date().isoformat()
        if "${github_report}" in template.template:
            data["github_report"] = report_query.tabulate()
        report_sections.append(template.safe_substitute(data))

    settings = Settings()
    if settings.is_slack_valid():
        if click.confirm("Send to Slack?", prompt_suffix=" "):
            try:
                first_query = None
                for section in report_sections:
                    query = SlackPostMessageQuery(section,
                                                  reply_to=first_query)
                    query.execute()
                    if first_query is None:
                        first_query = query
                query = SlackMessageLinkQuery(first_query)
                query.execute()
                click.secho("Sent! ­Ъцў {}".format(query.url), bold=True)
            except Exception as error:
                click.secho("Failed to send: {}".format(str(error)), bold=True)
                LOGGER.error(str(error))

    report = "\n".join(report_sections)
    if click.confirm("Copy to clipboard?", prompt_suffix=" "):
        try:
            pyperclip.copy(report)
            click.secho("Copied! ­Ъцў", bold=True)
        except Exception as error:
            click.echo(report)
            LOGGER.error(str(error))
            raise click.ClickException(
                "Not supported on your system, please `sudo apt-get install xclip`"
            )
    else:
        click.echo(report)