readwebform 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- readwebform/__init__.py +63 -0
- readwebform/__main__.py +10 -0
- readwebform/api.py +335 -0
- readwebform/browser.py +115 -0
- readwebform/cli.py +267 -0
- readwebform/core.py +241 -0
- readwebform/forms.py +408 -0
- readwebform/multipart.py +399 -0
- readwebform/output.py +171 -0
- readwebform/parser.py +285 -0
- readwebform/py.typed +0 -0
- readwebform/server.py +690 -0
- readwebform-0.4.0.dist-info/METADATA +710 -0
- readwebform-0.4.0.dist-info/RECORD +18 -0
- readwebform-0.4.0.dist-info/WHEEL +5 -0
- readwebform-0.4.0.dist-info/entry_points.txt +2 -0
- readwebform-0.4.0.dist-info/licenses/LICENSE +21 -0
- readwebform-0.4.0.dist-info/top_level.txt +1 -0
readwebform/cli.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Command-line interface for readwebform.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import math
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .multipart import parse_size_limit
|
|
11
|
+
from .output import DEFAULT_ENV_PREFIX, is_valid_var_name
|
|
12
|
+
|
|
13
|
+
EXIT_INVALID_ARGUMENT = 8
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _ArgumentParser(argparse.ArgumentParser):
|
|
17
|
+
"""ArgumentParser whose usage errors exit with the documented code 8."""
|
|
18
|
+
|
|
19
|
+
def error(self, message):
|
|
20
|
+
self.print_usage(sys.stderr)
|
|
21
|
+
self.exit(EXIT_INVALID_ARGUMENT, f'{self.prog}: error: {message}\n')
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ReadWebFormArgumentParser:
|
|
25
|
+
"""Custom argument parser for readwebform."""
|
|
26
|
+
|
|
27
|
+
def __init__(self):
|
|
28
|
+
self.parser = _ArgumentParser(
|
|
29
|
+
prog='readwebform',
|
|
30
|
+
description='Gather structured user input through a temporary web form',
|
|
31
|
+
epilog='See https://github.com/vlasky/readwebform for documentation and examples.'
|
|
32
|
+
)
|
|
33
|
+
self._setup_arguments()
|
|
34
|
+
|
|
35
|
+
def _setup_arguments(self):
|
|
36
|
+
"""Configure all command-line arguments."""
|
|
37
|
+
self.parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
|
|
38
|
+
|
|
39
|
+
input_group = self.parser.add_argument_group('input sources (mutually exclusive)')
|
|
40
|
+
input_group.add_argument(
|
|
41
|
+
'--html',
|
|
42
|
+
metavar='<string>',
|
|
43
|
+
help='Inline HTML fragment or document containing one <form> element'
|
|
44
|
+
)
|
|
45
|
+
input_group.add_argument(
|
|
46
|
+
'--htmlfile',
|
|
47
|
+
metavar='<path>',
|
|
48
|
+
help='Path to an HTML file containing a form'
|
|
49
|
+
)
|
|
50
|
+
input_group.add_argument(
|
|
51
|
+
'--field',
|
|
52
|
+
action='append',
|
|
53
|
+
metavar='<spec>',
|
|
54
|
+
help='Declaratively define a form field (format: name:type[:label][:options]). '
|
|
55
|
+
'May be given multiple times.'
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
presentation_group = self.parser.add_argument_group('presentation options')
|
|
59
|
+
presentation_group.add_argument(
|
|
60
|
+
'--title',
|
|
61
|
+
metavar='<string>',
|
|
62
|
+
help='Page title shown above the form and in the browser tab'
|
|
63
|
+
)
|
|
64
|
+
presentation_group.add_argument(
|
|
65
|
+
'--text',
|
|
66
|
+
metavar='<string>',
|
|
67
|
+
help='Instructional text shown above the form'
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
server_group = self.parser.add_argument_group('server configuration')
|
|
71
|
+
server_group.add_argument(
|
|
72
|
+
'--host',
|
|
73
|
+
metavar='<ip>',
|
|
74
|
+
default='127.0.0.1',
|
|
75
|
+
help='IPv4 or IPv6 address to bind to (default: 127.0.0.1)'
|
|
76
|
+
)
|
|
77
|
+
server_group.add_argument(
|
|
78
|
+
'--port',
|
|
79
|
+
type=int,
|
|
80
|
+
metavar='<int>',
|
|
81
|
+
help='TCP port (default: auto-select a free port)'
|
|
82
|
+
)
|
|
83
|
+
server_group.add_argument(
|
|
84
|
+
'--url-host',
|
|
85
|
+
metavar='<host>',
|
|
86
|
+
help='Host name or address to put in the printed URL (default: the bind address, '
|
|
87
|
+
'or a best-effort guess of this machine\'s address when binding to all interfaces)'
|
|
88
|
+
)
|
|
89
|
+
server_group.add_argument(
|
|
90
|
+
'--cert',
|
|
91
|
+
metavar='<path>',
|
|
92
|
+
help='Path to SSL certificate file (PEM format) for HTTPS'
|
|
93
|
+
)
|
|
94
|
+
server_group.add_argument(
|
|
95
|
+
'--key',
|
|
96
|
+
metavar='<path>',
|
|
97
|
+
help='Path to SSL private key file (PEM format) for HTTPS'
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
upload_group = self.parser.add_argument_group('upload options')
|
|
101
|
+
upload_group.add_argument(
|
|
102
|
+
'--max-file-size',
|
|
103
|
+
metavar='<limit>',
|
|
104
|
+
help='Maximum individual upload size (e.g. 5M, 200K)'
|
|
105
|
+
)
|
|
106
|
+
upload_group.add_argument(
|
|
107
|
+
'--max-total-size',
|
|
108
|
+
metavar='<limit>',
|
|
109
|
+
help='Maximum total request size (e.g. 20M, 1G; default: 20M)'
|
|
110
|
+
)
|
|
111
|
+
upload_group.add_argument(
|
|
112
|
+
'--upload-dir',
|
|
113
|
+
metavar='<path>',
|
|
114
|
+
help='Directory to save uploaded files in (default: a new temporary directory)'
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
timeout_group = self.parser.add_argument_group('timeout configuration')
|
|
118
|
+
timeout_group.add_argument(
|
|
119
|
+
'--timeout',
|
|
120
|
+
type=float,
|
|
121
|
+
metavar='<seconds>',
|
|
122
|
+
default=300,
|
|
123
|
+
help='Max time to wait for submission in seconds (default: 300)'
|
|
124
|
+
)
|
|
125
|
+
timeout_group.add_argument(
|
|
126
|
+
'--reset-timeout-on-error',
|
|
127
|
+
type=self._str_to_bool,
|
|
128
|
+
metavar='<bool>',
|
|
129
|
+
default=True,
|
|
130
|
+
help='Restart the timeout after a recoverable error (default: true)'
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
output_group = self.parser.add_argument_group('output format')
|
|
134
|
+
output_group.add_argument(
|
|
135
|
+
'--json',
|
|
136
|
+
action='store_true',
|
|
137
|
+
default=True,
|
|
138
|
+
help='Output result as JSON on stdout (default; accepted for compatibility)'
|
|
139
|
+
)
|
|
140
|
+
output_group.add_argument(
|
|
141
|
+
'--envfile',
|
|
142
|
+
metavar='<path>',
|
|
143
|
+
help='Write sanitized export statements to this file (mode 0600)'
|
|
144
|
+
)
|
|
145
|
+
output_group.add_argument(
|
|
146
|
+
'--print-env',
|
|
147
|
+
action='store_true',
|
|
148
|
+
help='Print sanitized export statements to stdout instead of JSON'
|
|
149
|
+
)
|
|
150
|
+
output_group.add_argument(
|
|
151
|
+
'--env-prefix',
|
|
152
|
+
metavar='<prefix>',
|
|
153
|
+
default=DEFAULT_ENV_PREFIX,
|
|
154
|
+
help=f'Prefix for environment variable names (default: {DEFAULT_ENV_PREFIX})'
|
|
155
|
+
)
|
|
156
|
+
output_group.add_argument(
|
|
157
|
+
'--url-file',
|
|
158
|
+
metavar='<path>',
|
|
159
|
+
help='Write the form URL to this file once the server is listening'
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
browser_group = self.parser.add_argument_group('browser options')
|
|
163
|
+
browser_group.add_argument(
|
|
164
|
+
'--launch-browser',
|
|
165
|
+
nargs='?',
|
|
166
|
+
const='',
|
|
167
|
+
metavar='<path>',
|
|
168
|
+
help='Open the form in a browser even when no desktop is detected, optionally '
|
|
169
|
+
'with a specific browser executable. By default the browser opens '
|
|
170
|
+
'automatically when a desktop is available (not in CI or over SSH).'
|
|
171
|
+
)
|
|
172
|
+
browser_group.add_argument(
|
|
173
|
+
'--no-launch-browser',
|
|
174
|
+
action='store_true',
|
|
175
|
+
help='Never open a browser; just print the URL'
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
form_group = self.parser.add_argument_group('form generation')
|
|
179
|
+
form_group.add_argument(
|
|
180
|
+
'--no-submit-button',
|
|
181
|
+
action='store_true',
|
|
182
|
+
help='Omit the automatic submit button in declarative mode'
|
|
183
|
+
)
|
|
184
|
+
form_group.add_argument(
|
|
185
|
+
'--submit-label',
|
|
186
|
+
metavar='<text>',
|
|
187
|
+
default='Submit',
|
|
188
|
+
help='Label for the submit button (default: Submit)'
|
|
189
|
+
)
|
|
190
|
+
form_group.add_argument(
|
|
191
|
+
'--no-cancel-button',
|
|
192
|
+
action='store_true',
|
|
193
|
+
help='Omit the cancel button in declarative mode'
|
|
194
|
+
)
|
|
195
|
+
form_group.add_argument(
|
|
196
|
+
'--cancel-label',
|
|
197
|
+
metavar='<text>',
|
|
198
|
+
default='Cancel',
|
|
199
|
+
help='Label for the cancel button (default: Cancel)'
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _str_to_bool(value: str) -> bool:
|
|
204
|
+
"""Convert a string to a boolean for --reset-timeout-on-error."""
|
|
205
|
+
if isinstance(value, bool):
|
|
206
|
+
return value
|
|
207
|
+
if value.lower() in ('yes', 'true', 't', 'y', '1'):
|
|
208
|
+
return True
|
|
209
|
+
if value.lower() in ('no', 'false', 'f', 'n', '0'):
|
|
210
|
+
return False
|
|
211
|
+
raise argparse.ArgumentTypeError(f'Boolean value expected, got: {value}')
|
|
212
|
+
|
|
213
|
+
def parse_args(self, args=None):
|
|
214
|
+
"""Parse command-line arguments and validate them."""
|
|
215
|
+
parsed = self.parser.parse_args(args)
|
|
216
|
+
self._validate_args(parsed)
|
|
217
|
+
return parsed
|
|
218
|
+
|
|
219
|
+
def _validate_args(self, args):
|
|
220
|
+
"""Validate argument combinations."""
|
|
221
|
+
input_sources = sum([
|
|
222
|
+
args.html is not None,
|
|
223
|
+
args.htmlfile is not None,
|
|
224
|
+
args.field is not None
|
|
225
|
+
])
|
|
226
|
+
if input_sources > 1:
|
|
227
|
+
self.parser.error('Only one input source allowed: --html, --htmlfile, or --field')
|
|
228
|
+
|
|
229
|
+
if not math.isfinite(args.timeout) or args.timeout <= 0:
|
|
230
|
+
self.parser.error('--timeout must be a positive, finite number of seconds')
|
|
231
|
+
|
|
232
|
+
if args.port is not None and (args.port < 1 or args.port > 65535):
|
|
233
|
+
self.parser.error('--port must be between 1 and 65535')
|
|
234
|
+
|
|
235
|
+
if args.launch_browser is not None and args.no_launch_browser:
|
|
236
|
+
self.parser.error('--launch-browser and --no-launch-browser are mutually exclusive')
|
|
237
|
+
|
|
238
|
+
if args.cert and not args.key:
|
|
239
|
+
self.parser.error('--cert requires --key')
|
|
240
|
+
if args.key and not args.cert:
|
|
241
|
+
self.parser.error('--key requires --cert')
|
|
242
|
+
|
|
243
|
+
for option in ('max_file_size', 'max_total_size'):
|
|
244
|
+
value = getattr(args, option)
|
|
245
|
+
if value is not None:
|
|
246
|
+
try:
|
|
247
|
+
parse_size_limit(value)
|
|
248
|
+
except ValueError:
|
|
249
|
+
flag = '--' + option.replace('_', '-')
|
|
250
|
+
self.parser.error(f'{flag}: invalid size {value!r} (use e.g. 5M, 200K, 1G, or bytes)')
|
|
251
|
+
|
|
252
|
+
if not is_valid_var_name(args.env_prefix + 'X'):
|
|
253
|
+
self.parser.error('--env-prefix must contain only letters, digits and underscores '
|
|
254
|
+
'and not start with a digit')
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def main():
|
|
258
|
+
"""Main entry point for the readwebform CLI."""
|
|
259
|
+
parser = ReadWebFormArgumentParser()
|
|
260
|
+
args = parser.parse_args()
|
|
261
|
+
|
|
262
|
+
from .core import run_readwebform
|
|
263
|
+
return run_readwebform(args)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
if __name__ == '__main__':
|
|
267
|
+
sys.exit(main())
|
readwebform/core.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core orchestration for readwebform: load, validate, serve, output.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import sys
|
|
7
|
+
import traceback
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from .browser import gui_available
|
|
11
|
+
from .forms import FieldSpec, generate_form_html
|
|
12
|
+
from .multipart import parse_size_limit
|
|
13
|
+
from .output import format_env_output, format_json_output, write_env_file
|
|
14
|
+
from .parser import inject_csrf_token, validate_html, wrap_html_fragment
|
|
15
|
+
from .server import FormServer
|
|
16
|
+
|
|
17
|
+
# Exit codes
|
|
18
|
+
EXIT_SUCCESS = 0
|
|
19
|
+
EXIT_INTERNAL_ERROR = 1
|
|
20
|
+
EXIT_INVALID_HTML = 2
|
|
21
|
+
EXIT_READ_ERROR = 3
|
|
22
|
+
EXIT_BROWSER_LAUNCH_ERROR = 4 # reserved: browser failures only warn
|
|
23
|
+
EXIT_TIMEOUT = 5
|
|
24
|
+
EXIT_UPLOAD_SIZE_EXCEEDED = 6 # reserved: oversized uploads are recoverable (HTTP 413)
|
|
25
|
+
EXIT_CANCELLED = 7
|
|
26
|
+
EXIT_INVALID_ARGUMENT = 8
|
|
27
|
+
EXIT_INTERRUPTED = 130
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class InputError(Exception):
|
|
31
|
+
"""A problem with the form input that maps to a specific exit code."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: str, exit_code: int):
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.exit_code = exit_code
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def run_readwebform(args) -> int:
|
|
39
|
+
"""
|
|
40
|
+
Main execution function for readwebform.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
args: Parsed command-line arguments
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
Exit code
|
|
47
|
+
"""
|
|
48
|
+
try:
|
|
49
|
+
try:
|
|
50
|
+
html = load_html(args)
|
|
51
|
+
except InputError as e:
|
|
52
|
+
print(f'Error: {e}', file=sys.stderr)
|
|
53
|
+
return e.exit_code
|
|
54
|
+
|
|
55
|
+
html = wrap_html_fragment(html, args.title, args.text)
|
|
56
|
+
|
|
57
|
+
warn_no_submit = not (args.field and not args.no_submit_button)
|
|
58
|
+
valid, error = validate_html(html, warn_no_submit=warn_no_submit)
|
|
59
|
+
if not valid:
|
|
60
|
+
print(f'Error: {error}', file=sys.stderr)
|
|
61
|
+
return EXIT_INVALID_HTML
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
max_file_size = parse_size_limit(args.max_file_size)
|
|
65
|
+
max_total_size = parse_size_limit(args.max_total_size)
|
|
66
|
+
except ValueError as e:
|
|
67
|
+
print(f'Error: Invalid size limit: {e}', file=sys.stderr)
|
|
68
|
+
return EXIT_INVALID_ARGUMENT
|
|
69
|
+
|
|
70
|
+
server = FormServer(
|
|
71
|
+
html='', # set after CSRF injection
|
|
72
|
+
host=args.host,
|
|
73
|
+
port=args.port,
|
|
74
|
+
max_file_size=max_file_size,
|
|
75
|
+
max_total_size=max_total_size,
|
|
76
|
+
timeout=args.timeout,
|
|
77
|
+
reset_timeout_on_error=args.reset_timeout_on_error,
|
|
78
|
+
cert_file=getattr(args, 'cert', None),
|
|
79
|
+
key_file=getattr(args, 'key', None),
|
|
80
|
+
upload_dir=getattr(args, 'upload_dir', None),
|
|
81
|
+
url_host=getattr(args, 'url_host', None),
|
|
82
|
+
)
|
|
83
|
+
server.html = inject_csrf_token(html, server.csrf_token, server.endpoint)
|
|
84
|
+
|
|
85
|
+
if args.host in ('0.0.0.0', '::'):
|
|
86
|
+
print('Warning: Binding to all interfaces. The form will be reachable from other machines.',
|
|
87
|
+
file=sys.stderr)
|
|
88
|
+
print(' Consider --host 127.0.0.1 for local-only access.', file=sys.stderr)
|
|
89
|
+
|
|
90
|
+
browser_path = resolve_browser_launch(args)
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
success, form_data, file_metadata, cancelled = server.serve(
|
|
94
|
+
launch_browser_path=browser_path,
|
|
95
|
+
url_file=getattr(args, 'url_file', None)
|
|
96
|
+
)
|
|
97
|
+
except KeyboardInterrupt:
|
|
98
|
+
_emit_failure(args, 'interrupted')
|
|
99
|
+
print('\nInterrupted by user', file=sys.stderr)
|
|
100
|
+
return EXIT_INTERRUPTED
|
|
101
|
+
|
|
102
|
+
if cancelled:
|
|
103
|
+
_emit_failure(args, 'cancelled')
|
|
104
|
+
print('Form submission cancelled by user', file=sys.stderr)
|
|
105
|
+
return EXIT_CANCELLED
|
|
106
|
+
|
|
107
|
+
if not success or form_data is None:
|
|
108
|
+
_emit_failure(args, 'timeout')
|
|
109
|
+
print('Error: Timeout waiting for submission', file=sys.stderr)
|
|
110
|
+
return EXIT_TIMEOUT
|
|
111
|
+
|
|
112
|
+
env_prefix = getattr(args, 'env_prefix', 'WEBFORM_')
|
|
113
|
+
if args.envfile:
|
|
114
|
+
write_env_file(args.envfile, form_data.fields, env_prefix, file_metadata)
|
|
115
|
+
if args.print_env:
|
|
116
|
+
print(format_env_output(form_data.fields, env_prefix, file_metadata))
|
|
117
|
+
else:
|
|
118
|
+
print(format_json_output(form_data.fields, file_metadata, success=True))
|
|
119
|
+
|
|
120
|
+
return EXIT_SUCCESS
|
|
121
|
+
|
|
122
|
+
except KeyboardInterrupt:
|
|
123
|
+
_emit_failure(args, 'interrupted')
|
|
124
|
+
print('\nInterrupted by user', file=sys.stderr)
|
|
125
|
+
return EXIT_INTERRUPTED
|
|
126
|
+
except Exception as e:
|
|
127
|
+
print(f'Internal error: {e}', file=sys.stderr)
|
|
128
|
+
traceback.print_exc(file=sys.stderr)
|
|
129
|
+
return EXIT_INTERNAL_ERROR
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def is_loopback_host(host: str) -> bool:
|
|
133
|
+
"""
|
|
134
|
+
True for 'localhost' and any loopback IP literal (127.0.0.0/8, ::1 in any
|
|
135
|
+
spelling). Other hostnames are treated as non-loopback without a DNS
|
|
136
|
+
lookup, so a name like 127.example.invalid does not count.
|
|
137
|
+
"""
|
|
138
|
+
if host == 'localhost':
|
|
139
|
+
return True
|
|
140
|
+
try:
|
|
141
|
+
return ipaddress.ip_address(host.strip('[]')).is_loopback
|
|
142
|
+
except ValueError:
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def resolve_browser_launch(args) -> Optional[str]:
|
|
147
|
+
"""
|
|
148
|
+
Decide whether, and with which browser, to open the form.
|
|
149
|
+
|
|
150
|
+
Returns None (do not launch), '' (system default browser) or a browser
|
|
151
|
+
executable path, following these rules in order:
|
|
152
|
+
|
|
153
|
+
1. ``--no-launch-browser``: never.
|
|
154
|
+
2. ``--launch-browser [path]``: always, with that browser.
|
|
155
|
+
3. Otherwise launch the default browser only when a desktop is detected
|
|
156
|
+
(see ``browser.gui_available``) AND the form is for this machine's
|
|
157
|
+
user: the host is a loopback address (a non-loopback host means the
|
|
158
|
+
URL is for someone else) and no ``--url-file`` was requested (which
|
|
159
|
+
means the caller is handling the URL itself).
|
|
160
|
+
"""
|
|
161
|
+
if getattr(args, 'no_launch_browser', False):
|
|
162
|
+
return None
|
|
163
|
+
if args.launch_browser is not None:
|
|
164
|
+
return args.launch_browser
|
|
165
|
+
if not is_loopback_host(args.host):
|
|
166
|
+
return None
|
|
167
|
+
if getattr(args, 'url_file', None):
|
|
168
|
+
return None
|
|
169
|
+
return '' if gui_available() else None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _emit_failure(args, error: str) -> None:
|
|
173
|
+
"""Print the JSON failure envelope unless env output was requested."""
|
|
174
|
+
if not args.print_env:
|
|
175
|
+
print(format_json_output({}, {}, success=False, error=error))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def load_html(args) -> str:
|
|
179
|
+
"""
|
|
180
|
+
Load HTML from the input source selected by the arguments.
|
|
181
|
+
|
|
182
|
+
Priority: --html, --htmlfile, --field, then stdin.
|
|
183
|
+
|
|
184
|
+
Raises:
|
|
185
|
+
InputError: If the input cannot be read or is invalid
|
|
186
|
+
"""
|
|
187
|
+
if args.html is not None:
|
|
188
|
+
return args.html
|
|
189
|
+
|
|
190
|
+
if args.htmlfile is not None:
|
|
191
|
+
try:
|
|
192
|
+
with open(args.htmlfile, encoding='utf-8') as f:
|
|
193
|
+
return f.read()
|
|
194
|
+
except FileNotFoundError as e:
|
|
195
|
+
raise InputError(f'File not found: {args.htmlfile}', EXIT_READ_ERROR) from e
|
|
196
|
+
except PermissionError as e:
|
|
197
|
+
raise InputError(f'Permission denied: {args.htmlfile}', EXIT_READ_ERROR) from e
|
|
198
|
+
except UnicodeDecodeError as e:
|
|
199
|
+
raise InputError(f'{args.htmlfile} is not valid UTF-8: {e}', EXIT_READ_ERROR) from e
|
|
200
|
+
except OSError as e:
|
|
201
|
+
raise InputError(f'Cannot read {args.htmlfile}: {e}', EXIT_READ_ERROR) from e
|
|
202
|
+
|
|
203
|
+
if args.field:
|
|
204
|
+
return generate_html_from_fields(
|
|
205
|
+
args.field,
|
|
206
|
+
args.no_submit_button,
|
|
207
|
+
getattr(args, 'no_cancel_button', False),
|
|
208
|
+
getattr(args, 'cancel_label', 'Cancel'),
|
|
209
|
+
getattr(args, 'submit_label', 'Submit'),
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
return read_stdin()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def generate_html_from_fields(field_specs: list, no_submit_button: bool,
|
|
216
|
+
no_cancel_button: bool = False,
|
|
217
|
+
cancel_label: str = 'Cancel',
|
|
218
|
+
submit_label: str = 'Submit') -> str:
|
|
219
|
+
"""
|
|
220
|
+
Generate form HTML from declarative field specification strings.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
InputError: If a field specification is invalid (exit code 2)
|
|
224
|
+
"""
|
|
225
|
+
fields = []
|
|
226
|
+
for spec in field_specs:
|
|
227
|
+
try:
|
|
228
|
+
fields.append(FieldSpec.parse(spec))
|
|
229
|
+
except ValueError as e:
|
|
230
|
+
raise InputError(str(e), EXIT_INVALID_HTML) from e
|
|
231
|
+
|
|
232
|
+
return generate_form_html(fields, add_submit_button=not no_submit_button,
|
|
233
|
+
add_cancel_button=not no_cancel_button, cancel_label=cancel_label,
|
|
234
|
+
submit_label=submit_label)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def read_stdin() -> str:
|
|
238
|
+
"""Read HTML from stdin."""
|
|
239
|
+
if sys.stdin.isatty():
|
|
240
|
+
print('Reading HTML from stdin (press Ctrl+D when done)...', file=sys.stderr)
|
|
241
|
+
return sys.stdin.read()
|