From b7670b2292c9ee33fc3653ef521382812ce2758a Mon Sep 17 00:00:00 2001 From: a1fred Date: Fri, 3 Dec 2021 18:33:26 +0300 Subject: [PATCH] template upload need check --- carnival/cmd/transfer.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/carnival/cmd/transfer.py b/carnival/cmd/transfer.py index 789681b..62404e9 100644 --- a/carnival/cmd/transfer.py +++ b/carnival/cmd/transfer.py @@ -1,7 +1,10 @@ from io import BytesIO from typing import Any +from hashlib import sha1 -from carnival import Connection, Result, SshHost, Host +from colorama import Fore as F, Style as S # type: ignore + +from carnival import Connection, Result, SshHost, Host, cmd from carnival.hosts.local import localhost_connection from carnival.templates import render @@ -91,7 +94,7 @@ def put(c: Connection, local: str, remote: str, preserve_mode: bool = True) -> N t.put(local=local, remote=remote, preserve_mode=preserve_mode) -def put_template(c: Connection, template_path: str, remote: str, **context: Any) -> None: +def put_template(c: Connection, template_path: str, remote: str, **context: Any) -> bool: """ Отрендерить файл с помощью jinja-шаблонов и закачать на сервер См раздел templates. @@ -104,6 +107,29 @@ def put_template(c: Connection, template_path: str, remote: str, **context: Any) :param context: контекс для рендеринга jinja2 """ filestr = render(template_path=template_path, **context) + + shasum_exist = cmd.cli.is_cmd_exist(c, "shasum") + if shasum_exist is False: + print(f"{F.YELLOW}[WARN]{F.RESET} shasum is not found on remote, lazy uploading is not possible") + is_remote_exists = True + + if shasum_exist: + is_remote_exists = cmd.fs.is_file_exists(c, remote) + if is_remote_exists: + # Check hashed to prevent unneeded upload + filestr_hash = sha1(filestr.encode()).hexdigest() + remotehash_result = c.run(f"cat {remote} | shasum -a1", hide=True).stdout.strip(" -\t\n") + if filestr_hash == remotehash_result: + print(f"{S.BRIGHT}{template_path}{S.RESET_ALL}: {F.GREEN}not changed{F.RESET}") + return False + # TODO: c._c ;( t = Transfer(c._c) # type: ignore t.put(local=BytesIO(filestr.encode()), remote=remote, preserve_mode=False) + + if is_remote_exists: + print(f"{S.BRIGHT}{template_path}{S.RESET_ALL}: {F.YELLOW}updated{F.RESET}") + else: + print(f"{S.BRIGHT}{template_path}{S.RESET_ALL}: {F.YELLOW}created{F.RESET}") + + return True