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