Compare commits

...

2 Commits

Author SHA1 Message Date
6063c8b3b3
Escape HTML characters when printing the train
Since it's wrapped in a `<pre>`, I assume it's meant to be inserted into
HTML?
2025-06-02 17:24:04 -04:00
0b53c462de
Make validate_car raise exception on failure instead of returning 0 2025-06-02 17:23:45 -04:00

View File

@ -41,6 +41,7 @@ import curses
from signal import signal, SIGINT
import time # allowing the loop steps of train animation to be slowed
import string # for input validation
from html import escape
from inspect import cleandoc
from pathlib import Path
@ -90,6 +91,9 @@ default_car = [
r" \__/ \__/ \__/ \__/ ",
]
class CarError(Exception):
"""Error related validating a car."""
def print_help():
print(
cleandoc(
@ -206,9 +210,11 @@ def validate_car(car: list[str]):
while car_list[(len(car_list)-1)].strip() == "":
car_list.pop() # clear bottom
# len(choochoo_list) is the height of the train car, in number of rows.
if len(car_list) > max_y+1 or len(car_list) == 0:
return 0 # train car too tall or non-existant; skip it.
# len(car_list) is the height of the train car, in number of rows.
if len(car_list) > max_y+1:
raise CarError(f"Car is too tall ({len(car_list)} > {max_y + 1}).")
if len(car_list) == 0:
raise CarError(f"Car is empty.")
# vertically pad short cars with 1 space (lines will be lengthened later).
while len(car_list) < max_y:
@ -221,9 +227,9 @@ def validate_car(car: list[str]):
for idx,row in enumerate(car_list):
if len(row) > max_x+1: # check length of each row in .choochoo file.
return 0 # train car too long; skip it.
raise CarError(f"Car is too wide ({len(row)} > {max_x + 1}).")
elif "\t" in row or "\v" in row or "\f" in row or "\r" in row:
return 0 # skip if contains tabs, vert tabs, line feeds or carriage ret
raise CarError(f"Car contains illegal control characters.")
elif len(row) < longest_line:
padding = " "*(longest_line - len(row))
car_list[idx] += padding # add padding spaces.
@ -241,13 +247,12 @@ def print_all_cars():
continue # the train car was too tall; skip it.
car = validate_car(choochoo_list) # printing is only a DEBUG feature.
if car != 0:
print("")
print(fname + ":")
print("\n".join(car)) # print the car to stdout
print("")
print(fname + ":")
print("\n".join(car)) # print the car to stdout
except:
pass;
pass
def chuggachugga(stdscr: curses.window):
@ -306,11 +311,10 @@ for fname in glob.glob('/home/*/' + traincarFN):
continue # the train car was too tall; skip it.
car = validate_car(choochoo_list) # printing is only a DEBUG feature.
if car != 0:
cars.append(car) # start a list of lists (list of cars) here.
cars.append(car) # start a list of lists (list of cars) here.
except:
pass;
pass
while len(cars) < max_cars:
cars.append([*default_car]) # add copies of default cars if train too short
@ -336,7 +340,7 @@ train_str = "\n".join(train)
if print_train:
print("<pre>")
print(train_str)
print(escape(train_str))
print("</pre>")
sys.exit()