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