Skip to content

Commit

Permalink
Code cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrik-corneliusson committed Oct 14, 2021
1 parent 92e0a04 commit 2ab7a16
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 31 deletions.
8 changes: 4 additions & 4 deletions click_web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def _get_output_folder():


def create_click_web_app(module, command: click.BaseCommand):
'''
"""
Create a Flask app that wraps a click command. (Call once)
:param module: the module that contains the click command, needed to get the path to the script.
Expand All @@ -46,7 +46,7 @@ def create_click_web_app(module, command: click.BaseCommand):
app = create_click_web_app(a_click_script, a_click_script.a_group_or_command)
'''
"""
global _flask_app, logger
assert _flask_app is None, "Flask App already created."

Expand All @@ -73,12 +73,12 @@ def create_click_web_app(module, command: click.BaseCommand):


def _register(module, command: click.BaseCommand):
'''
"""
:param module: the module that contains the command, needed to get the path to the script.
:param command: The actual click root command, needed to be able to read the command tree and arguments
in order to generate the index page and the html forms
'''
"""
global click_root_cmd, script_file
script_file = str(Path(module.__file__).absolute())
click_root_cmd = command
21 changes: 9 additions & 12 deletions click_web/resources/cmd_exec.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import traceback
from pathlib import Path
from typing import List
from typing import List, Union

from flask import Response, request
from werkzeug.utils import secure_filename

import click_web

from ..web_click_types import PasswordParamType
from .input_fields import FieldId

logger = None
logger: Union[logging.Logger, None] = None

HTML_HEAD = '''<!doctype html>
<html lang="en">
Expand All @@ -32,6 +32,7 @@
class Executor:
def __init__(self):
self.returncode = None
self._command_line = None

def exec(self, command_path):
"""
Expand Down Expand Up @@ -112,8 +113,7 @@ def _create_result_footer(self):
# important yield this block as one string so it pushed to client in one go.
# This is so the whole block can be treated as html if JS frontend.
to_download = self._command_line.get_download_field_infos()
lines = []
lines.append('<!-- CLICK_WEB START FOOTER -->')
lines = ['<!-- CLICK_WEB START FOOTER -->']
if to_download:
lines.append('<b>Result files:</b><br>')
for fi in to_download:
Expand Down Expand Up @@ -193,7 +193,7 @@ def __init__(self, command_line: CommandLine):
# important to sort them so they will be in expected order on command line
self.field_infos = list(sorted(field_infos))

def add_command_args(self, command_index):
def add_command_args(self, command_index: int):
"""
Convert the post request into a list of command line arguments
Expand Down Expand Up @@ -227,11 +227,9 @@ def add_command_args(self, command_index):
# treat each line we get from text area as a separate argument.
for value in arg_values:
values = value.splitlines()
logger.info(f'variadic arguments, split into: "{values}"')
for val in values:
self.command_line.append(val, secret=fi.param.form_type == 'password')
else:
logger.info(f'arg_value: "{arg_values}"')
for val in arg_values:
self.command_line.append(val, secret=fi.param.form_type == 'password')

Expand Down Expand Up @@ -325,7 +323,7 @@ def __str__(self):
return str(self.param)

def __lt__(self, other):
"Make class sortable"
# Make class sortable
return (self.param.command_index, self.param.param_index) < \
(other.param.command_index, other.param.param_index)

Expand All @@ -347,6 +345,7 @@ def __init__(self, fimeta):
self.mode = self.param.click_type.split('[')[1][:-1]
self.generate_download_link = True if 'w' in self.mode else False
self.link_name = f'{self.cmd_opt}.out'
self.file_path = None

logger.info(f'File mode for {self.key} is {self.mode}')

Expand Down Expand Up @@ -379,9 +378,7 @@ def save(self):
file.save(filename)

def __str__(self):

res = [super().__str__()]
res.append(f'file_path: {self.file_path}')
res = [super().__str__(), f'file_path: {self.file_path}']
return ', '.join(res)


Expand Down
20 changes: 9 additions & 11 deletions click_web/resources/cmd_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get_form_for(command_path: str):
command_path=command_path)


def _get_commands_by_path(command_path: str) -> Tuple[click.Context, click.Command]:
def _get_commands_by_path(command_path: str) -> List[Tuple[click.Context, click.Command]]:
"""
Take a (slash separated) string and generate (context, command) for each level.
:param command_path: "some_group/a_command"
Expand All @@ -32,7 +32,7 @@ def _get_commands_by_path(command_path: str) -> Tuple[click.Context, click.Comma
command_name, *command_path_items = command_path_items
command = click_web.click_root_cmd
if command.name != command_name:
raise CommandNotFound('Failed to find root command {}. There is a root commande named:{}'
raise CommandNotFound('Failed to find root command {}. There is a root command named:{}'
.format(command_name, command.name))
result = []
with click.Context(command, info_name=command, parent=None) as ctx:
Expand Down Expand Up @@ -79,7 +79,7 @@ def _process_help(help_text):
:param help_text: str
:return: A html formatted help string.
"""
help = []
help_ = []
in_pre = False
html_help = ''
if not help_text:
Expand All @@ -92,20 +92,18 @@ def _process_help(help_text):
if in_pre and not line.strip():
# end of code block
in_pre = False
html_help += '\n'.join(help)
help = []
help.append('</pre>')
html_help += '\n'.join(help_)
help_ = ['</pre>']
continue
elif line.strip() == '\b':
# start of code block
in_pre = True
html_help += '<br>\n'.join(help)
help = []
help.append('<pre>')
html_help += '<br>\n'.join(help_)
help_ = ['<pre>']
continue
help.append(escape(line))
help_.append(escape(line))
except StopIteration:
break

html_help += '\n'.join(help) if in_pre else '<br>\n'.join(help)
html_help += '\n'.join(help_) if in_pre else '<br>\n'.join(help_)
return html_help
7 changes: 4 additions & 3 deletions click_web/resources/index.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from collections import OrderedDict
from typing import Union

import click
from flask import render_template
Expand All @@ -11,11 +12,11 @@ def index():
return render_template('show_tree.html.j2', ctx=ctx, tree=_click_to_tree(ctx, click_web.click_root_cmd))


def _click_to_tree(ctx: click.Context, node: click.BaseCommand, ancestors=[]):
'''
def _click_to_tree(ctx: click.Context, node: Union[click.Command, click.MultiCommand], ancestors=[]):
"""
Convert a click root command to a tree of dicts and lists
:return: a json like tree
'''
"""
res_childs = []
res = OrderedDict()
res['is_group'] = isinstance(node, click.core.MultiCommand)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_request_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import flask
import pytest

from click_web.resources.cmd_exec import CommandLine, FormToCommandLineBuilder
from click_web.resources.cmd_exec import CommandLine

app = flask.Flask(__name__)

Expand Down

0 comments on commit 2ab7a16

Please sign in to comment.