Example #1
0
def test_setup_does_not_erase_if_user_does_not_want(runner):
    result = runner.invoke(cli.main, ["account", "setup"],
                           input="\n".join(["n", "n"]))
    assert result.exit_code == ExitCode.NO_ERROR.value
    assert "Reset GitHub config?" in result.output
    assert "Reset Slack config?" in result.output
    settings = Settings()
    assert settings.is_github_valid()
    assert settings.is_slack_valid()
Example #2
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)
Example #3
0
def _setup_slack():
    settings = Settings()

    if settings.is_slack_valid():
        if not click.confirm("Reset Slack config?", prompt_suffix=" "):
            return
    else:
        if not click.confirm("(optional) Configure Slack integration?",
                             prompt_suffix=" "):
            return

    click.echo(get_slack_text())
    token = click.prompt("Slack token", type=click.STRING,
                         hide_input=True).strip()
    channel = click.prompt("Slack channel",
                           type=click.STRING,
                           prompt_suffix=": #").strip()
    settings.set_slack_token(token)
    settings.set_slack_channel(channel)

    try:
        auth_query = SlackAuthCheck()
        auth_query.execute()  # pylint: disable=no-value-for-parameter
        channel_query = SlackChannelListQuery()
        channel_query.execute()
        if channel not in channel_query.channels:
            raise click.ClickException("Channel does not exist")
    except Exception as exception:
        settings.reset_slack()
        raise exception

    click.secho("✓ Slack, hello {}! 🔌✨".format(auth_query.user),
                bold=True)
Example #4
0
 def _get_payload(self):
     settings = Settings()
     payload = {
         "token": settings.get_slack_token(),
         "channel": settings.get_slack_channel(),
         "text": self.message,
         "as_user": True,
         "link_names": True,
     }
     if self.reply_to is not None:
         payload.update({"thread_ts": self.reply_to.ts})
     return payload
Example #5
0
def test_with_specific_date(mock_get_report, runner):
    Settings().reset_slack()
    _add_graphql_response(
        {
            "data": {
                "viewer": {
                    "contributionsCollection": {
                        "pullRequestContributions": {"edges": []},
                        "pullRequestReviewContributions": {"edges": []},
                    }
                }
            }
        }
    )

    result = runner.invoke(cli.main, ["scrum", "report", "--date", "2019-06-05"], input="\n".join(["n\n"]))

    assert result.exit_code == ExitCode.NO_ERROR.value
    report_settings = ScrumReportSettings()
    assert result.output == (
        "Tips:\n"
        "Рђб To customize report template, edit `{}`\n"
        "Рђб Begin line with an extra <space> to indent it\n"
        "\n"
        "GitHub's cheat sheet ­ЪўЈ:\n"
        "Рђб Sorry, nothing from GitHub may be you can ask your mum? ­ЪциРђЇ\n"
        "\n"
        "Report of 2019-06-05\n"
        "Copy to clipboard? [y/N] n\n"
        "\n"
    ).format(report_settings.get_path())
Example #6
0
def branch_list(ctx):  # pylint: disable=unused-argument
    """
    List your branches
    """
    query = BranchListQuery(emails=Settings().get_emails())
    query.execute()
    query.print()
Example #7
0
def get_welcome_text():
    """
    Return Welcome text
    """
    settings = Settings()
    return r"""                   _ _
 _   _  ___   __ _(_) |_ 
| | | |/ _ \ / _` | | __|
| |_| | (_) | (_| | | |_ 
 \__, |\___/ \__, |_|\__|
 |___/       |___/       

Welcome to yogit!

Configuration is stored here `{}`,
and is not encrypted, only use yogit on your personal computer.
""".format(settings.get_path())
Example #8
0
def branch_list(ctx, dangling):  # pylint: disable=unused-argument
    """
    List your branches
    """
    query = BranchListQuery(emails=Settings().get_github_emails(),
                            is_dangling=dangling)
    query.execute()  # pylint: disable=no-value-for-parameter
    query.print()
Example #9
0
def assert_empty_settings():
    settings = Settings()
    assert settings.get_github_token() == ""
    assert settings.get_github_login() == ""
    assert settings.get_github_emails() == []
    assert settings.get_slack_token() == ""
    assert settings.get_slack_channel() == ""
Example #10
0
def test_setup_ok(runner):
    _add_graphql_response(200, {"data": {"viewer": {"login": "******"}}})
    _add_rest_response("/user/emails", 200, [{
        "email": "email1"
    }, {
        "email": "email2"
    }, {
        "email": "email3"
    }])
    result = runner.invoke(cli.main, ["account", "setup"],
                           input="   <token>   ")
    assert result.exit_code == ExitCode.NO_ERROR.value
    assert result.output == get_welcome_text() + ("\nGitHub token: \n"
                                                  "Hello user1!\n")
    settings = Settings()
    assert settings.get_token() == "<token>"
    assert settings.get_login() == "user1"
    assert settings.get_emails() == ["email1", "email2", "email3"]
Example #11
0
def prepare(statement, variables, extra_data={}):
    """
    Set variable in statement and return the prepared statement
    """
    template = Template(statement)
    data = extra_data.copy()
    for variable in variables:
        if variable == S.LOGIN_VARIABLE:
            data[variable] = Settings().get_github_login()
        elif variable == S.TODAY_VARIABLE:
            data[variable] = today_earliest_str()
    return template.safe_substitute(data)
Example #12
0
def test_setup_ok(runner):
    _add_graphql_response(200, {"data": {"viewer": {"login": "******"}}})
    _add_rest_response("/user/emails", 200, [{
        "email": "email1"
    }, {
        "email": "email2"
    }, {
        "email": "email3"
    }])
    _add_post_slack_api_response(SLACK_AUTH_CHECK_ENDPOINT, {
        "ok": True,
        "user": "******"
    })
    _add_get_slack_api_response(SLACK_CHANNEL_LIST_ENDPOINT, {
        "ok": True,
        "channels": [{
            "name": "slack_channel"
        }]
    })
    result = runner.invoke(
        cli.main,
        ["account", "setup"],
        input="\n".join([
            "   github_token   ", "y", "   slack_token   ",
            "   slack_channel   "
        ]),
    )
    assert result.exit_code == ExitCode.NO_ERROR.value
    assert result.output == "\n".join([
        get_welcome_text(),
        get_github_text(),
        "GitHub token: ",
        "✓ GitHub, hello user1! 💕✨",
        "(optional) Configure Slack integration? [y/N] y",
        get_slack_text(),
        "Slack token: ",
        "Slack channel: #   slack_channel   ",
        "✓ Slack, hello user1! 🔌✨",
        "✓ Done, you can safely rerun this command at any time!\n",
    ])

    settings = Settings()
    assert settings.get_github_token() == "github_token"
    assert settings.get_github_login() == "user1"
    assert settings.get_github_emails() == ["email1", "email2", "email3"]
    assert settings.get_slack_token() == "slack_token"
    assert settings.get_slack_channel() == "slack_channel"
Example #13
0
def test_report_github_error(mock_compute_date, mock_query, mock_get_report, runner):
    Settings().reset_slack()
    result = runner.invoke(cli.main, ["scrum", "report"], input="\n".join(["n\n"]))
    report_settings = ScrumReportSettings()

    assert result.exit_code == ExitCode.NO_ERROR.value
    assert result.output == (
        "Tips:\n"
        "Рђб To customize report template, edit `{}`\n"
        "Рђб Begin line with an extra <space> to indent it\n"
        "\n"
        "GitHub's cheat sheet ­ЪўЈ:\n"
        "Рђб Sorry, nothing from GitHub may be you can ask your mum? ­ЪциРђЇ\n"
        "\n"
        "Report of 2019-08-20\n"
        "Copy to clipboard? [y/N] n\n"
        "\n"
    ).format(report_settings.get_path())
Example #14
0
def fill_settings():
    settings = Settings()
    settings.set_emails(
        ["*****@*****.**", "*****@*****.**", "*****@*****.**"])
    settings.set_login("user1")
    settings.set_token("<token>")
Example #15
0
def test_set_get_reset_settings():
    settings = Settings()
    settings.set_github_token("github_token")
    settings.set_github_login("github_login")
    settings.set_github_emails(
        ["github_email1", "github_email2", "github_email3"])

    assert settings.is_github_valid()
    assert not settings.is_slack_valid()
    assert settings.get_github_token() == "github_token"
    assert settings.get_github_login() == "github_login"
    assert settings.get_github_emails() == [
        "github_email1", "github_email2", "github_email3"
    ]

    settings.set_slack_token("slack_token")
    settings.set_slack_channel("slack_channel")

    assert settings.is_github_valid()
    assert settings.is_slack_valid()
    assert settings.get_slack_token() == "slack_token"
    assert settings.get_slack_channel() == "slack_channel"

    settings.reset_slack()
    assert not settings.is_slack_valid()
    settings.reset_github()
    assert not settings.is_github_valid()
    assert_empty_settings()
Example #16
0
def test_empty_settings():
    settings = Settings()
    assert not settings.is_github_valid()
    assert not settings.is_slack_valid()
    assert_empty_settings()
Example #17
0
def _get_authorization():
    """
    Craft Authorization HTTP header
    """
    token = Settings().get_token()
    return "token {}".format(token)
Example #18
0
 def __init__(self):
     super().__init__("post", SLACK_AUTH_CHECK_ENDPOINT)
     settings = Settings()
     self.user = None
     self.payload = {"token": settings.get_slack_token()}
Example #19
0
def fill_settings():
    settings = Settings()
    settings.set_github_emails(
        ["*****@*****.**", "*****@*****.**", "*****@*****.**"])
    settings.set_github_login("user1")
    settings.set_github_token("github_token")
    settings.set_slack_token("slack_token")
    settings.set_slack_channel("slack_channel")
Example #20
0
def _setup_github():
    settings = Settings()

    if settings.is_github_valid():
        if not click.confirm("Reset GitHub config?", prompt_suffix=" "):
            return

    click.echo(get_github_text())
    token = click.prompt("GitHub token", type=click.STRING,
                         hide_input=True).strip()
    settings.set_github_token(token)

    try:
        login_query = LoginQuery()
        login_query.execute()  # pylint: disable=no-value-for-parameter
        login = login_query.get_login()

        email_query = EmailQuery()
        email_query.execute()  # pylint: disable=no-value-for-parameter
    except Exception as exception:
        settings.reset_github()
        raise exception

    settings.set_github_login(login)
    settings.set_github_emails(email_query.get_emails())

    click.secho("✓ GitHub, hello {}! 💕✨".format(login), bold=True)
Example #21
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)
Example #22
0
 def wrapper(self, *args, **kwargs):
     # pylint: disable=missing-docstring
     if not Settings().is_valid():
         raise click.ClickException(
             "Account required, please `yogit account setup` first.")
     func(self, *args, **kwargs)
Example #23
0
def assert_empty_settings():
    settings = Settings()
    assert settings.get_token() == ""
    assert settings.get_login() == ""
    assert settings.get_emails() == []