-
Notifications
You must be signed in to change notification settings - Fork 56
/
docker.js
1585 lines (1414 loc) · 49.9 KB
/
docker.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// # docker.js
// ### _A simple documentation generator based on [docco](http://jashkenas.github.com/docco/)_
// **Docker** is a really simple documentation generator, which originally started out as a
// pure-javascript port of **docco**, but which eventually gained many extra little features
// which somewhat break docco's philosophy of being a quick-and-dirty thing.
//
// Docker source-code can be found on [GitHub](https://github.com/jbt/docker)
//
// Take a look at the [original docco project](http://jashkenas.github.com/docco/) to get a feel
// for the sort of functionality this provides. In short: **Markdown**-based displaying of code comments
// next to syntax-highlighted code. This page is the result of running docker against itself.
//
// The command-line usage of docker is somewhat more useful than that of docco. To use, simply run
//
// ```sh
// ./docker -i path/to/code -o path/to/docs [a_file.js a_dir]
// ```
//
// Docker will then recurse into the code root directory (or alternatively just the files
// and directories you specify) and document-ize all the files it can.
// The folder structure will be preserved in the document root.
//
// More detailed usage instructions and examples can be found in the [README](../README.md.html)
//
// ## Differences from docco
// The main differences from docco are:
//
// - **jsDoc support**: support for **jsDoc**-style code comments, which
// is provided in a style similar to [Dox](https://github.com/visionmedia/dox). You can see some examples of
// the sort of output you get below.
//
// - **Folder Tree** and **Heading Navigation**: collapsible sidebar with folder tree and jump-to
// heading links for easy navigation between many files and within long files.
//
// - **Markdown File Support**: support for plain markdown files, like the [README](../README.md.html) for this project.
//
// - **Colour Schemes**: support for multiple output colour schemes
//
//
// So let's get started!
// ## Node Modules
// Include all the necessay node modules.
var mkdirp = require('mkdirp'),
fs = require('fs'),
os = require('os'),
path = require('path'),
exec = require('child_process').exec,
spawn = require('child_process').spawn,
watchr = require('watchr'),
pygmentize = require('pygmentize-bundled'),
showdown = require('../lib/showdown').Showdown;
// Polyfill `fs.exists` for node <= 0.6
if(typeof fs.exists != 'function') fs.exists = path.exists;
/**
* ## Docker Constructor
*
* Creates a new docker instance. All methods are called on one instance of this object.
*
* Input arguments are either
*
* * Object containing any of the keys `inDir`, `outDir`, `onlyUpdated`, `colourScheme`, `ignoreHidden`, `sidebarState`, `exclude`
* * Or `indir`, `outDir`, `onlyUpdated`, `colourScheme` and `ignoreHidden` in order
*/
var Docker = module.exports = function( /* inDir, outDir, onlyUpdated, colourScheme, ignoreHidden */ ){
if(typeof arguments[0] === 'object'){
this.parseOpts(arguments[0]);
}else{
this.parseOpts({
inDir: arguments[0],
outDir: arguments[1],
onlyUpdated: arguments[2],
colourScheme: arguments[3],
ignoreHidden: arguments[4]
});
}
this.running = false;
this.scanQueue = [];
this.files = [];
this.tree = {};
};
/**
* ## Docker.prototype.parseOpts
*
* Parses options for this docker instance
*
* @param {object} opts Object containing all options fo rthis instance
*/
Docker.prototype.parseOpts = function(opts){
var defaults = {
inDir: path.resolve('.'),
outDir: path.resolve('doc'),
onlyUpdated: false,
colourScheme: 'default',
ignoreHidden: false,
sidebarState: true,
exclude: false,
lineNums: false,
multiLineOnly: false,
js: [],
css: [],
extras: []
};
// Loop through and fix up any unspecified options with the defaults.
for(var i in defaults){
if(defaults.hasOwnProperty(i) && typeof opts[i] === 'undefined'){
opts[i] = defaults[i];
}
}
this.inDir = opts.inDir.replace(/\/$/,'');
this.outDir = opts.outDir;
this.onlyUpdated = !!opts.onlyUpdated;
this.colourScheme = opts.colourScheme;
this.ignoreHidden = !!opts.ignoreHidden;
this.sidebarState = opts.sidebarState;
this.lineNums = !!opts.lineNums;
this.extraJS = opts.js || [];
this.extraCSS = opts.css || [];
this.multiLineOnly = !!opts.multiLineOnly;
// Generate an exclude regex for the given pattern
if(typeof opts.exclude === 'string'){
this.excludePattern = new RegExp('^(' +
opts.exclude.replace(/\./g,'\\.')
.replace(/\*/g, '.*')
.replace(/,/g, '|') +
')(/|$)');
}else{
this.excludePattern = false;
}
// Oh go on then. Allow American-Enligsh spelling of colour if used programmatically
if(opts.colorScheme) opts.colourScheme = opts.colorScheme;
// Load bundled extras
var extrasRoot = path.resolve(__dirname, '..', 'extras');
for(var i = 0; i < opts.extras.length; i += 1){
var extraName = opts.extras[i];
this.extraJS.push(path.join(extrasRoot, extraName, extraName + '.js'));
this.extraCSS.push(path.join(extrasRoot, extraName, extraName + '.css'));
}
};
/**
* ## Docker.prototype.doc
*
* Generate documentation for a bunch of files
*
* @this Docker
* @param {Array} files Array of file paths relative to the `inDir` to generate documentation for.
*/
Docker.prototype.doc = function(files){
this.running = true;
[].push.apply(this.scanQueue, files);
var self = this;
if(this.onlyUpdated){
// Attempt to grab the existing tree if possible.
fs.readFile(path.join(self.outDir, 'doc-filelist.js'), function(err, file){
if(err) return self.addNextFile();
file = file.toString().replace(/(^var tree=|;$)/g,'');
self.tree = JSON.parse(file);
self.addNextFile();
});
}else{
this.addNextFile();
}
};
/**
* ## Docker.prototype.watch
*
* Watches the input directory for file changes and updates docs whenever a file is updated
*
* @param {Array} files Array of file paths relative to the `inDir` to generate documentation for.
*/
Docker.prototype.watch = function(files){
this.watching = true;
this.watchFiles = files;
// Function to call when a file is changed. We put this on a timeout to account
// for several file changes happening in quick succession.
var uto = false, self = this;
function update(){
if(self.running) return (uto = setTimeout(update, 250));
self.clean();
self.doc(self.watchFiles);
uto = false;
}
// Install watchr. The `null` here is a watchr bug - looks like he forgot to allow for exactly
// two arguments (like in his example)
watchr.watch({
path: this.inDir,
listener: function(){
if(!uto) uto = setTimeout(update, 250);
}
});
// Aaaaand, go!
this.doc(files);
};
/**
* ## Docker.prototype.finished
*
* Callback function fired when processing is finished.
*/
Docker.prototype.finished = function(){
this.running = false;
if(this.watching){
// If we're in watch mode, switch "only updated files" mode on if it isn't already
this.onlyUpdated = true;
console.log('Done. Waiting for changes...');
}else{
console.log('Done.');
}
};
/**
* ## Docker.prototype.clean
*
* Clears out any instance variables so this docker can be rerun
*/
Docker.prototype.clean = function(){
this.scanQueue = [];
this.files = [];
};
/**
* ## Docker.prototype.addNextFile
*
* Process the next file on the scan queue. If it's a directory, list all the children and queue those.
* If it's a file, add it to the queue.
*/
Docker.prototype.addNextFile = function(){
if(this.scanQueue.length > 0){
var self = this, filename = this.scanQueue.shift();
if(this.excludePattern && this.excludePattern.test(filename)){
this.addNextFile();
return;
}
var currFile = path.resolve(this.inDir, filename);
fs.lstat(currFile, function cb(err, stat){
if(err){
// Something unexpected happened on the filesystem.
// Nothing really that we can do about it, so throw it and be done with it
throw err;
}
if(stat && stat.isSymbolicLink()){
fs.readlink(currFile, function(err, link){
if(err){
// Something unexpected happened on the filesystem.
// Nothing really that we can do about it, so throw it and be done with it
throw err;
}
currFile = path.resolve(path.dirname(currFile), link);
fs.exists(currFile, function(exists){
if(!exists){
console.error("Unable to follow symlink to " + currFile + ': file does not exist');
self.addNextFile();
}else{
fs.lstat(currFile, cb);
}
});
});
}else if(stat && stat.isDirectory()){
// Find all children of the directory and queue those
fs.readdir(path.resolve(self.inDir, filename), function(err, list){
if(err){
// Something unexpected happened on the filesystem.
// Nothing really that we can do about it, so throw it and be done with it
throw err;
}
for(var i = 0; i < list.length; i += 1){
if(self.ignoreHidden && list[i].charAt(0).match(/[\._]/)) continue;
self.scanQueue.push(path.join(filename, list[i]));
}
self.addNextFile();
});
}else{
self.queueFile(filename);
self.addNextFile();
}
});
}else{
// Once we're done scanning all the files, start processing them in order.
this.files = this.files.sort();
this.processNextFile();
}
};
/**
* ## Docker.prototype.queueFile
*
* Queues a file for processing, and additionally stores it in the folder tree
*
* @param {string} filename Name of the file to queue
*/
Docker.prototype.queueFile = function(filename){
this.files.push(filename);
};
/**
* ## Docker.prototype.addFileToFree
*
* Adds a file to the file tree to show in the sidebar. This used to be in `queueFile` but
* since we're now only deciding whether or not the file can be included at the point of
* reading it, this has to happen later.
*
* @param {string} filename Name of file to add to the tree
*/
Docker.prototype.addFileToTree = function(filename){
var pathSeparator = path.join('a', 'b').replace(/(^.*a|b.*$)/g, '');
// Split the file's path into the individual directories
filename = filename.replace(new RegExp('^' + pathSeparator.replace(/([\/\\])/g, '\\$1')),'');
var bits = filename.split(pathSeparator);
// Loop through all the directories and process the folder structure into `this.tree`.
//
// `this.tree` takes the format:
// ```js
// {
// dirs: {
// 'child_dir_name': { /* same format as tree */ },
// 'other_child_name': // etc...
// },
// files: [
// 'filename.js',
// 'filename2.js',
// // etc...
// ]
// }
// ```
var currDir = this.tree;
for(var i = 0; i < bits.length - 1; i += 1){
if(!currDir.dirs) currDir.dirs = {};
if(!currDir.dirs[bits[i]])currDir.dirs[bits[i]] = {};
currDir = currDir.dirs[bits[i]];
}
if(!currDir.files) currDir.files = [];
var lastBit = bits[bits.length-1];
if(currDir.files.indexOf(lastBit) === -1) currDir.files.push(bits[bits.length-1]);
};
/**
* ## Docker.prototype.processNextFile
*
* Take the next file off the queue and process it
*/
Docker.prototype.processNextFile = function(){
var self = this;
// If we still have files on the queue, process the first one
if(this.files.length > 0){
this.generateDoc(this.files.shift(), function(){
self.processNextFile();
});
}else{
this.copySharedResources();
}
};
/**
* ## Docker.prototype.generateDoc
* ### _This is where the magic happens_
*
* Generate the documentation for a file
*
* @param {string} filename File name to generate documentation for
* @param {function} cb Callback function to execute when we're done
*/
Docker.prototype.generateDoc = function(infilename, cb){
var self = this;
this.running = true;
filename = path.resolve(this.inDir, infilename);
this.decideWhetherToProcess(filename, function(shouldProcess){
if(!shouldProcess) return cb();
fs.readFile(filename, 'utf-8', function(err, data){
if(err) throw err;
var lang = self.languageParams(filename, data);
if(lang === false) return cb();
self.addFileToTree(infilename);
switch(self.languages[lang].type){
case 'markdown':
self.renderMarkdownHtml(data, filename, cb);
break;
default:
case 'code':
var sections = self.parseSections(data, lang);
self.highlight(sections, lang, function(){
self.renderCodeHtml(sections, filename, cb);
});
break;
}
});
});
};
/**
* ## Docker.prototype.decideWhetherToProcess
*
* Decide whether or not a file should be processed. If the `onlyUpdated`
* flag was set on initialization, only allow processing of files that
* are newer than their counterpart generated doc file.
*
* Fires a callback function with either true or false depending on whether
* or not the file should be processed
*
* @param {string} filename The name of the file to check
* @param {function} callback Callback function
*/
Docker.prototype.decideWhetherToProcess = function(filename, callback){
// If we should be processing all files, then yes, we should process this one
if(!this.onlyUpdated) return callback(true);
// Find the doc this file would be compiled to
var outFile = this.outFile(filename);
// See whether the file is newer than the output
this.fileIsNewer(filename, outFile, callback);
};
/**
* ## Docker.prototype.fileIsNewer
*
* Sees whether one file is newer than another
*
* @param {string} file File to check
* @param {string} otherFile File to compare to
* @param {function} callback Callback to fire with true if file is newer than otherFile
*/
Docker.prototype.fileIsNewer = function(file, otherFile, callback){
fs.stat(otherFile, function(err, outStat){
// If the output file doesn't exist, then definitely process this file
if(err && err.code == 'ENOENT') return callback(true);
fs.stat(file, function(err, inStat){
// Process the file if the input is newer than the output
callback(+inStat.mtime > +outStat.mtime);
});
});
};
/**
* ## Docker.prototype.parseSections
*
* Parse the content of a file into individual sections.
* A section is defined to be one block of code with an accompanying comment
*
* Returns an array of section objects, which take the form
* ```js
* {
* doc_text: 'foo', // String containing comment content
* code_text: 'bar' // Accompanying code
* }
* ```
* @param {string} data The contents of the script file
* @param {string} language The language of the script file
* @return {Array} array of section objects
*/
Docker.prototype.parseSections = function(data, language){
var codeLines = data.split('\n');
var sections = [];
// Fetch language-specific parameters for this code file
var params = this.languages[language];
var section = {
docs: '',
code: ''
};
var inMultiLineComment = false;
var multiLine = '';
var jsDocData;
function md(a, stripParas){
var h = showdown.makeHtml(a.replace(/(^\s*|\s*$)/,''));
return stripParas ? h.replace(/<\/?p>/g,'') : h;
}
var commentRegex = new RegExp('^\\s*' + params.comment + '\\s?');
// Loop through all the lines, and parse into sections
for(var i = 0; i < codeLines.length; i += 1){
var line = codeLines[i];
// Only match against parts of the line that don't appear in strings
var matchable = line.replace(/(["'])((?:[^\\\1]|(?:\\\\)*?\\[^\\])*?)\1/g,'$1$1');
if(params.literals) {
params.literals.forEach(function(replace){
matchable = matchable.replace(replace[0], replace[1]);
});
}
if(params.multiLine){
// If we are currently in a multiline comment, behave differently
if(inMultiLineComment){
// End-multiline comments should match regardless of whether they're 'quoted'
if(line.match(params.multiLine[1])){
// Once we have reached the end of the multiline, take the whole content
// of the multiline comment, and parse it as jsDoc.
inMultiLineComment = false;
multiLine += line;
// Replace block comment delimiters with whitespace of the same length
// This way we can safely outdent without breaking too many things if the
// comment has been deliberately indented. For example, the lines in the
// followinc comment should all be outdented equally:
//
// ```c
// /* A big long multiline
// comment that should get
// outdented properly */
// ```
multiLine = multiLine
.replace(params.multiLine[0], function(a){ return Array(a.length + 1).join(' '); })
.replace(params.multiLine[1], function(a){ return Array(a.length + 1).join(' '); });
multiLine = this.outdent(multiLine);
if(params.jsDoc){
// Strip off leading * characters.
multiLine = multiLine.replace(/^[ \t]*\*? ?/gm, "");
jsDocData = this.parseMultiline(multiLine);
// Put markdown parser on the data so it can be accessed in the template
jsDocData.md = md;
section.docs += this.jsDocTemplate(jsDocData);
}else{
section.docs += '\n' + multiLine + '\n';
}
multiLine = '';
}else{
multiLine += line + '\n';
}
continue;
}else if(
// We want to match the start of a multiline comment only if the line doesn't also match the
// end of the same comment, or if a single-line comment is started before the multiline
// So for example the following would not be treated as a multiline starter:
// ```js
// alert('foo'); // Alert some foo /* Random open comment thing
// ```
matchable.match(params.multiLine[0]) &&
!matchable.replace(params.multiLine[0],'').match(params.multiLine[1]) &&
(!params.comment || !matchable.split(params.multiLine[0])[0].match(commentRegex))
){
// Here we start parsing a multiline comment. Store away the current section and start a new one
if(section.code){
if(!section.code.match(/^\s*$/) || !section.docs.match(/^\s*$/)) sections.push(section);
section = { docs: '', code: '' };
}
inMultiLineComment = true;
multiLine = line + "\n";
continue;
}
}
if(
!this.multiLineOnly &&
params.comment &&
matchable.match(commentRegex) &&
(!params.commentsIgnore || !matchable.match(params.commentsIgnore)) &&
!matchable.match(/#!/)
){
// This is for single-line comments. Again, store away the last section and start a new one
if(section.code){
if(!section.code.match(/^\s*$/) || !section.docs.match(/^\s*$/)) sections.push(section);
section = { docs: '', code: '' };
}
section.docs += line.replace(commentRegex, '') + '\n';
}else if(!params.commentsIgnore || !line.match(params.commentsIgnore)){
// If this is the first line of active code, store it in the section
// so we can grab it for line numbers later
if(!section.firstCodeLine){
section.firstCodeLine = i + 1;
}
section.code += line + '\n';
}
}
sections.push(section);
return sections;
};
/**
* ## Docker.prototype.parseMultline
*
* Parse a multiline comment for jsDoc à la [dox](https://github.com/visionmedia/dox)
*
* @param {string} comment The comment to parse
* @return {object} Object containing parsed comment data
*/
Docker.prototype.parseMultiline = function(comment){
var commentData = { tags: [], description: {} };
if(!/^\s*@/.test(comment)){
// Split out a summary and body from the comment
var full = comment.split('\n@')[0];
commentData.description.summary = full.split(/\n\s*\n\s*/)[0];
commentData.description.body = full.split(/\n\s*\n\s*/).slice(1).join('\n\n');
}else{
// If the comment starts with a tag, do nothing
commentData.description.summary = '';
commentData.description.body = '';
}
// grabType function grabs the type out of an array of space-separated
// bits, so for example we can pick up {string, optional} from the beginning
// of a tag. `bits` is passed in as an array so we can shift and unshift
// to remove the type from it.
function grabType(bits){
var type = bits.shift();
var badChars = /[&<>"'`]/g;
var escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
// Carry on adding bits until we reach a closing brace
while(bits.length && type.indexOf('}') === -1) type += bits.shift();
// If for whatever reason the tag was of the format {type}blah without
// the trailing space after the }, extract whatever was left over and
// put it back onto the bits array.
if(!/\}$/.test(type)){
bits.unshift(type.replace(/^.*\}(.*)$/, '$1'));
type = type.replace(/\}.*$/,'}');
}
function escapeChar(chr) {
return escape[chr] || "&";
}
type = type.replace(badChars, escapeChar);
return type.replace(/[{}]/g,'');
}
// Prepend a newline here in case the comment starts with a tag
comment = '\n' + comment;
// If we have jsDoc-style parameters, parse them
if(comment.indexOf('\n@') !== -1){
var tags = comment.split('\n@').slice(1);
// Loop through all of the tags and process the ones we support
commentData.tags = tags.map(function(line){
var bits = line.split(' '), tag = {};
var tagType = tag.type = bits.shift();
switch(tagType){
case 'arg':
case 'argument':
case 'param':
// `@param {typename} paramname Parameter description`
if(bits[0].charAt(0) == '{') tag.types = grabType(bits).split(/ *[|,\/] */);
tag.name = bits.shift() || '';
tag.description = bits.join(' ');
tag.type = 'param';
break;
case 'returns':
case 'return':
// `@return {typename} Return description`
if(bits[0].charAt(0) == '{') tag.types = grabType(bits).split(/ *[|,\/] */);
tag.description = bits.join(' ');
tag.type = 'return';
break;
case 'type':
// `@type {typename}`
tag.types = grabType(bits).split(/ *[|,\/] */);
break;
case 'access':
case 'api':
// `@api public` or `@api private` etc.
tag.visibility = bits.shift();
tag.type = 'api';
break;
case 'private':
case 'protected':
case 'public':
// `@public` or `@private` etc.
tag.visibility = tagType;
tag.type = 'api';
break;
case 'see':
// `@see Title http://url` or `@see local place`
if(/http/.test(line)){
tag.title = bits.length > 1 ? bits.shift() : '';
tag.url = bits.join(' ');
}else{
tag.local = bits.join(' ');
}
break;
default:
if(bits.length > 0 && bits[0].charAt(0) == '{') tag.types = grabType(bits).split(/ *[|,\/] */);
tag.description = bits.join(' ');
tag.name = tagType;
tag.type = 'unknown';
}
return tag;
});
}
return commentData;
};
/**
* ## Docker.prototype.outdent
*
* Attempts to automatically detect indented lines in multiline comments
* and bring them back to normal indentation level. This is to avoid markdown
* picking up indented lines and thinking they're code
*
* @param {string} code The code to attempt to outdent
* @return {string} Outdented code
*/
Docker.prototype.outdent = function(code){
var lines = code.split('\n');
var tabWidth = 2;
var smallestIndent = Infinity;
// Loop through all the lines, finding the least-indented of all of them
for(var i = 0; i < lines.length; i += 1){
var line = lines[i].replace(/\t/g, Array(tabWidth+1).join(' '));
if(/^\s$/.test(line)) continue;
var lineIndent = 0;
while(line.length && line.charAt(0) == ' '){
line = line.slice(1);
lineIndent += 1;
}
// If the line consists entirely of whitespace, don't factor it into
// the calculation (editors that trim trailing whitespace may make the
// line shorter)
if(line.length) smallestIndent = Math.min(lineIndent, smallestIndent);
}
// This should only happen if the input code was entirely
// whitespace, which should never be the case
if(!isFinite(smallestIndent)) smallestIndent = 0;
// Now loop over lines again and outdent them by the largest possible amount
var outLines = [];
for(var j = 0; j < lines.length; j += 1){
var line = lines[j].replace(/\t/g, Array(tabWidth+1).join(' '));
// If the line was smaller than the smallestIndent it's because
// it was entirely whitespace anyway, so we're safe to do this.
outLines.push(line.substr(smallestIndent));
}
return outLines.join('\n');
};
/**
* ## Docker.prototype.languageParams
*
* Provides language-specific params for a given file name.
*
* @param {string} filename The name of the file to test
* @param {string} filedata The contents of the file (to check for shebang)
* @return {object} Object containing all of the language-specific params
*/
Docker.prototype.languageParams = function(filename, filedata){
// First try to detect the language from the file extension
var ext = path.extname(filename);
ext = ext.replace(/^\./, '');
// Bit of a hacky way of incorporating .C for C++
if(ext === '.C') return 'cpp';
ext = ext.toLowerCase();
var base = path.basename(filename);
base = base.toLowerCase();
for(var i in this.languages){
if(!this.languages.hasOwnProperty(i)) continue;
if(this.languages[i].extensions &&
this.languages[i].extensions.indexOf(ext) !== -1) return i;
if(this.languages[i].names &&
this.languages[i].names.indexOf(base) !== -1) return i;
}
// If that doesn't work, see if we can grab a shebang
var shebangRegex = /^\n*#!\s*(?:\/usr\/bin\/env)?\s*(?:[^\n]*\/)*([^\/\n]+)(?:\n|$)/;
var match = shebangRegex.exec(filedata);
if(match){
for(var j in this.languages){
if(!this.languages.hasOwnProperty(j)) continue;
if(this.languages[j].executables && this.languages[j].executables.indexOf(match[1]) !== -1) return j;
}
}
// If we still can't figure it out, give up and return false.
return false;
};
// The language params can have the following keys:
//
// * `name`: Name of Pygments lexer to use
// * `comment`: String flag for single-line comments
// * `multiline`: Two-element array of start and end flags for block comments
// * `commentsIgnore`: Regex of comments to strip completely (don't even doc)
// * `jsDoc`: Whether to parse multiline comments as jsDoc
// * `type`: Either `'code'` (default) or `'markdown'` - format of page to render
// * `literals`: Array of match/replace pairs for literals to ignore for comment matching
//
// I'm not even going to pretend that this is an exhaustive list of
// languages that Pygments can understand. This is just a list of the most
// common ones I think are necessary. If you can think of another that
// might be useful, and can find it on the [Pygments lexer page](http://pygments.org/docs/lexers/),
// then let me know and I'll add it in
Docker.prototype.languages = {
javascript: {
extensions: [ 'js' ],
executables: [ 'node' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], commentsIgnore: /^\s*\/\/=/, jsDoc: true,
literals: [
[ /\/(?![\*\/])((?:[^\\\/]|(?:\\\\)*?\\[^\\])*?)\//g, '/./' ]
]
},
coffeescript: {
extensions: [ 'coffee' ],
names: [ 'cakefile' ],
executables: [ 'coffee' ],
comment: '#', multiLine: [ /^\s*#{3}\s*$/m, /^\s*#{3}\s*$/m ], jsDoc: true,
literals: [
[ /\/(?![\*\/])((?:[^\\\/]|(?:\\\\)*?\\[^\\])*?)\//g, '/./' ]
]
},
livescript: {
extensions: [ 'ls' ],
executables: [ 'lsc' ],
comment: '#', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
ruby: {
extensions: [ 'rb', 'rbw', 'rake', 'gemspec' ],
executables: [ 'ruby' ],
names: [ 'rakefile' ],
comment: '#', multiLine: [ /\=begin/, /\=end/ ]
},
python: {
extensions: [ 'py' ],
executables: [ 'python' ],
comment: '#' // Python has no block commments :-(
},
perl: {
extensions: [ 'pl', 'pm' ],
executables: [ 'perl' ],
comment: '#' // Nor (really) does perl.
},
c: {
extensions: [ 'c', 'h' ],
executables: [ 'gcc' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
cpp: {
extensions: [ 'cc', 'cpp' ],
executables: [ 'g++' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
vbnet: {
extensions: [ 'vb', 'vbs', 'bas' ],
comment: "'" // No multiline
},
'aspx-vb': {
extensions: [ 'asp', 'aspx', 'asax', 'ascx', 'ashx', 'asmx', 'axd' ],
comment: "'" // No multiline
},
csharp: {
extensions: [ 'cs' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
'aspx-cs': {
extensions: [ 'aspx', 'asax', 'ascx', 'ashx', 'asmx', 'axd' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
java: {
extensions: [ 'java' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
php: {
extensions: [ 'php', 'php3', 'php4', 'php5' ],
executables: [ 'php' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
actionscript: {
extensions: [ 'as' ],
comment: '//', multiLine: [ /\/\*/, /\*\// ]
},
sh: {
extensions: [ 'sh', 'kst', 'bash' ],
names: [ '.bashrc', 'bashrc' ],
executables: [ 'bash', 'sh', 'zsh' ],
comment: '#'
},
yaml: {
extensions: [ 'yaml', 'yml' ],
comment: '#'
},
markdown: {
extensions: [ 'md', 'mkd', 'markdown' ],
type: 'markdown'
},
sass: {
extensions: [ 'sass' ],
comment: '//' //, multiLine: [ /\/\*/, /\*\// ]
},
scss: {
extensions: [ 'scss' ],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
make: {
names: [ 'makefile' ],
comment: '#'
},
apache: {
names: [ '.htaccess', 'apache.conf', 'apache2.conf' ],
comment: '#'
},
jade: {
extensions: ['jade'],
comment: '//-?', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
groovy: {
extensions: ['groovy'],
comment: '//', multiLine: [ /\/\*\*?/, /\*\// ], jsDoc: true
},
gsp: {
extensions: [ 'gsp' ],
//comment: '//', gsp only supports multiline comments.
multiLine: [ /<%--/, /--%>/ ],
pygment: "html"// .gsp is grails server pages in pygments, html is close enough.
},
styl: {
extensions: [ 'styl' ],
comment: '//', multiLine: [ /\/\*/, /\*\// ],
pygment: "sass"// .styl isn't supported by pygments, sass is close enough.
},
css: {
extensions: [ 'css' ],
multiLine: [ /\/\*/, /\*\// ], // for when we detect multi-line comments
commentStart: '/*', commentEnd: '*/' // for when we add multi-line comments
},
html: {
extensions: [ 'html', 'htm' ],
multiLine: [ /<!--/, /-->/ ],
commentStart: '<!--', commentEnd: '-->'
}
};
/**
* ## Docker.prototype.pygments
*
* Runs a given block of code through pygments
*
* @param {string} data The code to give to Pygments
* @param {string} language The name of the Pygments lexer to use
* @param {function} cb Callback to fire with Pygments output