JSDOC/BuildDocs.js
[gnome.introspection-doc-generator] / JSDOC / BuildDocs.js
1 //<script type="text/javascript">
2 /**
3         This is the main container for the JSDOC application.
4         @namespace
5 */
6 Gio = imports.gi.Gio;
7
8 XObject = imports.XObject.XObject;
9 File = imports.File.File;
10
11 Template = imports.JsTemplate.Template.Template;
12 Link = imports.JsTemplate.Link.Link; // ?? fixme!??
13
14 Parser      = imports.Parser.Parser;
15 TextStream  = imports.TextStream.TextStream;
16 TokenReader = imports.TokenReader.TokenReader;
17 TokenStream = imports.TokenStream.TokenStream;
18 Symbol      = imports.Symbol.Symbol;
19 DocComment  = imports.DocComment.DocComment;
20
21  
22 // should not realy be here -- or anywhere...??
23
24 function makeSortby(attribute) {
25     return function(a, b) {
26         if (a[attribute] != undefined && b[attribute] != undefined) {
27             a = a[attribute]; //.toLowerCase();
28             b = b[attribute];//.toLowerCase();
29             if (a < b) return -1;
30             if (a > b) return 1;
31             return 0;
32         }
33     }
34 }
35
36 Options = false; // refer to this everywhere!
37
38
39 BuildDocs = {
40     
41     VERSION : "2.0.0",
42     
43     
44     srcFiles : [],
45     
46     
47     build : function (opts)
48     {
49         Options = opts; 
50         Options.init();
51         
52         Options.LOG.inform("JsDoc Toolkit main() running at "+new Date()+".");
53         //Options.LOG.inform("With options: ");
54         
55         if (Options.cacheDirectory.length && !File.isDirectory(Options.cacheDirectory)) {   
56             File.mkdir(Options.cacheDirectory)
57         }
58         
59         Options.srcFiles = this._getSrcFiles();
60         this._parseSrcFiles();
61         this.symbolSet = Parser.symbols;
62         
63         // this currently uses the concept of publish.js...
64         
65         this.publish();
66          
67         
68         
69     },
70     /**
71      * create a list of files in this.srcFiles using list of directories / files in Options.src
72      * 
73      */
74     
75     _getSrcFiles : function() 
76     {
77         this.srcFiles = [];
78         var _this = this;
79         var ext = ["js"];
80         if (Options.ext) {
81             ext = Options.ext.split(",").map(function($) {return $.toLowerCase()});
82         }
83         
84         for (var i = 0; i < Options.src.length; i++) {
85             // add to sourcefiles..
86             
87             File.list(Options.src[i] ).forEach(function($) {
88                 if (Options['exclude-src'].indexOf($) > -1) {
89                     return;
90                 }
91                 var thisExt = $.split(".").pop().toLowerCase();
92                 if (ext.indexOf(thisExt) < 0) {
93                     return;
94                 }
95                 _this.srcFiles.push(Options.src[i] + '/' + $);
96             });
97                 
98         }
99         //Seed.print(JSON.stringify(this.srcFiles, null,4));Seed.quit();
100         return this.srcFiles;
101     },
102     /**
103      * Parse the source files.
104      * 
105      */
106
107     _parseSrcFiles : function() 
108     {
109         Parser.init();
110         
111         for (var i = 0, l = this.srcFiles.length; i < l; i++) {
112             
113             var srcFile = this.srcFiles[i];
114             
115             
116             var cacheFile = !Options.cacheDirectory.length ? false : 
117                 Options.cacheDirectory + srcFile.replace(/\//g, '_') + ".cache";
118             
119             //print(cacheFile);
120             // disabled at present!@!!
121             
122             if (cacheFile  && File.exists(cacheFile)) {
123                 // check filetime?
124                 
125                 var c_mt = File.mtime(cacheFile);
126                 var o_mt = File.mtime(srcFile);
127                 //println(c_mt.toSource());
128                // println(o_mt.toSource());
129                
130                 // this check does not appear to work according to the doc's - need to check it out.
131                
132                 if (c_mt > o_mt) { // cached time  > original time!
133                     // use the cached mtimes..
134                     var syms =  JSON.parse(File.read(cacheFile), function(k, v) {
135                         if (typeof(v) != 'object') {
136                             return v;
137                         }
138                         if (typeof(v._object) == 'undefined') {
139                             return v;
140                         }
141                         var cls = imports[v._object];
142                         delete v._object;
143                         var ret = new cls();
144                         XObject.extend(ret, v);
145                         return ret;
146                     });
147                      
148                     for (var sy in syms) {
149                         //println("ADD:" + sy );
150                        Parser.symbols.addSymbol(syms[sy]);
151                     }
152                     continue;
153                 }
154             }
155             
156             var src = ''
157             try {
158                 Options.LOG.inform("reading : " + srcFile);
159                 src = File.read(srcFile);
160             }
161             catch(e) {
162                 Options.LOG.warn("Can't read source file '"+srcFile+"': "+e.message);
163                 continue;
164             }
165
166             var txs = new TextStream(src);
167             
168             var tr = new TokenReader({ keepComments : true, keepWhite : true , sepIdents: false });
169             
170             var ts = new TokenStream(tr.tokenize(txs));
171         
172             Parser.parse(ts, srcFile);
173             
174             if (cacheFile) {
175                 File.write(cacheFile,
176                   JSON.stringify(
177                     Parser.symbolsToObject(srcFile),
178                     null,2
179                   )
180                 );
181             
182             }
183             //var outstr = JSON.stringify(
184             //    Parser.filesSymbols[srcFile]._index
185             //);
186             //File.write(cacheFile, outstr);
187              
188                 
189     //          }
190         }
191         
192         
193         
194         Parser.finish();
195     },
196     
197      
198         
199     publish  : function() {
200         Options.LOG.inform("Publishing");
201          
202         // link!!!
203         
204         
205         Options.LOG.inform("Making directories");
206         if (!File.isDirectory(Options.target))
207             File.mkdir(Options.target);
208         if (!File.isDirectory(Options.target+"/symbols"))
209             File.mkdir(Options.target+"/symbols");
210         if (!File.isDirectory(Options.target+"/symbols/src"))
211             File.mkdir(Options.target+"/symbols/src");
212         
213         if (!File.isDirectory(Options.target +"/json")) {
214             File.mkdir(Options.target +"/json");
215         }
216         
217         Options.LOG.inform("Copying files from static: " +Options.templateDir);
218         // copy everything in 'static' into 
219         File.list(Options.templateDir + '/static').forEach(function (f) {
220             Options.LOG.inform("Copy " + Options.templateDir + '/static/' + f + ' to  ' + Options.target + '/' + f);
221             File.copyFile(Options.templateDir + '/static/' + f, Options.target + '/' + f,  Gio.FileCopyFlags.OVERWRITE);
222         });
223         
224         
225         Options.LOG.inform("Setting up templates");
226         // used to check the details of things being linked to
227         Link.symbolSet = this.symbolSet;
228         Link.base = "../";
229         
230         Link.srcFileFlatName = this.srcFileFlatName;
231         Link.srcFileRelName = this.srcFileRelName;
232         
233         var classTemplate = new Template({
234              templateFile : Options.templateDir  + "/class.html",
235              Link : Link
236         });
237         var classesTemplate = new Template({
238             templateFile : Options.templateDir +"/allclasses.html",
239             Link : Link
240         });
241         var classesindexTemplate = new Template({
242             templateFile : Options.templateDir +"/index.html",
243             Link : Link
244         });
245         var fileindexTemplate = new Template({   
246             templateFile : Options.templateDir +"/allfiles.html",
247             Link: Link
248         });
249
250         
251         classTemplate.symbolSet = this.symbolSet;
252         
253         
254         function hasNoParent($) {
255             return ($.memberOf == "")
256         }
257         function isaFile($) {
258             return ($.is("FILE"))
259         }
260         function isaClass($) { 
261             return ($.is("CONSTRUCTOR") || $.isNamespace); 
262         }
263         
264         
265         
266         
267         
268         
269         
270         
271         
272         
273         var symbols = this.symbolSet.toArray();
274         
275         var files = Options.srcFiles;
276         
277         for (var i = 0, l = files.length; i < l; i++) {
278             var file = files[i];
279             var targetDir = Options.target + "/symbols/src/";
280             this.makeSrcFile(file, targetDir);
281         }
282         
283         var classes = symbols.filter(isaClass).sort(makeSortby("alias"));
284          
285          //Options.LOG.inform("classTemplate Process : all classes");
286             
287        // var classesIndex = classesTemplate.process(classes); // kept in memory
288         
289         Options.LOG.inform("iterate classes");
290         
291         var jsonAll = {}; 
292         
293         for (var i = 0, l = classes.length; i < l; i++) {
294             var symbol = classes[i];
295             var output = "";
296             
297             Options.LOG.inform("classTemplate Process : " + symbol.alias);
298             
299             
300             
301             
302             File.write(Options.target+"/symbols/" +symbol.alias+'.' + Options.publishExt ,
303                     classTemplate.process(symbol));
304             
305             jsonAll[symbol.alias] = this.publishJSON(symbol);
306             
307             
308             
309         }
310         
311         File.write(Options.target+"/json/roodata.json",
312                 JSON.stringify({
313                     success : true,
314                     data : jsonAll
315                 }, null, 1)
316         );
317         
318         
319         // regenrate the index with different relative links
320         Link.base = "";
321         //var classesIndex = classesTemplate.process(classes);
322         
323         Options.LOG.inform("build index");
324         
325         File.write(Options.target +  "/index."+ Options.publishExt, 
326             classesindexTemplate.process(classes)
327         );
328         
329         // blank everything???? classesindexTemplate = classesIndex = classes = null;
330         
331  
332         
333         var documentedFiles = symbols.filter(function ($) {
334             return ($.is("FILE"))
335         });
336         
337         var allFiles = [];
338         
339         for (var i = 0; i < files.length; i++) {
340             allFiles.push(new  Symbol(files[i], [], "FILE", new DocComment("/** */")));
341         }
342         
343         for (var i = 0; i < documentedFiles.length; i++) {
344             var offset = files.indexOf(documentedFiles[i].alias);
345             allFiles[offset] = documentedFiles[i];
346         }
347             
348         allFiles = allFiles.sort(makeSortby("name"));
349         Options.LOG.inform("write files index");
350         
351         File.write(Options.target + "/files."+Options.publishExt, 
352             fileindexTemplate.process(allFiles)
353         );
354         
355         
356         
357         
358     },
359     /**
360      * JSON files are lookup files for the documentation
361      * - can be used by IDE's or AJAX based doc tools
362      * 
363      * 
364      */
365     publishJSON : function(data)
366     {
367         // what we need to output to be usefull...
368         // a) props..
369         var cfgProperties = [];
370         if (!data.comment.getTag('singleton').length) {
371             cfgProperties = data.configToArray();
372             cfgProperties = cfgProperties.sort(makeSortby("alias"));
373             
374         }
375         var props = []; 
376         //println(cfgProperties.toSource());
377         var p ='';
378         for(var i =0; i < cfgProperties.length;i++) {
379             p = cfgProperties[i];
380             props.push( {
381                 name : p.name,
382                 type : p.type,
383                 desc : p.desc,
384                 memberOf : p.memberOf == data.alias ? '' : p.memberOf
385             });
386         }
387         
388          
389         var ownEvents = data.methods.filter( function(e){
390                 return e.isEvent && !e.comment.getTag('hide').length;
391             }).sort(makeSortby("name"));
392              
393         
394         var events = [];
395         var m;
396         for(var i =0; i < ownEvents.length;i++) {
397             m = ownEvents[i];
398             events.push( {
399                 name : m.name.substring(1),
400                 sig : this.makeFuncSkel(m.params),
401                 type : 'function',
402                 desc : m.desc
403             });
404         }
405         //println(props.toSource());
406         // we need to output:
407         //classname => {
408         //    propname => 
409         //        type=>
410         //        desc=>
411         //    }
412
413         var ret = {
414             props : props,
415             events: events
416         };
417         return ret;
418         
419         
420         
421         // b) methods
422         // c) events
423         
424         
425     },
426     srcFileRelName : function(sourceFile)
427     {
428       return sourceFile.substring(Options.baseDir.length+1);
429     },
430     srcFileFlatName: function(sourceFile)
431     {
432         var name = this.srcFileRelName(sourceFile);
433         name = name.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
434         return name.replace(/\:/g, "_") + '.html'; //??;
435         
436     },
437     
438     makeSrcFile: function(sourceFile) 
439     {
440         // this stuff works...
441      
442         
443         var name = this.srcFileFlatName(sourceFile);
444         
445         Options.LOG.inform("Write Source file : " + Options.target+"/symbols/src/" + name);
446         var pretty = imports.PrettyPrint.toPretty(File.read(  sourceFile));
447         File.write(Options.target+"/symbols/src/" + name, 
448             '<html><head>' +
449             '<title>' + sourceFile + '</title>' +
450             '<link rel="stylesheet" type="text/css" href="../../../css/highlight-js.css"/>' + 
451             '</head><body class="highlightpage">' +
452             pretty +
453             '</body></html>');
454     },
455     /**
456      * used by JSON output to generate a function skeleton
457      */
458     makeFuncSkel :function(params) {
459         if (!params) return "function ()\n{\n\n}";
460         return "function ("     +
461             params.filter(
462                 function($) {
463                     return $.name.indexOf(".") == -1; // don't show config params in signature
464                 }
465             ).map( function($) { return $.name == 'this' ? '_self' : $.name; } ).join(", ") +
466         ")\n{\n\n}";
467     }
468         
469  
470     
471 };
472   
473
474
475
476
477
478  
479
480
481
482