From 40ec00a4ad45eab484a039b9c6f562263d3c8802 Mon Sep 17 00:00:00 2001 From: Nathan McCarty Date: Tue, 21 Jan 2025 03:24:01 -0500 Subject: [PATCH] Basic database operations --- blog | 53 ++++++++++++++++++++++++++++++++++++++++++++++---- db/.gitkeep | 0 lib/DB.rakumod | 24 +++++++++++++++++++++-- 3 files changed, 71 insertions(+), 6 deletions(-) delete mode 100644 db/.gitkeep diff --git a/blog b/blog index eb271a0..d505cb7 100755 --- a/blog +++ b/blog @@ -1,9 +1,54 @@ #!/usr/bin/env raku +use v6.e.PREVIEW; use DB; -my $example-post = DB::MarkdownPost.new: - source => "../Idris/advent/src/Util/Digits.md".IO, - posted-at => DateTime.now; +my %*SUB-MAIN-OPTS = + :named-anywhere, + :bundling, +; -say $example-post.title; +my IO::Path:D $blog-dir = $*PROGRAM.dirname.IO.dirname.IO; +#= The directory this script is located in + +#| Load the database from the provided file +sub load-db(IO::Path $file --> DB::PostDB:D) { + my $result = DB::PostDB.from-json: $file.slurp; + if $result ~~ DB::PostDB:D { + return $result; + } else { + die "Error parsing $file as databse: $result"; + } +} + +#| Initalize the database +multi MAIN( + "db", + "init", + #| The path of the database file + IO::Path :$file = $blog-dir.add("db.json"), + #| Overwrite an already existing database file + Bool :$force +) { + die "Database file already exists, use --force to overwrite: {$file.Str}" + if $file.e && !$force; + + my $db = DB::PostDB.new; + + if $force { + $file.spurt: $db.to-json, :create-only; + } else { + $file.spurt: $db.to-json; + } +} + +#| Ensure that the database loads, erroring otherwise +multi MAIN( + "db", + "verify", + #| The path of the database file + IO::Path :$file = $blog-dir.add("db.json"), +) { + load-db $file; + say "Database OK"; +} diff --git a/db/.gitkeep b/db/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/lib/DB.rakumod b/lib/DB.rakumod index a12deb4..fd70f73 100644 --- a/lib/DB.rakumod +++ b/lib/DB.rakumod @@ -1,10 +1,13 @@ +use v6.e.PREVIEW; + #| Post database unit module DB; use Pandoc; +use JSON::Class:auth; #| Shared post meta-data -role Post { +role Post is json { #| The location of the source file for the post has IO::Path:D $.source is required; #| The time to display for the creation of the post @@ -18,9 +21,26 @@ role Post { } #| A plain markdown post -class MarkdownPost does Post { +class MarkdownPost does Post is json { + #| Marker for disambiguation between post types in json representation, the + #| cheaty way + has Bool:D $.markdown = True; method title(--> Str:D) { markdown-title($!source) } } + +# #| A literate idris post in markdown format +# class IdrisPost does Post { + +# method title(--> Str:D) { +# markdown-title($!source) +# } +# } + +#| The top level posts database +class PostDB is json(:pretty) { + #| The inner list of posts + has Post:D @.posts = []; +}