logseq2gemtext/run.php

72 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
use LogseqGem\ArticleRender;
use LogseqGem\GemlogRender;
require __DIR__ . '/vendor/autoload.php';
$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)) {
throw new \Exception('Please provide an input gemlog file listing some articles. Got: ' . $gemlog_input_path);
}
if (is_null($gemlog_output_path) || !is_dir($gemlog_output_path)) {
throw new \Exception('Please provide a destination directory using -o');
}
$dir = dirname($gemlog_input_path);
$gemlog = new LogseqGem\GemlogParser;
$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';
$article->load($article_path);
$gemtext = $article->convert();
if (!$article->isPublished() || empty($gemtext)) {
continue;
}
if ($trim_prefix && strpos($title, $trim_prefix) === 0) {
$title = substr($title, strlen($trim_prefix));
}
$sanitized_title = $title;
$sanitized_title = strtolower($sanitized_title);
$sanitized_title = str_replace([' ', ','], ['-'], $sanitized_title);
$sanitized_title .= '.gmi';
$output_path = $gemlog_output_path . '/' . $sanitized_title;
echo "Writing to ", $sanitized_title, "...\n";
$render = new ArticleRender($title, $gemtext, $article->getProperties());
$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);
}