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