Created
June 14, 2012 06:31
-
-
Save mrklein/2928396 to your computer and use it in GitHub Desktop.
Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env coffee | |
path = require 'path' | |
fs = require 'fs' | |
util = require 'util' | |
hat = require 'hat' | |
argv = require('optimist') | |
.usage('Usage: $0 --name <deck name> --color <card color> <directory>') | |
.string(['name', 'color']) | |
.demand(1) | |
.argv | |
exec = (require 'child_process').exec | |
properties = | |
modifiedDate: Date.now() | |
name: argv.name ? "Default name" | |
cardColor: argv.color ? "blue" | |
flashcards = [] | |
work_dir = argv._[0] | |
if not path.existsSync work_dir | |
console.log "Unable to access directory #{work_dir}. Will exit." | |
return 1 | |
console.log "Collecting cards..." | |
for file in fs.readdirSync(work_dir) | |
if (path.extname file) is ".txt" | |
cards = fs.readFileSync(path.join(work_dir, file), "utf8") | |
lines = cards.split('\n') | |
front = "" | |
back = [] | |
cnt = 0 | |
back_cnt = 1 | |
for line in lines | |
if line is "---" | |
cnt = 0 | |
back_cnt = 1 | |
flashcards.push([front, "", back.join("\n"), ""]) | |
if cnt is 0 | |
front = line | |
if cnt > 1 | |
back.push("#{back_cnt}. #{line}") | |
back_cnt += 1 | |
cnt += 1 | |
data = | |
properties: properties | |
flashcards: flashcards | |
# Create data directory | |
tmp_dir_name = hat() | |
data_dir = path.join(tmp_dir_name, properties.name) | |
fs.mkdirSync(tmp_dir_name) | |
fs.mkdirSync(data_dir) | |
console.log path.join(data_dir, "data.txt") | |
data_file = fs.openSync(path.join(data_dir, "data.txt"), "w") | |
fs.writeSync(data_file, util.format("%j", data)) | |
fs.closeSync(data_file) | |
# Create zip | |
process.chdir(tmp_dir_name) | |
archive = properties.name + '.zip' | |
zip = exec "zip -r '" + archive + "' '" + properties.name + "'", | |
(error, stdout, stderr) -> | |
console.log stdout | |
fs.renameSync(archive, path.join("..", archive)) | |
process.chdir("..") | |
exec "rm -rf '" + tmp_dir_name + "'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment