build.js (1711B)
1 import * as std from "std"; 2 import * as os from "os"; 3 4 function is_dir(path) { 5 let stat = os.stat(path)[0]; 6 if (stat == null) return false; 7 return !!(stat.mode & os.S_IFDIR); 8 } 9 10 function is_file(path) { 11 let stat = os.stat(path)[0]; 12 if (stat == null) return false; 13 return !!(stat.mode & os.S_IFREG); 14 } 15 16 function parent_dir(path) { 17 if (path.endsWith("/")) path = path.slice(0, -1); 18 if (!path.includes("/")) return "."; 19 return path.slice(0, path.lastIndexOf("/")); 20 } 21 22 // creates the directory with all needed parents 23 function mkdir_p(path) { 24 if (!is_dir(path)) { 25 mkdir_p(parent_dir(path)); 26 os.mkdir(path); 27 } 28 } 29 30 // return paths to all pages 31 function get_pages(entry_path) { 32 return os.readdir(entry_path)[0].filter(e => e != "." && e != "..") 33 .map(e => entry_path + "/" + e) 34 .flatMap(e => { 35 if (is_dir(e) && !e.endsWith("/src")) { 36 return get_pages(e); 37 } else if (is_file(e) && e.endsWith("/index.html")) { 38 return [e]; 39 } 40 return []; 41 }); 42 } 43 44 // list of paths 45 const pages = [...get_pages("content"), "content/404.html"]; 46 47 const template = std.loadFile("template/dist/index.html"); 48 49 pages.forEach(src => { 50 const dst = src.replace("content/", "dist/"); 51 52 const txt_src = std.loadFile(src); 53 const title = txt_src.includes("<h1>") ? 54 txt_src.split("<h1>")[1].split("</h1>")[0] + " | tongong.net" 55 : "tongong.net"; 56 const txt = template 57 .replace("{{title}}", title) 58 .replace("{{content}}\n", txt_src) 59 60 mkdir_p(parent_dir(dst)); 61 const dfile = std.open(dst, "w"); 62 dfile.puts(txt); 63 dfile.close(); 64 });