Changeset 3

Show
Ignore:
Timestamp:
10/18/05 22:14:55 (3 years ago)
Author:
Jan-Klaas Kollhof
Message:

simplifying module import

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • jsolait/trunk/jsolait/jsolait.js

    r2 r3  
    2323    It provides the core functionalities  for creating classes, modules and for importing modules. 
    2424     
    25     @varsion 2.0 
     25    @version 2.0 
    2626    $LastChangedBy$ 
    2727    $Date$ 
     
    232232        publ.module = mod; 
    233233    }) 
    234  
    235     //this is for hooks that need to work with modules before their scope is run 
    236     Module.preScopeExecution(mod); 
    237  
     234     
    238235    try{//to execute the scope of the module 
    239236        moduleScope.call(mod, mod); 
     
    324321    publ.module; 
    325322}) 
    326 ///a hook for other modules to override for customization todo:doc 
    327 Module.preScopeExecution=function(mod){}; 
    328    
     323  
    329324     
    330325/** 
     
    355350    }) 
    356351         
    357      
    358     mod.__import__=function(modName){ 
    359         var modImp = mod.modules[modName]; 
    360         if(modImp !== undefined){ 
    361             return modImp; 
     352        ///The paths of  the modules that come with jsolait. 
     353    mod.modulePaths={codecs:"%(installPath)s/lib/codecs.js", 
     354                                    crypto:"%(installPath)s/lib/crypto.js", 
     355                                    dom:"%(installPath)s/lib/dom.js", 
     356                                    forms:"%(installPath)s/lib/forms.js", 
     357                                    iter:"%(installPath)s/lib/iter.js", 
     358                                    jsonrpc:"%(installPath)s/lib/jsonrpc.js", 
     359                                    lang:"%(installPath)s/lib/lang.js", 
     360                                    sets:"%(installPath)s/lib/sets.js", 
     361                                    testing:"%(installPath)s/lib/testing.js", 
     362                                    urllib:"%(installPath)s/lib/urllib.js", 
     363                                    xml:"%(installPath)s/lib/xml.js", 
     364                                    xmlrpc:"%(installPath)s/lib/xmlrpc.js"}; 
     365     
     366    ///The paths to search for modules 
     367    mod.moduleSearchPaths = ["."]; 
     368     
     369    ///The location where jsolait is installed. 
     370    mod.installPath="./jsolait"; 
     371     
     372    /** 
     373        Creates an HTTP request object for retreiving files. 
     374        @return HTTP request object. 
     375    */ 
     376    var getHTTP=function() { 
     377        var obj; 
     378        try{ //to get the mozilla httprequest object 
     379            obj = new XMLHttpRequest(); 
     380        }catch(e){ 
     381            try{ //to get MS HTTP request object 
     382                obj=new ActiveXObject("Msxml2.XMLHTTP.4.0"); 
     383            }catch(e){ 
     384                try{ //to get MS HTTP request object 
     385                    obj=new ActiveXObject("Msxml2.XMLHTTP"); 
     386                }catch(e){ 
     387                    try{// to get the old MS HTTP request object 
     388                        obj = new ActiveXObject("microsoft.XMLHTTP");  
     389                    }catch(e){ 
     390                        throw new mod.Exception("Unable to get an HTTP request object."); 
     391                    } 
     392                }     
     393            } 
     394        } 
     395        return obj; 
     396    } 
     397     
     398    /** 
     399        Retrieves a file given its URL. 
     400        @param url             The url to load. 
     401        @param headers=[]  The headers to use. 
     402        @return                 The content of the file. 
     403    */ 
     404    mod.loadFile=function(url, headers) {  
     405        //if callback is defined then the operation is done async 
     406        headers = (headers !== undefined) ? headers : []; 
     407        //setup the request 
     408        try{ 
     409            var xmlhttp= getHTTP(); 
     410            xmlhttp.open("GET", url, false); 
     411            for(var i=0;i< headers.length;i++){ 
     412                xmlhttp.setRequestHeader(headers[i][0], headers[i][1]);     
     413            } 
     414            xmlhttp.send(""); 
     415        }catch(e){ 
     416            throw new mod.Exception("Unable to load URL: '%s'.".format(url), e); 
     417        } 
     418        if(xmlhttp.status == 200 || xmlhttp.status == 0){ 
     419            return xmlhttp.responseText; 
    362420        }else{ 
    363             if(mod.modules.moduleLoader){ 
    364                 return mod.modules.moduleLoader.imprt(modName); 
    365             }else{ 
    366                 throw mod.ImportFailed(modName, new mod.Exception("No module loader available")) 
    367             } 
    368         } 
    369     } 
     421             throw new mod.Exception("File not loaded: '%s'.".format(url)); 
     422        } 
     423    } 
     424     
     425     /** 
     426       Imports a module given its name(someModule.someSubModule). 
     427       A module's file location is determined by treating each module name as a directory. 
     428       Only the last one points to a file. 
     429       If the module's URL is not known to jsolait then it will be searched for in jsolait.baseURL which is "." by default. 
     430       @param name   The name of the module to load. 
     431       @return           The module object. 
     432    */ 
     433    mod.__imprt__ = function(name){ 
     434 
     435        if(mod.modules[name]){ //module already loaded 
     436            return mod.modules[name]; 
     437        }else{ 
     438            var src,modPath; 
     439             
     440            //check if jsolait already knows the path of the module 
     441            if(mod.modulePaths[name]){ 
     442                modPath = mod.modulePaths[name].format(mod); 
     443                try{//to load the source of the module 
     444                    src = mod.loadFile(modPath); 
     445                }catch(e){ 
     446                    throw new mod.ImportFailed(name, modPath, e); 
     447                } 
     448            }else{//go through the search path and try loading the module 
     449                var failedPaths=[]; 
     450                for(var i=0;i<mod.moduleSearchPaths.length; i++){ 
     451                    modPath = "%s/%s.js".format(mod.moduleSearchPaths[i], name.split(".").join("/")); 
     452                    try{ 
     453                        src = mod.loadFile(modPath); 
     454                        break; 
     455                    }catch(e){ 
     456                        failedPaths.push(modPath); 
     457                    } 
     458                } 
     459                if(src == null){ 
     460                    throw new mod.ModuleImportFailed(name, failedPaths, e); 
     461                } 
     462            } 
     463             
     464            try{//interpret the script 
     465                (new Function("",src))(); //todo should it use globalEval ? 
     466            }catch(e){ 
     467                throw new mod.ImportFailed(name, modPath, e); 
     468            } 
     469             
     470            return mod.modules[name];  
     471        } 
     472    }; 
     473     
     474     
     475    /** 
     476        Thrown when a module could not be found. 
     477    **/ 
     478    mod.ImportFailed=Class(mod.Exception, function(publ, supr){ 
     479        /** 
     480            Initializes a new ModuleImportFailed Exception. 
     481            @param name      The name of the module. 
     482            @param modulePath The path or a list of paths jsolait tried to load the modules from 
     483            @param trace      The error cousing this Exception. 
     484        **/ 
     485        publ.__init__=function(moduleName, modulePath, trace){ 
     486            supr(this).__init__("Failed to import module: '%s' from:\n%s".format(moduleName, modulePath), trace); 
     487            this.moduleName = moduleName; 
     488            this.modulePath = modulePath; 
     489        } 
     490        ///The  name of the module that was not found. 
     491        publ.moduleName; 
     492        ///The path or a list of paths jsolait tried to load the modules from. 
     493        publ.modulePath; 
     494    }) 
    370495     
    371496    /** 
     
    375500        @return           The module object. 
    376501    **/ 
    377     mod.imprt = function(name){ 
    378         return mod.__import__(name); 
    379     } 
    380      
    381502    imprt = function(name){ 
    382         return mod.imprt(name); 
     503        return mod.__imprt__(name); 
    383504    } 
    384505     
     
    626747         
    627748    } 
    628 }) 
    629  
    630 //--------------------------------------------Module loader-------------------------------------------- 
    631  
    632  
    633 Module("moduleLoader", "$Revision$", function(mod){ 
    634      
    635     ///The paths to search for modules 
    636     mod.moduleSearchPaths = ["."]; 
    637      
    638     ///The location where jsolait is installed. 
    639     mod.installPath="./jsolait"; 
    640      
    641     ///The paths of  the modules that come with jsolait. 
    642     var modulePathMap={codecs:"%(installPath)s/lib/codecs.js", 
    643                                     crypto:"%(installPath)s/lib/crypto.js", 
    644                                     dom:"%(installPath)s/lib/dom.js", 
    645                                     forms:"%(installPath)s/lib/forms.js", 
    646                                     iter:"%(installPath)s/lib/iter.js", 
    647                                     jsonrpc:"%(installPath)s/lib/jsonrpc.js", 
    648                                     lang:"%(installPath)s/lib/lang.js", 
    649                                     sets:"%(installPath)s/lib/sets.js", 
    650                                     testing:"%(installPath)s/lib/testing.js", 
    651                                     urllib:"%(installPath)s/lib/urllib.js", 
    652                                     xml:"%(installPath)s/lib/xml.js", 
    653                                     xmlrpc:"%(installPath)s/lib/xmlrpc.js"}                                       
    654      
    655     /** 
    656        Imports a module given its name(someModule.someSubModule). 
    657        A module's file location is determined by treating each module name as a directory. 
    658        Only the last one points to a file. 
    659        If the module's URL is not known to jsolait then it will be searched for in jsolait.baseURL which is "." by default. 
    660        @param name   The name of the module to load. 
    661        @return           The module object. 
    662     */ 
    663     mod.imprt = function(name){ 
    664  
    665         if (jsolait.modules[name]){ //module already loaded 
    666             return mod.modules[name]; 
    667         }else{ 
    668             var src,modPath; 
    669              
    670             //check if jsolait already knows the path of the module 
    671             if(modulePathMap[name]){ 
    672                 modPath = modulePathMap[name].format(mod); 
    673                 try{//to load the source of the module 
    674                     src = getFile(modPath); 
    675                 }catch(e){ 
    676                     throw new mod.ImportFailed(name, modPath, e); 
    677                 } 
    678             }else{//go through the search path and try loading the module 
    679                 var failedPaths=[]; 
    680                 for(var i=0;i<mod.moduleSearchPaths.length; i++){ 
    681                     modPath = "%s/%s.js".format(mod.moduleSearchPaths[i], name.split(".").join("/")); 
    682                     try{ 
    683                         src = getFile(modPath); 
    684                         break; 
    685                     }catch(e){ 
    686                         failedPaths.push(modPath); 
    687                     } 
    688                 } 
    689                 if(src == null){ 
    690                     throw new mod.ModuleImportFailed(name, failedPaths, e); 
    691                 } 
    692             } 
    693              
    694             try{//interpret the script 
    695                 (new Function("",src))(); //todo should it use globalEval ? 
    696             }catch(e){ 
    697                 throw new mod.ImportFailed(name, modPath, e); 
    698             } 
    699              
    700             return jsolait.__import__(name);  
    701         } 
    702     }  
    703      
    704     /** 
    705         Thrown when a module could not be found. 
    706     **/ 
    707     mod.ImportFailed=Class(mod.Exception, function(publ, supr){ 
    708         /** 
    709             Initializes a new ModuleImportFailed Exception. 
    710             @param name      The name of the module. 
    711             @param modulePath The path or a list of paths jsolait tried to load the modules from 
    712             @param trace      The error cousing this Exception. 
    713         **/ 
    714         publ.__init__=function(moduleName, modulePath, trace){ 
    715             supr(this).__init__("Failed to import module: '%s' from:\n%s".format(moduleName, modulePath), trace); 
    716             this.moduleName = moduleName; 
    717             this.modulePath = modulePath; 
    718         } 
    719         ///The  name of the module that was not found. 
    720         publ.moduleName; 
    721         ///The path or a list of paths jsolait tried to load the modules from. 
    722         publ.modulePath; 
    723     }) 
    724      
    725     /** 
    726         Creates an HTTP request object for retreiving files. 
    727         @return HTTP request object. 
    728     */ 
    729     var getHTTP=function() { 
    730         var obj; 
    731         try{ //to get the mozilla httprequest object 
    732             obj = new XMLHttpRequest(); 
    733         }catch(e){ 
    734             try{ //to get MS HTTP request object 
    735                 obj=new ActiveXObject("Msxml2.XMLHTTP.4.0"); 
    736             }catch(e){ 
    737                 try{ //to get MS HTTP request object 
    738                     obj=new ActiveXObject("Msxml2.XMLHTTP"); 
    739                 }catch(e){ 
    740                     try{// to get the old MS HTTP request object 
    741                         obj = new ActiveXObject("microsoft.XMLHTTP");  
    742                     }catch(e){ 
    743                         throw new mod.Exception("Unable to get an HTTP request object."); 
    744                     } 
    745                 }     
    746             } 
    747         } 
    748         return obj; 
    749     } 
    750      
    751     /** 
    752         Retrieves a file given its URL. 
    753         @param url             The url to load. 
    754         @param headers=[]  The headers to use. 
    755         @return                 The content of the file. 
    756     */ 
    757     var getFile=function(url, headers) {  
    758         //if callback is defined then the operation is done async 
    759         headers = (headers !== undefined) ? headers : []; 
    760         //setup the request 
    761         try{ 
    762             var xmlhttp= getHTTP(); 
    763             xmlhttp.open("GET", url, false); 
    764             for(var i=0;i< headers.length;i++){ 
    765                 xmlhttp.setRequestHeader(headers[i][0], headers[i][1]);     
    766             } 
    767             xmlhttp.send(""); 
    768         }catch(e){ 
    769             throw new mod.Exception("Unable to load URL: '%s'.".format(url), e); 
    770         } 
    771         if(xmlhttp.status == 200 || xmlhttp.status == 0){ 
    772             return xmlhttp.responseText; 
    773         }else{ 
    774              throw new mod.Exception("File not loaded: '%s'.".format(url)); 
    775         } 
    776     } 
    777      
    778     /** 
    779         Loads and interprets a script file. 
    780         @param url  The url of the script to load. 
    781     */ 
    782     mod.loadScript=function(url){ 
    783         var src = getFile(url); 
    784         try{//to interpret the source  
    785             (new Function("",src))(); 
    786         }catch(e){ 
    787             throw new mod.EvalFailed(url, e); 
    788         } 
    789     }   
    790 }) 
    791  
    792  
     749}); 
     750 
     751 
     752 
  • jsolait/trunk/jsolait/jsolait.wsf

    r2 r3  
    3333     
    3434    <script language="JavaScript"> <![CDATA[ 
    35         globalEval=function(){ 
    36             eval(arguments[0]); 
     35     
     36    Module("jsolaitws", "0.0.1", function(mod){ 
     37         
     38             
     39        var fs= new ActiveXObject("Scripting.FileSystemObject"); 
     40        var wshShell= new ActiveXObject("WScript.Shell"); 
     41        var ForReading = 1, ForWriting = 2; 
     42     
     43        ///The paths to search for modules 
     44        jsolait.moduleSearchPaths = [fs.buildPath(fs.getParentFolderName(WScript.scriptFullName),"lib")]; 
     45         
     46        ///The location where jsolait is installed. 
     47        jsolait.installPath = fs.getParentFolderName(WScript.scriptFullName); 
     48           
     49        jsolait.loadFile=function(path){ 
     50            try{ 
     51                var f = fs.GetFile(path); 
     52                var src = f.OpenAsTextStream(ForReading).readall(); 
     53                var pse = Module.preScopeExecution; 
     54                Module.preScopeExecution = function(mod){ 
     55                    mod.__fileName__ = path; 
     56                }; 
     57                return src; 
     58            }catch(e){ 
     59                //Module.preScopeExecution=pse; 
     60                throw new mod.ScriptLoadingFailed(path, e); 
     61            } 
    3762        } 
    3863         
    39     print = function(m){ 
    40         var s=[]; 
    41         for(var i=0;i<arguments.length;i++){ 
    42             s.push(''+arguments[i]); 
     64        print = function(m){ 
     65            var s=[]; 
     66            for(var i=0;i<arguments.length;i++){ 
     67                s.push(''+arguments[i]); 
     68            } 
     69             
     70            WScript.echo(s.join(" ")); 
     71        } 
     72          
     73        pprint=function(m, indent){ 
     74            var m = m.split("\n"); 
     75             
     76            indent =(indent === undefined) ? 0 : indent; 
     77             
     78            if(indent<0){ 
     79                pprint.indent+=indent; 
     80            } 
     81             
     82            var s=[]; 
     83            for(var i=0;i<pprint.indent;i++){ 
     84                s.push(' '); 
     85            } 
     86            s=s.join(''); 
     87            for(var i=0;i<m.length;i++){ 
     88                print(s + m[i]); 
     89            } 
     90             
     91            if(indent>0){ 
     92                pprint.indent += indent; 
     93            } 
     94        } 
     95        pprint.indent=0; 
     96         
     97        Error.prototype.toString=function(){ 
     98            return this.name +": " + this.message; 
     99        } 
     100                 
     101        LogError=1; 
     102        LogWarn=2; 
     103        LogInfo=4; 
     104        Error.prototype.toTraceString=function(){ 
     105            return this.message 
    43106        } 
    44107         
    45         WScript.echo(s.join(" ")); 
     108        log=function(msg, level){ 
     109            level = level==null?LogInfo:level; 
     110            if(typeof msg !="string"){ 
     111                level = LogError; 
     112                 
     113                msg = msg.toTraceString(); 
     114            } 
     115             
     116            if(level & log.level){ 
     117                print(msg); 
     118            } 
     119        } 
     120        log.level = LogInfo | LogWarn | LogError;     
     121         
     122        mod.run=function(){ 
     123            mod.__fileName__ = WScript.scriptFullName; 
     124            jsolait.__fileName__ = WScript.scriptFullName.slice(0,-3) + "js"; 
     125             
     126            if (WScript.arguments.unnamed.length==0){ 
     127                WScript.Arguments.ShowUsage();                                               
     128                return; 
     129            }else{ 
     130                var fileName=fs.getAbsolutePathName(WScript.arguments.unnamed.item(0)); 
     131                //todo:check if file exists 
     132            } 
     133             
     134            //get the base of the file to execute 
     135            var fileBase= fs.getParentFolderName(fileName); 
     136            //make sure the search path is updated to include the fileBase 
     137            jsolait.moduleSearchPaths.push(fileBase); 
     138             
     139            //change working dir to the file's location 
     140            //todo:is it OK to change cwd? 
     141            wshShell.currentDirectory = fileBase; 
     142             
     143             
     144            if(WScript.arguments.named.exists("compile")){ 
     145                var lang = imprt('lang'); 
     146                 
     147                var s = jsolait.loadFile(fileName); 
     148                var p = new lang.Parser(s); 
     149                     
     150                try{ 
     151                    p.parseStatements(p.next()); 
     152                }catch(e){ 
     153                    var l=p.getPosition(); 
     154                    throw fileName + '(' + (l[0] ) + ',' +l[1] + ') ' +   e + ' near:\n' + p._working.slice(0,200); 
     155                }  
     156     
     157            }else{ 
     158       
     159                try{//load the script if it is not the main jsolait or jsolaitws module that has already been loaded. 
     160                    if(fileName.toLowerCase() != jsolait.__fileName__.toLowerCase()  && 
     161                                fileName.toLowerCase() != mod.__fileName__.toLowerCase()){ 
     162                        mod.loadScript(fileName); 
     163                    } 
     164                }catch(e){ 
     165                    log(e); 
     166                    return; 
     167                } 
     168                 
     169                 
     170                if(WScript.arguments.named.exists("testModule")){ 
     171                    //if the script was loaded correctly and it contained a module then  
     172                    //that module should have a __filename__ property which matches fileName 
     173                    //and is teh one that needs to be tested 
     174                    for(var mn in jsolait.modules){ 
     175                        if(jsolait.modules[mn].__fileName__.toLowerCase() == fileName.toLowerCase()){ 
     176                            var testing = jsolait.imprt("testing"); 
     177                            testing.testModule(mn);         
     178                            return; 
     179                        } 
     180                    } 
     181                    throw "No Module found"; 
     182                } 
     183            } 
     184        } 
     185        
     186   }) 
     187 
     188    try{ 
     189        imprt("jsolaitws").run(); 
     190    }catch(e){ 
     191        log(e,LogError); 
    46192    } 
    47       
    48     pprint=function(m, indent){ 
    49         var m = m.split("\n"); 
    50          
    51         indent =(indent === undefined) ? 0 : indent; 
    52          
    53         if(indent<0){ 
    54             pprint.indent+=indent; 
    55         } 
    56          
    57         var s=[]; 
    58         for(var i=0;i<pprint.indent;i++){ 
    59             s.push(' '); 
    60         } 
    61         s=s.join(''); 
    62         for(var i=0;i<m.length;i++){ 
    63             print(s + m[i]); 
    64         } 
    65          
    66         if(indent>0){ 
    67             pprint.indent += indent; 
    68         } 
    69     } 
    70     pprint.indent=0; 
    71      
    72     Error.prototype.toString=function(){ 
    73         return this.name +": " + this.message; 
    74     } 
    75              
    76     LogError=1; 
    77     LogWarn=2; 
    78     LogInfo=4; 
    79     Error.prototype.toTraceString=function(){ 
    80         return this.message 
    81     } 
    82      
    83     log=function(msg, level){ 
    84         level = level==null?LogInfo:level; 
    85         if(typeof msg !="string"){ 
    86             level = LogError; 
    87              
    88             msg = msg.toTraceString(); 
    89         } 
    90          
    91         if(level & log.level){ 
    92             print(msg); 
    93         } 
    94     } 
    95     log.level = LogInfo | LogWarn | LogError;     
    96     
    97 ]]> 
    98     </script> 
    99      
    100     <script language="JavaScript" src="./libws/jsolaitws.js" /> 
    101      
    102     <script language="JavaScript" ><![CDATA[ 
    103         try{ 
    104             jsolait.imprt("jsolaitws").run(); 
    105         }catch(e){ 
    106             log(e,LogError); 
    107         } 
    108193        
    109194    ]]>