-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
139 lines (112 loc) · 4.93 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
const fs = require("fs");
const { parse } = require("csv-parse");
const slugify = require('slugify');
const prompt = require('prompt-sync')({sigint: true});
const clc = require("cli-color");
const { resolve } = require('path');
let { render } = require("mustache");
const convertCsvToMarkdown = () => {
// Parse the .csv file and return the data
const parseCsvFile = async (file, from, to = null, useColumns = false) => {
// Build parser options object
let parserOptions = { delimiter: ",", from_line: from, to_line: to }
if (useColumns) {
parserOptions = { columns: header => header.map(column => column.trim()) }
}
// Parse file
let records = []
const parser = fs
.createReadStream(file)
.pipe(parse(parserOptions));
for await (const record of parser) {
records.push(record)
}
return records
}
// Generate .md files based on given data
const generateMd = (rows, templateName, outputPath) => {
if (!rows.length) {
console.log('No variables could be generated from the CVS columns, please check your CSV and try again.');
return;
}
let schema = {};
const keys = Object.keys(rows[0]);
if (!keys.length) {
console.log('No variables could be generated from the CVS columns, please check your CSV and try again.');
return;
}
const mdVariables = prompt(`Available markdown variables: ${clc.red(keys.join(','))}, please update your markdown template. Updated? (y/N):` , 'y', {autocomplete: complete(['y', 'N'])});
if (mdVariables !== 'y') {
console.log('Markdown template not updated, please update and restart.');
return;
}
let selectedKey = prompt('Which variable should be used to generate slug and file name? ', 'id', {autocomplete: complete(keys)});
if (!keys.includes(selectedKey)) {
console.log(`Key are not part of your available variables: ${clc.red(keys.join(', '))}, fallback is used.`, clc.red(selectedKey));
if (!selectedKey) { selectedKey = schema[0]; }
} else {
console.log('Slug and filename generated based on key: ', clc.red(selectedKey));
}
let template = fs.readFileSync(`${templateName}`).toString();
rows.forEach( (row) => {
keys.forEach((key, i) => {
schema[key] = row[key] ? row[key] : '';
});
schema.slug = slugify(row[selectedKey], {lower: true, strict: true});
let output = render(template, schema)
fs.writeFileSync(`${outputPath}/${schema.slug}.md`, output);
console.log(`~ Markdown file ${clc.red(schema.slug)}.md generated.`);
})
}
// Init parser and get user input
const initCsvParser = () => {
let csvPath = prompt('Enter path to .csv file (e.g. ./demo.csv): ');
if (!csvPath) {
csvPath = prompt('Enter path to .csv file (e.g. ./demo.csv): ');
}
console.log('Your path: ', clc.red(csvPath));
const path = resolve(process.cwd(), csvPath);
let mdPath = prompt('Enter path to .md template file (e.g. ./basic.md): ');
if (!mdPath) {
mdPath = prompt('Enter path to .md template file (e.g. ./basic.md): ');
}
console.log('Your template name: ', clc.red(mdPath));
const templateName = resolve(process.cwd(), mdPath);
let mdFilesPath = prompt('Enter path to output directory, the directory must exist (e.g. ./md-files): ');
if (!mdFilesPath) {
mdFilesPath = prompt('Enter path to .md template file (e.g. ./basic.md): ');
}
console.log('Your output directory: ', clc.red(mdFilesPath));
const outputPath = resolve(process.cwd(), mdFilesPath);
const from = prompt('Enter start from line: ', 1);
console.log('Your start from Line: ', clc.red(Number(from)));
const till = prompt('Enter end line: ', null);
console.log('Your end Line: ', till ? clc.red(till) : clc.red('runs till the end of the file'));
console.log('The CSV column names are used for variable and schema generation!');
const useColumns = 'y';
// Parse .csv to get column and row data and start .md file generation
parseCsvFile(path, from, till ? Number(till) : null, useColumns).then(
(res) => {
generateMd(res, templateName, outputPath);
}
).catch(
(err) => {
console.log('rows:', err);
}
);
}
initCsvParser();
}
// Helper functions
function complete(commands) {
return function (str) {
let i;
let ret = [];
for (i=0; i< commands.length; i++) {
if (commands[i].indexOf(str) === 0)
ret.push(commands[i]);
}
return ret;
};
}
module.exports = convertCsvToMarkdown;