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