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][v._object];
142                         print(v._object);
143                         delete v._object;
144                         var ret = new cls();
145                         XObject.extend(ret, v);
146                         return ret;
147                     });
148                      
149                     for (var sy in syms) {
150                         //println("ADD:" + sy );
151                        Parser.symbols.addSymbol(syms[sy]);
152                     }
153                     continue;
154                 }
155             }
156             
157             var src = ''
158             try {
159                 Options.LOG.inform("reading : " + srcFile);
160                 src = File.read(srcFile);
161             }
162             catch(e) {
163                 Options.LOG.warn("Can't read source file '"+srcFile+"': "+e.message);
164                 continue;
165             }
166
167             var txs = new TextStream(src);
168             
169             var tr = new TokenReader({ keepComments : true, keepWhite : true , sepIdents: false });
170             
171             var ts = new TokenStream(tr.tokenize(txs));
172         
173             Parser.parse(ts, srcFile);
174             
175             if (cacheFile) {
176                 File.write(cacheFile,
177                   JSON.stringify(
178                     Parser.symbolsToObject(srcFile),
179                     null,2
180                   )
181                 );
182             
183             }
184             //var outstr = JSON.stringify(
185             //    Parser.filesSymbols[srcFile]._index
186             //);
187             //File.write(cacheFile, outstr);
188              
189                 
190     //          }
191         }
192         
193         
194         
195         Parser.finish();
196     },
197     
198      
199         
200     publish  : function() {
201         Options.LOG.inform("Publishing");
202          
203         // link!!!
204         
205         
206         Options.LOG.inform("Making directories");
207         if (!File.isDirectory(Options.target))
208             File.mkdir(Options.target);
209         if (!File.isDirectory(Options.target+"/symbols"))
210             File.mkdir(Options.target+"/symbols");
211         if (!File.isDirectory(Options.target+"/symbols/src"))
212             File.mkdir(Options.target+"/symbols/src");
213         
214         if (!File.isDirectory(Options.target +"/json")) {
215             File.mkdir(Options.target +"/json");
216         }
217         
218         Options.LOG.inform("Copying files from static: " +Options.templateDir);
219         // copy everything in 'static' into 
220         File.list(Options.templateDir + '/static').forEach(function (f) {
221             Options.LOG.inform("Copy " + Options.templateDir + '/static/' + f + ' to  ' + Options.target + '/' + f);
222             File.copyFile(Options.templateDir + '/static/' + f, Options.target + '/' + f,  Gio.FileCopyFlags.OVERWRITE);
223         });
224         
225         
226         Options.LOG.inform("Setting up templates");
227         // used to check the details of things being linked to
228         Link.symbolSet = this.symbolSet;
229         Link.base = "../";
230         
231         Link.srcFileFlatName = this.srcFileFlatName;
232         Link.srcFileRelName = this.srcFileRelName;
233         
234         var classTemplate = new Template({
235              templateFile : Options.templateDir  + "/class.html",
236              Link : Link
237         });
238         var classesTemplate = new Template({
239             templateFile : Options.templateDir +"/allclasses.html",
240             Link : Link
241         });
242         var classesindexTemplate = new Template({
243             templateFile : Options.templateDir +"/index.html",
244             Link : Link
245         });
246         var fileindexTemplate = new Template({   
247             templateFile : Options.templateDir +"/allfiles.html",
248             Link: Link
249         });
250
251         
252         classTemplate.symbolSet = this.symbolSet;
253         
254         
255         function hasNoParent($) {
256             return ($.memberOf == "")
257         }
258         function isaFile($) {
259             return ($.is("FILE"))
260         }
261         function isaClass($) { 
262             return ($.is("CONSTRUCTOR") || $.isNamespace); 
263         }
264         
265         
266         
267         
268         
269         
270         
271         
272         
273         
274         var symbols = this.symbolSet.toArray();
275         
276         var files = Options.srcFiles;
277         
278         for (var i = 0, l = files.length; i < l; i++) {
279             var file = files[i];
280             var targetDir = Options.target + "/symbols/src/";
281             this.makeSrcFile(file, targetDir);
282         }
283         
284         var classes = symbols.filter(isaClass).sort(makeSortby("alias"));
285          
286          //Options.LOG.inform("classTemplate Process : all classes");
287             
288        // var classesIndex = classesTemplate.process(classes); // kept in memory
289         
290         Options.LOG.inform("iterate classes");
291         
292         var jsonAll = {}; 
293         
294         for (var i = 0, l = classes.length; i < l; i++) {
295             var symbol = classes[i];
296             var output = "";
297             
298             Options.LOG.inform("classTemplate Process : " + symbol.alias);
299             
300             
301             
302             
303             File.write(Options.target+"/symbols/" +symbol.alias+'.' + Options.publishExt ,
304                     classTemplate.process(symbol));
305             
306             jsonAll[symbol.alias] = this.publishJSON(symbol);
307             
308             
309             
310         }
311         
312         File.write(Options.target+"/json/roodata.json",
313                 JSON.stringify({
314                     success : true,
315                     data : jsonAll
316                 }, null, 1)
317         );
318         
319         
320         // regenrate the index with different relative links
321         Link.base = "";
322         //var classesIndex = classesTemplate.process(classes);
323         
324         Options.LOG.inform("build index");
325         
326         File.write(Options.target +  "/index."+ Options.publishExt, 
327             classesindexTemplate.process(classes)
328         );
329         
330         // blank everything???? classesindexTemplate = classesIndex = classes = null;
331         
332  
333         
334         var documentedFiles = symbols.filter(function ($) {
335             return ($.is("FILE"))
336         });
337         
338         var allFiles = [];
339         
340         for (var i = 0; i < files.length; i++) {
341             allFiles.push(new  Symbol(files[i], [], "FILE", new DocComment("/** */")));
342         }
343         
344         for (var i = 0; i < documentedFiles.length; i++) {
345             var offset = files.indexOf(documentedFiles[i].alias);
346             allFiles[offset] = documentedFiles[i];
347         }
348             
349         allFiles = allFiles.sort(makeSortby("name"));
350         Options.LOG.inform("write files index");
351         
352         File.write(Options.target + "/files."+Options.publishExt, 
353             fileindexTemplate.process(allFiles)
354         );
355         
356         
357         
358         
359     },
360     /**
361      * JSON files are lookup files for the documentation
362      * - can be used by IDE's or AJAX based doc tools
363      * 
364      * 
365      */
366     publishJSON : function(data)
367     {
368         // what we need to output to be usefull...
369         // a) props..
370         var cfgProperties = [];
371         if (!data.comment.getTag('singleton').length) {
372             cfgProperties = data.configToArray();
373             cfgProperties = cfgProperties.sort(makeSortby("alias"));
374             
375         }
376         var props = []; 
377         //println(cfgProperties.toSource());
378         var p ='';
379         for(var i =0; i < cfgProperties.length;i++) {
380             p = cfgProperties[i];
381             props.push( {
382                 name : p.name,
383                 type : p.type,
384                 desc : p.desc,
385                 memberOf : p.memberOf == data.alias ? '' : p.memberOf
386             });
387         }
388         
389          
390         var ownEvents = data.methods.filter( function(e){
391                 return e.isEvent && !e.comment.getTag('hide').length;
392             }).sort(makeSortby("name"));
393              
394         
395         var events = [];
396         var m;
397         for(var i =0; i < ownEvents.length;i++) {
398             m = ownEvents[i];
399             events.push( {
400                 name : m.name.substring(1),
401                 sig : this.makeFuncSkel(m.params),
402                 type : 'function',
403                 desc : m.desc
404             });
405         }
406         //println(props.toSource());
407         // we need to output:
408         //classname => {
409         //    propname => 
410         //        type=>
411         //        desc=>
412         //    }
413
414         var ret = {
415             props : props,
416             events: events
417         };
418         return ret;
419         
420         
421         
422         // b) methods
423         // c) events
424         
425         
426     },
427     srcFileRelName : function(sourceFile)
428     {
429       return sourceFile.substring(Options.baseDir.length+1);
430     },
431     srcFileFlatName: function(sourceFile)
432     {
433         var name = this.srcFileRelName(sourceFile);
434         name = name.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
435         return name.replace(/\:/g, "_") + '.html'; //??;
436         
437     },
438     
439     makeSrcFile: function(sourceFile) 
440     {
441         // this stuff works...
442      
443         
444         var name = this.srcFileFlatName(sourceFile);
445         
446         Options.LOG.inform("Write Source file : " + Options.target+"/symbols/src/" + name);
447         var pretty = imports.PrettyPrint.toPretty(File.read(  sourceFile));
448         File.write(Options.target+"/symbols/src/" + name, 
449             '<html><head>' +
450             '<title>' + sourceFile + '</title>' +
451             '<link rel="stylesheet" type="text/css" href="../../../css/highlight-js.css"/>' + 
452             '</head><body class="highlightpage">' +
453             pretty +
454             '</body></html>');
455     },
456     /**
457      * used by JSON output to generate a function skeleton
458      */
459     makeFuncSkel :function(params) {
460         if (!params) return "function ()\n{\n\n}";
461         return "function ("     +
462             params.filter(
463                 function($) {
464                     return $.name.indexOf(".") == -1; // don't show config params in signature
465                 }
466             ).map( function($) { return $.name == 'this' ? '_self' : $.name; } ).join(", ") +
467         ")\n{\n\n}";
468     }
469         
470  
471     
472 };
473   
474
475
476
477
478
479  
480
481
482
483