#!/usr/bin/env node const fs = require('fs') const path = require('path') const args = require('minimist')(process.argv.slice(2)) const oslo = require('../src/index') class OsloCLI { constructor(opts) { let output if (opts.f) { output = this.file(path.join(process.cwd(), opts.f)) } else if (opts.d) { if (!opts.o) { console.log('Output directory required. Invoke oslo with `-o path/to/output/directory`') process.exit() } output = this.directory(this.absolutePath(opts.d), this.absolutePath(opts.o)) } else if (opts.e) { output = this.inline(opts.e) } else { this.printUsage() process.exit() } if (opts.o) { const absoluteOutputPath = this.absolutePath(opts.o) if (opts.f || opts.e) { fs.writeFile(absoluteOutputPath, output, function (err) { if (err) throw err }) } else if (opts.d) { const absoluteInputPath = this.absolutePath(opts.d) Object.keys(output).forEach(function (file) { const absoluteOutputFilePath = file.replace(absoluteInputPath, absoluteOutputPath).replace(/\.oslo$/, '.html') const parentDirectory = path.dirname(absoluteOutputFilePath) if (!fs.existsSync(parentDirectory)) { fs.mkdirSync(parentDirectory) } fs.writeFile(absoluteOutputFilePath, output[file], function (err) { if (err) throw err console.log(`Writing to ${absoluteOutputFilePath.replace(process.cwd(), '')}`) }) }) } } else { process.stdout.write(output) process.stdout.write('\n') } } file(file) { const contents = fs.readFileSync(file).toString() return oslo(contents) } directory(directory) { let files = {} fs.readdirSync(directory).forEach(item => { const absolutePath = this.absolutePath(item, directory) if (fs.lstatSync(absolutePath).isDirectory()) { files = Object.assign(files, this.directory(absolutePath)) } else { let output = this.file(absolutePath) files[absolutePath] = output } }) return files } inline(source) { return oslo(source) } absolutePath(file, root = null) { if (!root) { root = process.cwd() } return path.join(root, file) } printUsage() { console.log( `USAGE -d The path to a directory. The directory will be recursively scanned. An output directory is required with this option. oslo -d templates -e Pass oslo code directly. oslo -e '(div "Hello world")' -f The path to a single file. oslo -f index.oslo -o Where to direct the output. If no path is provided, output will be directed to stdout. When used with -f, the argument should be the path to a file. When used with -d, the argument should be the path to a directory, which will be created if it does not already exist. oslo -f index.oslo -o index.html oslo -d templates -o html` ) } } (new OsloCLI(args))