use database directory instead of database file

This commit is contained in:
Nathan McCarty 2025-02-02 17:57:27 -05:00
parent fc04245162
commit 3b0e34e66e
7 changed files with 80 additions and 51 deletions

46
blog
View file

@ -10,36 +10,28 @@ my %*SUB-MAIN-OPTS =
:bundling,
;
my IO::Path:D $blog-dir = $*PROGRAM.parent;
#= The directory this script is located in
#| The directory this script is located in
my IO::Path:D $default-blog-dir = $*PROGRAM.parent;
#| 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;
#| Default database directory
my IO::Path:D $default-db-dir =
do if %*ENV<BLOG_TEST> {
$default-blog-dir.add('test-db/')
} else {
die "Error parsing $file as databse: $result";
}
}
#| Write the databse to the provided file
sub write-db(IO::Path $file, DB::PostDB $db) {
my $output = $db.to-json;
$file.spurt: $output;
}
$default-blog-dir.add('db/')
};
#| Initalize the database
multi MAIN(
"db",
"init",
#| The path of the database file
IO::Path(Str) :$db-file = $blog-dir.add("db.json"),
IO::Path(Str) :$db-dir = $default-db-dir,
#| Overwrite an already existing database file
Bool :$force
) {
die "Database file already exists, use --force to overwrite: {$db-file.Str}"
if $db-file.e && !$force;
die "Database folder already exists, use --force to overwrite: {$db-dir.Str}"
if $db-dir.e && !$force;
print "Blog Title: ";
my $title = get;
@ -50,11 +42,7 @@ multi MAIN(
my $db = DB::PostDB.init: $meta;
if $force {
$db-file.spurt: $db.to-json, :create-only;
} else {
$db-file.spurt: $db.to-json;
}
$db.write: $db-dir;
}
#| Ensure that the database loads, erroring otherwise
@ -62,9 +50,9 @@ multi MAIN(
"db",
"verify",
#| The path of the database file
IO::Path(Str) :$db = $blog-dir.add("db.json"),
IO::Path(Str) :$db-dir = $default-db-dir,
) {
load-db $db;
read-db $db-dir;
say "Database OK";
}
@ -76,13 +64,13 @@ multi MAIN(
#| The path to the markdown file
IO::Path(Str) $source,
#| The path of the database file
IO::Path(Str) :$db-file = $blog-dir.add("db.json"),
IO::Path(Str) :$db-dir = $default-db-dir,
#| The date/time the post should be recorded as posted at
DateTime(Str) :$posted-at = DateTime.now,
#| Should the post be hidden from the archive?
Bool :$hidden = False,
) {
my $db = load-db $db-file;
my $db = read-db $db-dir;
my $id =
$db.insert-post:
MarkdownPost.new(
@ -90,7 +78,7 @@ multi MAIN(
posted-at => $posted-at,
hidden => $hidden,
);
write-db $db-file, $db;
$db.write: $db-dir;
say 'Post inserted with id ', $id;
say 'Post has slugs: ', $db.posts{$id}.all-slugs;
}