Skip to content

Instantly share code, notes, and snippets.

@lorenzo
Last active September 19, 2016 11:37
Show Gist options
  • Save lorenzo/090a770de6ba43df092181c4a421c5d5 to your computer and use it in GitHub Desktop.
Save lorenzo/090a770de6ba43df092181c4a421c5d5 to your computer and use it in GitHub Desktop.
<?php
//call `php gen_docs.php` in the forlder where docs.json is
// The markdown will be spit out to stdout
$sections = json_decode(file_get_contents("docs.json"), true);
$output = "";
function replaceDocs($comment, $section) {
return preg_replace_callback('/@docs\s+(.+)/mu', function ($matches) use ($section) {
$tokens = array_map('trim', explode(',', $matches[1]));
$functions = array_column($section['values'], 'comment', 'name');
$functionTypes = array_column($section['values'], 'type', 'name');
$aliases = array_column($section['aliases'], 'comment', 'name');
$aliasTypes = array_column($section['aliases'], 'type', 'name');
$types = array_column($section['types'], 'comment', 'name');
$typeDefinitions = array_column($section['types'], 'cases', 'name');
$output = "";
foreach ($tokens as $token) {
if (isset($aliases[$token])) {
$type = $aliasTypes[$token];
$comment = trim($aliases[$token]);
$output .= "```elm\ntype alias $token = \n";
$output .= " $type\n```\n\n$comment";
}
if (isset($functions[$token])) {
$type = formatSignature($functionTypes[$token]);
$comment = trim($functions[$token]);
$output .= "```elm\n$token : $type\n```\n\n$comment";
}
if (isset($types[$token])) {
$output .= formatType($token, $types[$token], $typeDefinitions[$token]);
}
$output .= "\n\n---\n";
}
return $output;
}, $comment);
}
function formatSignature($signature) {
$parts = array_map('trim', explode("->", $signature));
if (count($parts) > 3 || strlen($signature) > 110) {
$signature = array_map(function ($p) {
if ($p[0] === "(") {
return $p . " -> ";
}
return $p . "\n -> ";
}, $parts);
$signature = implode("", $signature);
$signature = trim($signature, "\n ->");
}
return $signature;
}
function formatType($name, $comment, $cases) {
$output = "";
$output .= "```elm\ntype $name\n";
$output .= " = ";
$firstCase = $cases[0] ?? $name;
$cases = array_slice($cases, 1);
$output .= $name;
foreach ($cases as $case) {
$case = $case[0] . " " . ($case[1][0] ?? "");
$output .= "\n | $case";
}
$output .= "\n```\n\n";
$output .= trim($comment);
return $output;
}
foreach ($sections as $section) {
$output .= "#" . $section['name'] . "\n\n";
$output .= replaceDocs($section['comment'], $section);
$output .= "\n\n---\n\n";
}
echo $output;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment