Adding -i for writing gemlog index

This commit is contained in:
Annika Backstrom 2022-05-22 11:46:18 +01:00
parent 27a8e454ef
commit a6b52e4136
4 changed files with 74 additions and 4 deletions

14
run.php
View File

@ -3,14 +3,16 @@
declare(strict_types=1);
use LogseqGem\ArticleRender;
use LogseqGem\GemlogRender;
require __DIR__ . '/vendor/autoload.php';
$opts = getopt('o:t:', rest_index: $rest_index);
$opts = getopt('o:t:i:', rest_index: $rest_index);
$rest = array_slice($argv, $rest_index);
$gemlog_input_path = $rest[0] ?? null;
$gemlog_output_path = $opts['o'] ?? null;
$gemlog_index_path = $opts['i'] ?? null;
$trim_prefix = $opts['t'] ?? null;
if (is_null($gemlog_input_path) || !file_exists($gemlog_input_path)) {
@ -29,6 +31,8 @@ $article = new LogseqGem\ArticleParser;
$gemlog->load($gemlog_input_path);
$titles = $gemlog->getTitles();
$gemlog_out = new GemlogRender;
foreach ($titles as $title) {
$encoded_title = str_replace('/', '%2F', $title);
$article_path = $dir . '/' . $encoded_title . '.md';
@ -56,4 +60,12 @@ foreach ($titles as $title) {
$output = $render->render(__DIR__ . '/templates/article.tpl');
file_put_contents($output_path, $output);
$gemlog_out->addArticle($title, $article->getProperties()['date'], 'log/' . $sanitized_title);
}
if ($gemlog_index_path) {
echo "Writing gemlog index to ", $gemlog_index_path, "...\n";
$gemlog_index = $gemlog_out->render();
file_put_contents($gemlog_index_path, $gemlog_index);
}

View File

@ -17,12 +17,11 @@ class GemlogParser extends Parser {
}
$text = $node->getLiteral();
if (substr($text, 0, 2) !== '[[' && substr($text, -2) !== ']]') {
if (!preg_match('/\[\[(.+)\]\]/', $text, $matches)) {
continue;
}
$titles[] = substr($text, 2, -2);
$titles[] = $matches[1];
}
return $titles;

36
src/GemlogRender.php Normal file
View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace LogseqGem;
class GemlogRender {
public $articles = [];
public function addArticle(string $title, string $date, string $path) {
$this->articles[] = [$title, $date, $path];
}
public function render() {
$gemlog = [];
usort($this->articles, fn ($a, $b) => $b[1] <=> $a[1]);
foreach ($this->articles as $article) {
$gemlog[] = sprintf('=> %s %s %s', $article[2], $article[1], $article[0]);
}
$gemlog = implode("\n", $gemlog);
return <<<EOF
# Annika's Gemlog
$gemlog
=> atom.xml Atom feed
=> / home
EOF;
}
}

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace LogseqGem\Tests;
use PHPUnit\Framework\TestCase;
use LogseqGem\GemlogRender;
class GemlogRenderTest extends TestCase {
public function testRender() {
$render = new GemlogRender;
$render->addArticle('second', '2021-01-01', 'foo.gmi');
$render->addArticle('third', '2020-01-01', 'old.gmi');
$render->addArticle('first', '2022-01-01', 'new.gmi');
$this->assertStringContainsString(<<<EOF
=> new.gmi 2022-01-01 first
=> foo.gmi 2021-01-01 second
=> old.gmi 2020-01-01 third
EOF, $render->render());
}
}