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