pivotalcli/commands/projects.py

72 lines
1.8 KiB
Python
Raw Normal View History

2018-04-03 10:56:07 +00:00
import sys
from typing import Dict
2018-07-22 09:45:15 +00:00
import base32_crockford as base32
2018-07-21 12:36:02 +00:00
import click
2018-04-03 10:56:07 +00:00
import tabulate
import api.projects
from config import Config
from util import require_login
2018-07-21 12:36:02 +00:00
from .cli import cli
2018-04-03 10:56:07 +00:00
2018-07-21 12:36:02 +00:00
@cli.group('projects', invoke_without_command=True)
@click.pass_context
2018-04-03 10:56:07 +00:00
@require_login
2018-07-21 12:36:02 +00:00
def projects(context: click.Context) -> None:
if context.invoked_subcommand is not None:
# click calls this function when a subcommand is
# invoked as well. In this case, do nothing.
return
projects_ = api.projects.get()
2018-07-22 09:45:15 +00:00
projects_.sort(key=lambda project_: project_['name'])
2018-04-03 10:56:07 +00:00
aliases: Dict[int, str] = {}
2018-07-22 09:45:15 +00:00
for alias_, alias_id in Config['project_aliases'].items():
aliases[int(alias_id)] = alias_
2018-04-03 10:56:07 +00:00
table = []
2018-07-22 09:45:15 +00:00
for project in sorted(projects_, key=lambda project_: project_['name']):
code = base32.encode(project['id'])
2019-02-05 13:29:33 +00:00
alias_ = aliases.get(project['id'], '')
2018-07-22 09:45:15 +00:00
table.append((code, project['name'], alias_))
2018-04-03 10:56:07 +00:00
print(tabulate.tabulate(table, headers=('Code', 'Name', 'Alias')))
2018-07-21 12:36:02 +00:00
@projects.group('alias')
def alias() -> None:
pass
@alias.command('add')
@click.argument('code')
@click.argument('name')
def alias_add(code: str, name: str) -> None:
2018-07-22 09:45:15 +00:00
project_id = base32.decode(code)
2018-07-21 12:36:02 +00:00
Config['project_aliases'][name] = str(project_id)
2018-04-03 10:56:07 +00:00
Config.write()
2018-07-21 12:36:02 +00:00
@alias.command('rm')
@click.argument('name')
def alias_rm(name: str) -> None:
del Config['project_aliases'][name]
2018-04-03 10:56:07 +00:00
Config.write()
2018-07-21 12:36:02 +00:00
@projects.command('info')
@click.argument('name')
def info(name: str) -> None:
2018-04-03 10:56:07 +00:00
try:
2018-07-21 12:36:02 +00:00
project_id = int(Config['project_aliases'][name])
2018-04-03 10:56:07 +00:00
except KeyError:
2018-07-21 12:36:02 +00:00
print(f'unknown alias {name}')
2018-04-03 10:56:07 +00:00
sys.exit(1)
project_info = api.projects.get_project(project_id)
2018-07-21 12:36:02 +00:00
print(tabulate.tabulate(project_info.items()))