UNPKG

1.81 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict';
4
5var path = require('path')
6 , fs = require('fs')
7 , file = require('./lib/file')
8 , transform = require('./lib/transform')
9 , argv = process.argv
10 , mode = 'github.com'
11 , files;
12
13function cleanPath(path) {
14 var homeExpanded = (path.indexOf('~') === 0) ? process.env.HOME + path.substr(1) : path;
15
16 // Escape all spaces
17 return homeExpanded.replace(/\s/g, '\\ ');
18}
19
20function transformAndSave(files, mode) {
21 console.log('\n==================\n');
22
23 var transformed = files
24 .map(function (x) {
25 var content = fs.readFileSync(x.path, 'utf8')
26 , result = transform(content, mode);
27 result.path = x.path;
28 return result;
29 });
30 var changed = transformed.filter(function (x) { return x.transformed; })
31 , unchanged = transformed.filter(function (x) { return !x.transformed; });
32
33 unchanged.forEach(function (x) {
34 console.log('"%s" is up to date', x.path);
35 });
36
37 changed.forEach(function (x) {
38 console.log('"%s" will be updated', x.path);
39 fs.writeFileSync(x.path, x.data, 'utf8');
40 });
41}
42
43if (argv.length < 3) {
44 console.log('Usage: doctoc <path> (where path is some path to a directory (i.e. .) or a file (i.e. README.md) )');
45 process.exit(0);
46}
47
48var bitbucketIdx = argv.indexOf('--bitbucket');
49
50if (~bitbucketIdx) {
51 mode = 'bitbucket.org';
52 argv.splice(bitbucketIdx, 1);
53}
54
55var target = cleanPath(argv[2]),
56 stat = fs.statSync(target);
57
58if (stat.isDirectory()) {
59 console.log ('\nDocToccing "%s" and its sub directories for %s.', target, mode);
60 files = file.findMarkdownFiles(target);
61} else {
62 console.log ('\nDocToccing single file "%s" for %s.', target, mode);
63 files = [{ path: target }];
64}
65
66transformAndSave(files, mode);
67
68console.log('\nEverything is OK.');
69