Skip to content

Commit

Permalink
Better error message when API token is missing
Browse files Browse the repository at this point in the history
Get the API token from the `--api-token` command-line option, with the
option of setting it from the TOGGL_API_TOKEN environment variable
using the `envvar` feature from Click.

Refs: #14
  • Loading branch information
zmoog committed Apr 4, 2023
1 parent 73f189d commit e8663b4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 17 deletions.
2 changes: 1 addition & 1 deletion toggl_track/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .cli import cli

if __name__ == "__main__":
cli()
auto_envvar_prefix="TOGGL"
23 changes: 16 additions & 7 deletions toggl_track/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,19 @@ def as_str(reference_date: dt.datetime = now) -> str:
"--json-root",
default=None,
)
@click.option(
"--api-token",
required=True,
envvar="TOGGL_API_TOKEN",
help="Toggl Track API token. Can also be set using the TOGGL_API_TOKEN environment variable.",
)
@click.pass_context
def cli(ctx: click.Context, format: str, json_root: str):
def cli(ctx: click.Context, format: str, json_root: str, api_token: str):
"CLI tool and Python library to access Toggl Track https://toggl.com/track/"
ctx.ensure_object(dict)
ctx.obj['format'] = format
ctx.obj['json_root'] = json_root
ctx.obj['api_token'] = api_token

@cli.group()
@click.option(
Expand Down Expand Up @@ -73,7 +80,7 @@ def entries(ctx: click.Context, description: List[str], project_id: List[int]):
def list_entries(ctx: click.Context, start_date: dt.datetime, end_date: dt.datetime):
"""Returns a list of the latest time entries (default: last 24 hours)"""

client = TimeEntries.from_environment()
client = TimeEntries(ctx.obj['api_token'])

click.echo(
render(
Expand Down Expand Up @@ -106,14 +113,16 @@ def list_entries(ctx: click.Context, start_date: dt.datetime, end_date: dt.datet
def group_by_entries(ctx: click.Context, start_date: dt.datetime, end_date: dt.datetime, field: str = "tags"):
"""Returns a list of time entries grouped by a field"""

client = TimeEntries.from_environment()
client = TimeEntries(ctx.obj['api_token'])

result = TimeEntriesGroupByResult(
client.list(start_date, end_date, project_ids=ctx.obj['project_id'], description=ctx.obj['description']),
key_func=GroupByCriterion(field)
)

click.echo(
render(
TimeEntriesGroupByResult(
client.list(start_date, end_date, project_ids=ctx.obj['project_id'], description=ctx.obj['description']),
key_func=GroupByCriterion(field)
),
result,
format=ctx.obj['format'],
json_root=ctx.obj['json_root'],
),
Expand Down
18 changes: 9 additions & 9 deletions toggl_track/toggl.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ class TimeEntries(object):
def __init__(self, api_token: str) -> None:
self.api_token = api_token

@classmethod
def from_environment(cls) -> "TimeEntries":
"""Creates a new `TimeEntries` instance from the `TOGGL_API_TOKEN` environment variable."""
if "TOGGL_API_TOKEN" not in os.environ:
raise Exception(
"TOGGL_API_TOKEN environment variable not found. "
"Please set it to your Toggl Track API token."
)
return cls(api_token=os.environ["TOGGL_API_TOKEN"])
# @classmethod
# def from_environment(cls) -> "TimeEntries":
# """Creates a new `TimeEntries` instance from the `TOGGL_API_TOKEN` environment variable."""
# if "TOGGL_API_TOKEN" not in os.environ:
# raise Exception(
# "TOGGL_API_TOKEN environment variable not found. "
# "Please set it to your Toggl Track API token."
# )
# return cls(api_token=os.environ["TOGGL_API_TOKEN"])

def list(self, start_date: datetime, end_date: datetime, description: str = None, project_ids: List[int] = []) -> Iterator[TimeEntry]:
"""Fetches the time entries between `start_date` and `end_date` dates.
Expand Down

0 comments on commit e8663b4

Please sign in to comment.