///usr/bin/env jbang "$0" "$@" ; exit $?
//
// This is a JBang script. You need JBang to run this script.
//
// To learn more go to https://www.jbang.dev and install JBang.
//
// Run this script:
// ./ghost2md.java -f -d
//
//DEPS info.picocli:picocli:4.7.7
//DEPS com.jayway.jsonpath:json-path:2.8.0
//DEPS com.fasterxml.jackson.core:jackson-databind:2.19.0
//DEPS io.github.furstenheim:copy_down:1.1
//JAVA 21+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ParseContext;
import com.jayway.jsonpath.TypeRef;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import io.github.furstenheim.CopyDown;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.concurrent.Callable;
@Command(name = "ghost2md", mixinStandardHelpOptions = true, version = "0.1", description = "Converts a Ghost export file to markdown files")
public class ghost2md implements Callable {
private static final ParseContext JSON = JsonPath.using(Configuration.builder().mappingProvider(new JacksonMappingProvider()).build());
private static final CopyDown HTML_TO_MD = new CopyDown();
@Option(names = { "--file", "-f" }, required = true, description = "The exported Ghost JSON file")
private File exportFile;
@Option(names = { "--dir", "-d" }, defaultValue = "exported", description = "The destination directory")
private File destinationDir;
@Override
public Integer call() throws Exception {
if (!exportFile.exists()) {
System.err.printf("%s does not exist%n", exportFile.getAbsolutePath());
return 404;
}
destinationDir.mkdirs();
var json = JSON.parse(exportFile);
var posts = json.read("$.db[*].data.posts[*]", new TypeRef>(){});
for (var post : posts) {
var filename = post.slug() + ".md";
var markdown = HTML_TO_MD.convert(post.html());
var file = new File(destinationDir, filename);
var title = "# " + post.title();
System.out.printf("Writing %s\n", file);
try (var writer = new FileWriter(file)) {
writer.write(title);
writer.write("\n\n");
writer.write(markdown);
}
}
return 0;
}
@JsonIgnoreProperties(ignoreUnknown = true)
record Post(String slug, String title, String html){}
public static void main(String[] args) {
final int exitCode = new CommandLine(new ghost2md()).execute(args);
System.exit(exitCode);
}
}