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