Skip to content
Snippets Groups Projects
Commit 01565a75 authored by Bruno Boiget's avatar Bruno Boiget
Browse files

Merge branch 'feature/317_list_messages' into 'develop'

Add new commands and help

See merge request !19
parents 8dcac0ee 32e00290
No related branches found
No related tags found
1 merge request!19Add new commands and help
Pipeline #418 failed
......@@ -4,6 +4,6 @@ __pycahe__/
build/
.cache/
dist/
tiramisu_cmdline_parser.py
tiramisu_cmdline_parser/
tiramisu_json_api/
zcli.spec
......@@ -19,7 +19,7 @@ then
else
git clone https://framagit.org/tiramisu/tiramisu-cmdline-parser.git
cd tiramisu-cmdline-parser
git checkout 708e623107c8f300462e54be186f2cfa2b327775
git checkout b67a1ec430ce8b5d3d285050fc8d2e99bbbb1d43
cd ..
fi
cp -Rpv tiramisu-cmdline-parser/tiramisu_cmdline_parser ${ZDIR}
......
......@@ -17,12 +17,10 @@ class ZcliConfig:
print("""Attention, le fichier de configuration de zephir-cli est inexistant !""")
url = input("Entrez l'adresse du serveur Zephir : ")
version = input("Entrez la version du zephir (defaut: 'v1') : ")
output = "yaml"
if not version:
version = "v1"
yaml_template = f"""url: {url}
version: {version}
output: {output}"""
version: {version}"""
with ZcliConfig.config_file.open("w", encoding ="utf-8") as fh:
fh.write(yaml_template)
......@@ -37,4 +35,3 @@ output: {output}"""
self.url = config.get('url')
self.version = config.get('version')
self.output = config.get('output')
......@@ -36,8 +36,7 @@ def api_v1():
@pytest.fixture
def create_zcli_config():
yaml_template = f"""url: {URL}
version: {VERSION}
output: json"""
version: {VERSION}"""
with CONFIG_FILE.open("w", encoding ="utf-8") as fh:
fh.write(yaml_template)
......@@ -58,8 +57,7 @@ def test_generate_config_file(monkeypatch):
assert zcliconf.version == "ma_version"
with CONFIG_FILE.open("r", encoding ="utf-8") as fh:
assert fh.read() == f"""url: mon_zephir.com
version: ma_version
output: yaml"""
version: ma_version"""
def test_message(create_zcli_config, api_v1):
......
......@@ -3,34 +3,123 @@
"""
import yaml
import sys
from zephir_client import remote_json_to_config, cmdline_factory, send, remove_token
from json import dumps
from pathlib import Path
from zephir_client import remote_json_to_config, cmdline_factory, send, remove_token, list_messages, authenticate
import config as zconf
zcliconf = zconf.ZcliConfig()
URL = zcliconf.url
VERSION = zcliconf.version
OUTPUT = 'yaml'
# get calling script base name
progname = Path(sys.argv[0]).parts[-1]
for arg in sys.argv:
if arg == '--json':
def main():
zcliconf = zconf.ZcliConfig()
URL = zcliconf.url
VERSION = zcliconf.version
OUTPUT = 'yaml'
list_msgs = False
if '--json' in sys.argv:
OUTPUT = 'json'
sys.argv.remove(arg)
sys.argv.remove('--json')
if len(sys.argv) == 1:
help()
if '-h' == sys.argv[1] or '--help' == sys.argv[1]:
if len(sys.argv) == 2 :
help()
if arg == '--login':
if 'logout' in sys.argv:
if '-h' in sys.argv or '--help' in sys.argv:
help()
remove_token()
sys.argv.remove(arg)
remote_config = remote_json_to_config(URL, VERSION)
config = cmdline_factory(remote_config)
for key in config.value.mandatory():
if not config.option(key).option.issymlinkoption():
text = input("* "+config.option(key).option.doc() + " : ")
if config.option(key).option.type() == 'integer':
config.option(key).value.set(int(text))
sys.argv.remove('logout')
print("Jeton d'authentification supprimé")
sys.exit(0)
if 'login' in sys.argv:
if '-h' in sys.argv or '--help' in sys.argv:
help()
remove_token()
user = None
if len(sys.argv) > 2 :
user = sys.argv[2]
authenticate(URL, user)
sys.exit(0)
if 'list' in sys.argv:
if '-h' in sys.argv or '--help' in sys.argv:
help()
list_msgs = True
start = None
if len(sys.argv) > 2 :
start = sys.argv[2]
sys.argv.remove(start)
sys.argv.remove('list')
remote_config = remote_json_to_config(URL, VERSION)
config = cmdline_factory(remote_config)
if list_msgs:
messages = list_messages(config, start)
if not messages:
print("Aucun résultat.")
elif OUTPUT == "yaml":
print("\n{}".format(yaml.dump(messages, default_flow_style=False)))
else:
config.option(key).value.set(text)
result = send(URL, VERSION, config)
if OUTPUT == "yaml":
print(yaml.dump(result, default_flow_style=False))
else:
print(result)
print(dumps(messages))
sys.exit(0)
# special case: no message name given
if 'message' in config.value.mandatory():
print(f"""\nNom de commande manquant. Vous devez spécifier une commande à exécuter.
Utiliser <{progname} list> pour lister les commandes disponibles.\n""")
sys.exit(0)
# ask for missing parameters
for key in config.value.mandatory():
if not config.option(key).option.issymlinkoption():
val_ok = False
while not val_ok:
text = input("* "+config.option(key).option.doc() + " : ")
try:
if config.option(key).option.type() == 'integer':
config.option(key).value.set(int(text))
else:
config.option(key).value.set(text)
val_ok = True
except Exception as err:
print('\nValeur invalide: {}\n'.format(err))
result = send(URL, VERSION, config)
if OUTPUT == "yaml":
print(yaml.dump(result, default_flow_style=False))
else:
print(result)
def help():
print(f"""
Client pour interroger un serveur Zéphir.
{progname} login [utilisateur]
Génère un token d'authentification.
{progname} logout
Supprime le token d'authentification.
{progname} list [recherche]
Liste les commandes disponibles commençant par <recherche>.
{progname} -h <commande>
Affiche l'aide d'une commande.
{progname} commande [paramètres]
Exécute la commande avec ses paramètres.
""")
sys.exit(0)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n Sortie utilisateur...")
sys.exit(0)
......@@ -4,7 +4,7 @@ import sys
import os
import getpass
from pathlib import Path
from json import loads, dumps
from json import dumps
import requests
import warnings
from urllib.request import urlopen, Request
......@@ -34,6 +34,14 @@ def enables_signature(config, message):
payload = {}
return payload
def list_messages(config, start=None):
"""lists all available messages from config
"""
messages = config.option('message').value.list()
if start is not None:
return [x for x in messages if x.startswith(start)]
else:
return messages
def send(url, version, config):
# check authentication
......@@ -71,11 +79,18 @@ def send(url, version, config):
sys.exit(1)
def authenticate(url):
print("\nVous n'êtes pas authentifié, veuillez saisir vos identifiants Zéphir\n")
def authenticate(url, user=None):
SSO_REALM = "zephir"
USERNAME = input("Utilisateur : ")
PASSWORD = getpass.getpass(prompt='Mot de passe : ', stream=None)
if user is not None:
USERNAME = user
else:
print("\nVous n'êtes pas authentifié, veuillez saisir vos identifiants Zéphir\n")
USERNAME = input("Utilisateur : ")
if sys.stdin.isatty():
PASSWORD = getpass.getpass(prompt='Mot de passe : ', stream=None)
else:
PASSWORD = sys.stdin.readline().rstrip()
auth_datas = {
"username": USERNAME,
......@@ -96,14 +111,7 @@ def authenticate(url):
def remove_token():
if os.path.exists(token_file):
os.remove(token_file)
def help():
print("""
Usage : zephir-client [-h] domain action
""")
sys.exit(1)
os.remove(token_file)
def remote_json_to_config(url, version):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment