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