Skip to content

Commit

Permalink
Format utils and scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
alexg-axis committed Dec 3, 2022
1 parent 535ea5f commit 7976c0a
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 157 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"deno.suggest.imports.hosts": {
"https://deno.land": true
},
"python.pythonPath": "/usr/local/opt/[email protected]/bin/python3"
"python.pythonPath": "/usr/local/opt/[email protected]/bin/python3",
"python.formatting.provider": "black"
}
224 changes: 114 additions & 110 deletions scripts/html2md.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,122 +10,126 @@

HTMLAttributes: TypeAlias = list[tuple[str, str | None]]


def attr(attrs: HTMLAttributes, needle: str) -> str | None:
for key, value in attrs:
if key == needle:
return value
return None
for key, value in attrs:
if key == needle:
return value
return None


class CustomParser(HTMLParser):
def __init__(self, *, convert_charrefs: bool = ...) -> None:
super().__init__(convert_charrefs=convert_charrefs)

# Tag stack
self.tags: list[tuple[str, HTMLAttributes]] = []
# Whether or not we're inside the main article
self.is_in_article = False
# The ul depth
self.list_depth = 0
# Whether the last seen ul was nested
self.list_was_nested = False

def handle_starttag(self, tag: str, attrs: HTMLAttributes) -> None:
self.tags.append((tag, attrs))
if attr(attrs, "class") == "day-desc":
self.is_in_article = True

if not self.is_in_article:
return

if tag == "em" and not self.is_in_tag("code"):
print("__", end="")
elif tag == "code":
if self.is_in_tag("pre"):
print("```")
else:
print("`", end="")
elif tag == "li":
print(" " * (self.list_depth - 1) + "- ", end="")
elif tag == "ul":
self.list_depth += 1
if self.list_depth == 1:
self.list_was_nested = False
elif self.list_depth > 1:
self.list_was_nested = True
print()

def handle_endtag(self, tag: str) -> None:
_, attrs = self.tags.pop()

# Naively believe only one article exists
if tag == "article":
def __init__(self, *, convert_charrefs: bool = ...) -> None:
super().__init__(convert_charrefs=convert_charrefs)

# Tag stack
self.tags: list[tuple[str, HTMLAttributes]] = []
# Whether or not we're inside the main article
self.is_in_article = False
# The ul depth
self.list_depth = 0
# Whether the last seen ul was nested
self.list_was_nested = False

def handle_starttag(self, tag: str, attrs: HTMLAttributes) -> None:
self.tags.append((tag, attrs))
if attr(attrs, "class") == "day-desc":
self.is_in_article = True

if not self.is_in_article:
return

if tag == "em" and not self.is_in_tag("code"):
print("__", end="")
elif tag == "code":
if self.is_in_tag("pre"):
print("```")
else:
print("`", end="")
elif tag == "li":
print(" " * (self.list_depth - 1) + "- ", end="")
elif tag == "ul":
self.list_depth += 1
if self.list_depth == 1:
self.list_was_nested = False
elif self.list_depth > 1:
self.list_was_nested = True
print()

def handle_endtag(self, tag: str) -> None:
_, attrs = self.tags.pop()

# Naively believe only one article exists
if tag == "article":
self.is_in_article = False

if not self.is_in_article:
return

if tag == "p":
print("\n")
elif tag == "em" and not self.is_in_tag("code"):
print("__", end="")
elif tag == "code":
if self.is_in_tag("pre"):
print("```\n")
else:
print("`", end="")
elif tag == "li":
print()
elif tag == "ul":
self.list_depth -= 1
# As a nested ul resides within a li tag two newlines will be printed
# for the last li. As we don't have a lookahead, best we can do is to
# keep track of last seen nested ul and add another newline when we
# leave a non-nested ul
if not self.list_was_nested and self.list_depth == 0:
print()
elif tag == "span":
title = attr(attrs, "title")
if title is not None:
print(f" (_{title}_)", end="")

@property
def current_tag(self) -> tuple[str, HTMLAttributes] | None:
if len(self.tags) == 0:
return None
return self.tags[len(self.tags) - 1]

def is_in_tag(self, tag: str) -> bool:
for parent_tag, _ in self.tags:
if parent_tag == tag:
return True
return False

def handle_data(self, data: str) -> None:
if self.is_in_article == False or self.current_tag is None:
return

tag, attrs = self.current_tag
if tag == "h2":
print(f"## {data}\n")
elif tag == "a":
href = attr(attrs, "href")
if href is not None:
print(f"[{data}]({href})", end="")
elif tag == "p":
print(data, end="")
elif tag == "em":
print(data, end="")
elif tag == "code":
print(data, end="")
elif tag == "span":
print(data, end="")
elif tag == "li":
print(data, end="")

if not self.is_in_article:
return

if tag == "p":
print("\n")
elif tag == "em" and not self.is_in_tag("code"):
print("__", end="")
elif tag == "code":
if self.is_in_tag("pre"):
print("```\n")
else:
print("`", end="")
elif tag == "li":
print()
elif tag == "ul":
self.list_depth -= 1
# As a nested ul resides within a li tag two newlines will be printed
# for the last li. As we don't have a lookahead, best we can do is to
# keep track of last seen nested ul and add another newline when we
# leave a non-nested ul
if not self.list_was_nested and self.list_depth == 0:
print()
elif tag == "span":
title = attr(attrs, "title")
if title is not None:
print(f" (_{title}_)", end="")

@property
def current_tag(self) -> tuple[str, HTMLAttributes] | None:
if len(self.tags) == 0:
return None
return self.tags[len(self.tags) - 1]

def is_in_tag(self, tag: str) -> bool:
for parent_tag, _ in self.tags:
if parent_tag == tag:
return True
return False

def handle_data(self, data: str) -> None:
if self.is_in_article == False or self.current_tag is None:
return

tag, attrs = self.current_tag
if tag == "h2":
print(f"## {data}\n")
elif tag == "a":
href = attr(attrs, "href")
if href is not None:
print(f"[{data}]({href})", end="")
elif tag == "p":
print(data, end="")
elif tag == "em":
print(data, end="")
elif tag == "code":
print(data, end="")
elif tag == "span":
print(data, end="")
elif tag == "li":
print(data, end="")

def main():
parser = CustomParser()
for line in stdin.readlines():
parser.feed(line)
parser = CustomParser()
for line in stdin.readlines():
parser.feed(line)


if __name__ == "__main__":
main()
main()
4 changes: 2 additions & 2 deletions scripts/init.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ mkdir -p "$year/$padded_day"

export PATH="/usr/local/opt/[email protected]/bin:$PATH"
session_cookie="$(security find-generic-password -w -a "com.adventofcode.SessionCookie")"
curl --silent --cookie "session=$session_cookie" "https://adventofcode.com/$year/day/$day" | ./scripts/html2md.py > "$year/$padded_day/README.md"
curl --silent --cookie "session=$session_cookie" "https://adventofcode.com/$year/day/$day/input" > "$year/$padded_day/input.txt"
curl --silent --cookie "session=$session_cookie" "https://adventofcode.com/$year/day/$day" | ./scripts/html2md.py >"$year/$padded_day/README.md"
curl --silent --cookie "session=$session_cookie" "https://adventofcode.com/$year/day/$day/input" >"$year/$padded_day/input.txt"

echo "$day/12 $year initialized successfully in ./$year/$padded_day" >&2
33 changes: 17 additions & 16 deletions scripts/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,22 @@ for file in $main_files; do
name="$(basename "$file")"
directory="$(dirname "$file")"
case "${name##*.}" in
"go")
go run "$file"
;;
"ts")
NO_COLOR=1 deno run --quiet --allow-read "$file"
;;
"py")
export PYTHONPATH="$PWD/utils/python/:$PYTHONPATH"
python3 "$file"
;;
"c")
out="$(mktemp --suffix=.main)"
gcc -o "$out" "$directory/"*.c utils/c/*.c && "$out"
;;
*)
echo "unsupported $file"
"go")
go run "$file"
;;
"ts")
NO_COLOR=1 deno run --quiet --allow-read "$file"
;;
"py")
export PYTHONPATH="$PWD/utils/python/:$PYTHONPATH"
python3 "$file"
;;
"c")
out="$(mktemp --suffix=.main)"
gcc -o "$out" "$directory/"*.c utils/c/*.c && "$out"
;;
*)
echo "unsupported $file"
;;
esac
done
11 changes: 6 additions & 5 deletions scripts/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ for file in $main_files; do
directory="$(dirname "$file")"
pushd "$directory"
case "${name##*.}" in
"ts")
NO_COLOR=1 deno test --quiet --allow-read
;;
*)
echo "unsupported $file"
"ts")
NO_COLOR=1 deno test --allow-read
;;
*)
echo "unsupported $file"
;;
esac
popd
done
4 changes: 2 additions & 2 deletions scripts/upload.sh
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ for solution in $solutions; do
too_recent="$(echo "$output" | grep -c "You gave an answer too recently" || true)"
if [[ "$correct" -eq 1 ]] || [[ "$already_solved" -eq 1 ]]; then
echo "✅ solution $part"
correct=$((correct+1))
correct=$((correct + 1))
elif [[ "$incorrect" -eq 1 ]]; then
echo "❌ solution $part"
elif [[ "$too_recent" -eq 1 ]]; then
Expand All @@ -39,7 +39,7 @@ for solution in $solutions; do
echo "$output"
echo "------------"
fi
part=$((part+1))
part=$((part + 1))
done

echo ""
Expand Down
10 changes: 5 additions & 5 deletions utils/deno/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@ import * as path from "https://deno.land/std/path/mod.ts";

const directory = path.dirname(path.fromFileUrl(Deno.mainModule));

const raw = await Deno.readTextFile(path.resolve(directory, "input.txt"))
const raw = await Deno.readTextFile(path.resolve(directory, "input.txt"));

/** Input represents a puzzle's input. */
export class Input {
constructor(public readonly raw: string) {}

/** The lines of the input. Trims trailing whitespace. */
get lines() {
return this.raw.trimEnd().split("\n")
return this.raw.trimEnd().split("\n");
}

/** The numbers of the input, one number per line. */
get numbers() {
return this.lines.map(x => Number(x))
return this.lines.map((x) => Number(x));
}
}

/** The puzzle's input */
const input = new Input(raw)
export default input
const input = new Input(raw);
export default input;
Loading

0 comments on commit 7976c0a

Please sign in to comment.