Add method docs and comments

This commit is contained in:
Zachary Talis 2021-06-27 22:40:15 -04:00
parent ff7c757ff0
commit ae8ba9ac7c
8 changed files with 61 additions and 44 deletions

View file

@ -4,6 +4,7 @@
import subprocess, os
import scripts.utils.csv as util_csv
# Change and get current working directory, for compatibility with standalone scripts
os.chdir("scripts/")
cwd = os.getcwd()
@ -44,10 +45,10 @@ if len(config) == 0:
optionSetup()
generate()
# Set options (as defined earlier)
# Set options (functions as defined earlier)
options = [optionSetup, optionAddCategory, optionAddRun, optionQuit]
# Main loop
# Main loop and input handler
while True:
key = "tk_game_name"
config = util_csv.dictReaderFirstRow("../csv/config.csv")

View file

@ -7,17 +7,21 @@ divider = "----------"
print(f"\nWe'll ask for the name and rules of the new category.\n\n{divider}\n")
# All input handling
tk_category_name = input("Name: ").replace('"', "")
tk_category_rules = input("Rules: ").replace('"', "")
# Generate dashname (specifically for directory names)
tk_category_dashname = tk_category_name.replace(" ", "_").replace("%", "")
# Define category dictionary
categoryDict = {
"tk_category_dashname": tk_category_dashname,
"tk_category_name": tk_category_name,
"tk_category_rules": tk_category_rules,
}
# Write to csv
util_csv.dictWriter("../csv/categories.csv", categoryDict, "a")
print(

View file

@ -26,6 +26,7 @@ existingRuns = util_csv.dictReaderMultiRow("../csv/runs.csv", "tk_run_id")
for id in existingRuns:
tk_run_id = int(id) + 1
# Handle input of tk_run_runner and tk_run_verifier
tk_run_runner = input("Runner: ").replace('"', "")
tk_run_verifier = input("Verifier: ").replace('"', "")
@ -51,7 +52,6 @@ while not doneDurationInput:
doneCategoryInput = False
displayName = "tk_category_name"
while not doneCategoryInput:
print("\nCategory (input a number)")
@ -84,10 +84,12 @@ print(f"You picked - {categoriesNew[categoryInput][displayName]}\n")
## End of: Handle input of tk_run_category_dashname ##
# Handle input of tk_run_date, tk_run_description, and tk_run_link
tk_run_date = input("Date (format - MM/DD/YYYY): ").replace('"', "")
tk_run_description = input("Description: ").replace('"', "")
tk_run_link = input("Recording link (format - https://foo.bar): ")
# Define run dictionary
runDict = {
"tk_run_id": tk_run_id,
"tk_run_runner": tk_run_runner,
@ -99,6 +101,7 @@ runDict = {
"tk_run_link": tk_run_link,
}
# Write to csv
util_csv.dictWriter("../csv/runs.csv", runDict, "a")
print(

View file

@ -9,6 +9,7 @@ print(
f"\nWelcome to paceboard! Let's set up your leaderboard site :)\nWe'll save this info in csv/config.csv\n\n{divider}\n"
)
# All input handling
tk_game_name = input("Your game's name: ").replace('"', "")
tk_game_description = input("Description for your game: ").replace('"', "")
tk_url = input("URL of your site (format - foobar.com): ")
@ -16,6 +17,7 @@ tk_logo_alt = input(
"Description of your game's logo (this is used for alt-text): "
).replace('"', "")
# Define config dictionary
configDict = {
"tk_game_name": tk_game_name,
"tk_game_description": tk_game_description,
@ -23,6 +25,7 @@ configDict = {
"tk_logo_alt": tk_logo_alt,
}
# Write to csv
util_csv.dictWriter("../csv/config.csv", configDict)
print(f"\n{divider}\n\nPerfect, that's all for now! <3")

View file

@ -3,25 +3,6 @@
import csv
def readerWithFunction(filepath, function, arg=None):
"""Read from a csv and execute a function using each row. Return a sequential list of all values returned by the function.
filepath -- the path of the csv we're reading\n
function -- the function we're executing once per row\n
arg -- if the function takes an additional argument, we pass arg (default None)\n
"""
with open(filepath, newline="") as file:
reader = csv.reader(file, delimiter=",")
value = []
for row in reader:
if arg == None:
value.append(function(row))
else:
value.append(function(row, arg))
file.close()
return value
def dictWriter(filepath, dict, flag="w"):
"""Completely rewrite a csv using the values in a single dictionary.
@ -40,7 +21,7 @@ def dictWriter(filepath, dict, flag="w"):
def dictReaderFirstRow(filepath):
"""Get a dictionary of the first (non-header) row of values in a csv
"""Get a dictionary of the first (non-header) row of values in a csv.
filepath -- the path of the csv\n
"""
@ -57,7 +38,7 @@ def dictReaderFirstRow(filepath):
def dictReaderMultiRow(filepath, idName):
"""Get a dictionary of dictionaries of the (non-header) row of values in a csv
"""Get a dictionary of dictionaries of the (non-header) row of values in a csv.
filepath -- the path of the csv\n
idName -- the property in the header of the csv to use as each key of the resulting dictionary\n
@ -71,8 +52,27 @@ def dictReaderMultiRow(filepath, idName):
return dict
def readerWithFunction(filepath, function, arg=None):
"""Read from a csv and execute a function using each row. Return a sequential list of all values returned by the function. Not currently used, but included for convenience.
filepath -- the path of the csv we're reading\n
function -- the function we're executing once per row\n
arg -- if the function takes an additional argument, we pass arg (default None)\n
"""
with open(filepath, newline="") as file:
reader = csv.reader(file, delimiter=",")
value = []
for row in reader:
if arg == None:
value.append(function(row))
else:
value.append(function(row, arg))
file.close()
return value
def getIndexOfField(filepath, field):
"""Get the index (column number) of a field in a csv.
"""Get the index (column number) of a field in a csv. Not currently used, but included for convenience.
filepath -- the path of the csv we're searching\n
field -- the field string we're looking for\n

View file

@ -13,6 +13,7 @@ def generate(templatedir, destinationdir, templateFilename):
templateFilename -- the filename of the category template (always category.html)\n
"""
# Read runs, categories, and config csv files
runIdName = "tk_run_id"
categoryIdName = "tk_category_dashname"
runs = util_csv.dictReaderMultiRow("../csv/runs.csv", runIdName)
@ -21,25 +22,29 @@ def generate(templatedir, destinationdir, templateFilename):
for category in categories:
# Get proper directory
thisCategory = categories[category]
path = f"{destinationdir}/{thisCategory[categoryIdName]}"
currentDir = os.getcwd()
# Copy template to appropriate directory
os.makedirs(path, exist_ok=True)
shutil.copy(
f"{currentDir}/{templatedir}/{templateFilename}",
f"{currentDir}/{path}/index.html",
)
# Replace category tk placeholders with values
for key in thisCategory:
util_file.replaceTextInFile(f"{path}/index.html", key, thisCategory[key])
# Replace config tk placeholders with values
for key in config.keys():
util_file.replaceTextInFile(f"{path}/index.html", key, config[key])
## lk_leaderboard handler ##
# Find runsInCategory
runsInCategory = {}
for run in runs:
thisRun = runs[run]
@ -49,19 +54,20 @@ def generate(templatedir, destinationdir, templateFilename):
):
runsInCategory[thisRun["tk_run_id"]] = thisRun
# Find runDurationsInCategory by parsing runsInCategory values
runDurationsInCategory = {}
for run in runsInCategory:
thisRun = runsInCategory[run]
runDurationSplit = [
float(value) for value in thisRun["tk_run_duration"].split(":")
]
runDurationsInCategory[thisRun["tk_run_id"]] = datetime.timedelta(
hours=runDurationSplit[0],
minutes=runDurationSplit[1],
seconds=runDurationSplit[2],
)
# Find sortedRunsInCategory by sorting durations from runDurationsInCategory
sortedRunsInCategory = {
runId: runDuration
for runId, runDuration in sorted(
@ -69,6 +75,7 @@ def generate(templatedir, destinationdir, templateFilename):
)
}
# Find trimmedRunsInCategory by only including one run per runner from sortedRunsInCategory
trimmedRunsInCategory = {}
runnersRepresentedInCategory = []
for run in sortedRunsInCategory:
@ -78,10 +85,12 @@ def generate(templatedir, destinationdir, templateFilename):
trimmedRunsInCategory[thisRun["tk_run_id"]] = thisRun
runnersRepresentedInCategory.append(runner)
# Replace lk_leaderboard with category leaderboard table
place = 1
lk_leaderboard = '<table class="categoryBoard centerHoriz">'
for run in trimmedRunsInCategory:
# Define values for table
thisRun = trimmedRunsInCategory[run]
thisRunner = thisRun["tk_run_runner"]
thisRunId = thisRun["tk_run_id"]
@ -89,6 +98,7 @@ def generate(templatedir, destinationdir, templateFilename):
thisDuration = str(runDurationsInCategory[thisRunId])
thisDate = thisRun["tk_run_date"]
# Concatenate a row to the table
lk_leaderboard += f'<tr><th>{place}.</th><th>{thisRunner}</th><th><a href="{thisLink}">{thisDuration}</a></th><th>{thisDate}</th></tr>'
# Also handle replacing lk_run_place on run pages
@ -99,9 +109,9 @@ def generate(templatedir, destinationdir, templateFilename):
)
place += 1
lk_leaderboard += "</table>"
# Replace lk_leaderboard placeholder with table string
util_file.replaceTextInFile(
f"{path}/index.html", "lk_leaderboard", lk_leaderboard
)

View file

@ -13,28 +13,25 @@ def generate(templatedir, destinationdir, templateFilename):
templateFilename -- the filename of the index template (always index.html)\n
"""
# Copy template to appropriate directory
shutil.copy(f"{templatedir}/{templateFilename}", destinationdir)
# Read categories and config csv files
idName = "tk_category_dashname"
categories = util_csv.dictReaderMultiRow("../csv/categories.csv", idName)
config = util_csv.dictReaderFirstRow("../csv/config.csv")
# Replace config tk placeholders with values
for key in config.keys():
util_file.replaceTextInFile(f"{destinationdir}/index.html", key, config[key])
# lk_categories handler
tk_category_dashname = "tk_category_dashname"
tk_category_name = "tk_category_name"
## lk_categories handler ##
for category in categories:
util_file.replaceTextInFile(
f"{destinationdir}/index.html",
"lk_categories",
f'<a class="categoryLink" href="categories/{categories[category][tk_category_dashname]}">{categories[category][tk_category_name]}</a>lk_categories',
)
util_file.replaceTextInFile(f"{destinationdir}/index.html", "lk_categories", "")
## End of: lk_categories handler ##

View file

@ -13,6 +13,7 @@ def generate(templatedir, destinationdir, templateFilename):
templateFilename -- the filename of the run template (always run.html)\n
"""
# Read runs, categories, and config csv files
runIdName = "tk_run_id"
categoryIdName = "tk_category_dashname"
runs = util_csv.dictReaderMultiRow("../csv/runs.csv", runIdName)
@ -21,17 +22,19 @@ def generate(templatedir, destinationdir, templateFilename):
for run in runs:
# Get proper directory
thisRun = runs[run]
path = f"{destinationdir}/{thisRun[runIdName]}"
currentDir = os.getcwd()
# Copy template to appropriate directory
os.makedirs(path, exist_ok=True)
shutil.copy(
f"{currentDir}/{templatedir}/{templateFilename}",
f"{currentDir}/{path}/index.html",
)
# Replace run tk placeholders with values, then save tk_run_link and tk_run_duration for use in lk handlers
tk_run_link = ""
for key in thisRun:
util_file.replaceTextInFile(f"{path}/index.html", key, thisRun[key])
@ -40,6 +43,7 @@ def generate(templatedir, destinationdir, templateFilename):
elif key == "tk_run_duration":
tk_run_duration = thisRun[key]
# Replace category tk placeholders with values
for key in categories[thisRun["tk_run_category_dashname"]]:
util_file.replaceTextInFile(
f"{path}/index.html",
@ -47,11 +51,11 @@ def generate(templatedir, destinationdir, templateFilename):
categories[thisRun["tk_run_category_dashname"]][key],
)
# Replace config tk placeholders with values
for key in config.keys():
util_file.replaceTextInFile(f"{path}/index.html", key, config[key])
## lk_run_link handler ##
# lk_run_link handler
if tk_run_link == "":
util_file.replaceTextInFile(
f"{path}/index.html", "lk_run_link", "No recording available"
@ -63,10 +67,7 @@ def generate(templatedir, destinationdir, templateFilename):
f'<a class="runLink" href="{tk_run_link}">Run recording</a>',
)
## End of: lk_run_link handler ##
## lk_run_duration handler ##
# lk_run_duration handler
runDurationSplit = [float(value) for value in tk_run_duration.split(":")]
lk_run_duration = datetime.timedelta(
hours=runDurationSplit[0],
@ -76,5 +77,3 @@ def generate(templatedir, destinationdir, templateFilename):
util_file.replaceTextInFile(
f"{path}/index.html", "lk_run_duration", str(lk_run_duration)
)
## End of: lk_run_duration handler ##