Changeset 6f9ab22 in tol


Ignore:
Timestamp:
May 8, 2012, 5:32:10 PM (14 years ago)
Author:
Jorge Pérez <josp.jorge@…>
Branches:
1941-docker-image-to-test, devel, master
Children:
270fc19
Parents:
9062e36
Message:

refs #1502, portando cambios en TolPackage

git-svn-id: ​https://www.tol-project.org/svn/tolp/trunk@4654 be4846ae-f051-483a-831f-b64e7d08527f

Location:
tol/stdlib/TolPackage
Files:
5 added
1 deleted
4 edited

Legend:

Unmodified
Added
Removed
  • tol/stdlib/TolPackage/TolPackage.tol

    r9062e36 r6f9ab22  
    55//////////////////////////////////////////////////////////////////////////////
    66
    7 NameBlock TolPackage = [[
    8 Text _.autodoc.description = "Utilidades para el manejo de paquetes TOL: "
    9 "instalación, actualización, borrado, consulta de estado, etc.\n"
    10 ".";
     7//////////////////////////////////////////////////////////////////////////////
     8NameBlock TolPackage =
     9//////////////////////////////////////////////////////////////////////////////
     10[[
     11  Text _.autodoc.name = "TolPackage";
     12  Text _.autodoc.description = "Utilidades para el manejo de paquetes TOL: "
     13    "instalación, actualización, borrado, consulta de estado, etc.";
     14  Set _.autodoc.keys = [["TOL", "Package", "Repository", "Modularity"]];
     15  Set _.autodoc.authors = [["vdebuen@tol-project.org", "pgea@bayesinf.com"]];
     16  Real _.autodoc.version.high = 2;
     17  Real _.autodoc.version.low = 1;
    1118
    12 Set _.autodoc.keys = [["TOL","Package","Repository","Modularity"]];
    13 Set _.autodoc.authors = [["vdebuen@tol-project.org"]];
     19  Text _.version = ""<<_.autodoc.version.high<<"."<<_.autodoc.version.low;
     20  // Se usa la version alta para todas las rutas locales
     21  Text _.localRoot = Replace(TolAppDataPath+"TolPackage."
     22    <<_.autodoc.version.high<<"/","\\","/");
    1423
    15 Text _.version = "1.2";
     24  Class @Catalog;
     25  Class @LocalBlock;
    1626
    17 Text _.localRoot =
    18   Replace(TolAppDataPath+"TolPackage/"+TolPackage::_.version+"/","\\","/");
    19 
    20 #Embed "common.tol";
    21 #Embed "client.tol";
    22 #Embed "server.tol";
    23 #Embed "builder.tol"
    24 
     27  #Embed "common.tol";
     28  #Embed "def_localblock.tol";
     29  #Embed "def_catalog.tol";
     30  #Embed "TolVersion.tol";
     31  #Embed "client.tol";
     32  #Embed "server.tol";
     33  #Embed "packager.tol";
     34  #Embed "builder.tol"
    2535]];
    26 
    27 //Sólo en version de pruebas
    28 //Real TolPackage::Client::Initialize(0);
    29 
     36//////////////////////////////////////////////////////////////////////////////
  • tol/stdlib/TolPackage/client.tol

    r9062e36 r6f9ab22  
    55//////////////////////////////////////////////////////////////////////////////
    66
    7 Text _.autodoc.member.Client=
    8 "Sistema cliente de gestión de paquetes TOL";
    9 
    10 //////////////////////////////////////////////////////////////////////////////
    11 NameBlock Client = [[
    12 //////////////////////////////////////////////////////////////////////////////
    13 
    14 Text _.localRoot = TolPackage::_.localRoot +"Client/";
    15 Text _.defaultPackagePath = GetAbsolutePath( "DefaultPackage" ) + "/";
    16 Text _.defaultListFile = GetAbsolutePath( "DefaultList.tol" );
    17 Set _.defaultList = Copy( Empty );
    18 
    19 Set _.versSyncInfo = Copy(Empty);
    20 //Listado de todos los paquetes disponibles
    21 Set _.packSyncInfo = Copy(Empty);
    22 //Paquetes para los que la versión remota es más moderna
    23 Set _.packForUpdate = Copy(Empty);
    24 //Paquetes para los que hay versiones remotas ulteriores
    25 Set _.packForUpgrade = Copy(Empty);
    26 //Paquetes no instalados
    27 Set _.packForInstall = Copy(Empty);
    28 //Paquetes ya instalados
    29 Set _.packInstalled = Copy(Empty);
    30 
    31 Text _common_php_arguments = "";
    32 
    33 Real  trace_max_level = 0;
    34 
    35 //////////////////////////////////////////////////////////////////////////////
    36 Text _.autodoc.member._trace =
    37 "Muestra la traza especificada";
    38 Real _trace(Text method, Text message, Real level)
    39 //////////////////////////////////////////////////////////////////////////////
    40 {
    41 //WriteLn("[TolPackage::Client::_trace] ("+method+","+message+" "<<level+") trace_max_level="<<trace_max_level);
    42   If(level > trace_max_level, 0,
    43   {
    44     WriteLn("[TolPackage::Client::"+method+"] "+message);
    45     1
    46   })
    47 };
    48 
    49 //////////////////////////////////////////////////////////////////////////////
    50 Text _.autodoc.member.Initialize =
    51 "Inicializa el cliente del servicio de paquetes TOL";
    52 Real Initialize(Real void)
    53 //////////////////////////////////////////////////////////////////////////////
    54 {
    55   Real _trace("Initialize", "Begin", 1);
    56   Real TolPackage::Initialize(void);
    57   Text _common_php_arguments :=
    58     "tol_package_version="<<TolPackage::_.version+
    59     "&tol_version="+Replace(TolPackage::_.currentTolVersion," ","%20");
    60   Real OSDirMake(_.localRoot);
    61   Real OSDirMake( _.defaultPackagePath );
    62   Real CheckDefaultPackages( 1 );
    63   Real _trace("Initialize", "End", 1);
    64   True
    65 };
    66 
    67 //////////////////////////////////////////////////////////////////////////////
    68 Text _.autodoc.member.AddRepository =
    69 "Añade un repositorio a la lista de configuración del usuario:\n"
    70 "  Set TolConfigManager::Config::Upgrading::TolPackage::Repositories\n";
    71 Real AddRepository(Text url)
    72 //////////////////////////////////////////////////////////////////////////////
    73 {
    74   Real _trace("AddRepository", "Begin", 1);
    75   Set TolConfigManager::Config::Upgrading::TolPackage::Repositories :=
    76     Unique(TolConfigManager::Config::Upgrading::TolPackage::Repositories <<
    77            [[url]]);
    78   Real TolConfigManager::SaveConfig(TolConfigManager::Config);
    79   Real _trace("AddRepository", "End", 1);
    80   True
    81 };
    82 
    83 //////////////////////////////////////////////////////////////////////////////
    84 Text _.autodoc.member.GetRequirements=
    85 "Crea un texto con los #Require para una lista de paquetes";
    86 Text GetRequirements(Set packages)
    87 //////////////////////////////////////////////////////////////////////////////
    88 {
    89   SetSum(EvalSet(packages,Text(Text required)
    90   {
    91     "#Require "+required+";\n"
    92   }))
    93 };
    94 
    95 //////////////////////////////////////////////////////////////////////////////
    96 Text _.autodoc.member.DoRequirements=
    97 "Llama a #Require para una lista de paquetes";
    98 Real DoRequirements(Set packages)
    99 //////////////////////////////////////////////////////////////////////////////
    100 {
    101   Real _trace("DoRequirements", "Begin", 1);
    102   Set EvalSet(packages,Real(Text required)
    103   {
    104     Set IncludeText("#Require "+required+";\nReal True;");
    105     True
    106   });
    107   Real _trace("DoRequirements", "End", 1);
    108   True
    109 };
    110 
    111 
    112 //////////////////////////////////////////////////////////////////////////////
    113 Text _.autodoc.member.LocalInfo =
    114 "Devuelve la información local disponible acerca de un paquete.";
    115 Set LocalInfo(Text name.version)
    116 //////////////////////////////////////////////////////////////////////////////
    117 {
    118   Text root = TolPackage::Client::_.localRoot+"/"+name.version+"/";
    119   Text info.path=root+"info.oza";
    120   Real If(!OSFilExist(info.path),
    121   {
    122     Set pkgCnt = Ois.Load(root+name.version+".oza")[1];
    123     TolPackage::PackageInfo.Build(pkgCnt[1], root, UnknownDate)
    124   });
    125   Ois.Load(info.path)[1]
    126 };
    127 
    128 //////////////////////////////////////////////////////////////////////////////
    129 Text _.autodoc.member.PackagePrefix =
    130 "Devuelve un prefijo de paquete para poder hacwer comparaciones con "
    131 "TextBeginWith.";
    132 Text PackagePrefix(Text package)
    133 //////////////////////////////////////////////////////////////////////////////
    134 {
    135   Real _trace("RefersPackage", "Begin", 1);
    136   Set tok = Tokenizer(package,".");
    137   Real tokCard = Card(tok);
    138   Real endAtPoint = TextEndAt(package,".");
    139   Text pkgPrefix = Case(
    140     tokCard==1,package+".",
    141     tokCard==4,tok[1]+"."+tok[2]+"."+tok[3],
    142     endAtPoint,package,
    143     1==1,      package+".");
    144   Real _trace("RefersPackage", "package='"<<package+"'", 5);
    145   Real _trace("RefersPackage", "tok={"<<tok+"}", 5);
    146   Real _trace("RefersPackage", "tokCard="<<tokCard, 5);
    147   Real _trace("RefersPackage", "endAtPoint="<<endAtPoint, 5);
    148   Real _trace("RefersPackage", "pkgPrefix='"<<pkgPrefix+"'", 1);
    149   Real _trace("RefersPackage", "End", 1);
    150   pkgPrefix
    151 };
    152 
    153 //////////////////////////////////////////////////////////////////////////////
    154 Text _.autodoc.member.LocalLastCompatible =
    155 "Devuelve la última versión de un paquete disponible localmente que es "
    156 "compatible con la versión actual de TOL.";
    157 Text LocalLastCompatible(Text package)
    158 //////////////////////////////////////////////////////////////////////////////
    159 {
    160   Text pkgPrefix = PackagePrefix(package);
    161   Set pkgLst = GetDir(TolPackage::Client::_.localRoot)[2];
    162   Set pkgSel = Select(pkgLst,Real(Text pkgNamVer)
    163   {
    164     Real _trace("LocalLastCompatible", "checking version ="<<pkgNamVer, 5);
    165     Real ok1 = TextBeginWith(pkgNamVer, pkgPrefix);
    166     If(!ok1, False,
    167     {
    168       Set info = TolPackage::Client::LocalInfo(pkgNamVer);
    169       Real ok2 = And(
    170        Compare.VersionString(info::_.autodoc.minTolVersion,TolPackage::_.currentTolVersion)<=0,
    171        Compare.VersionString(info::_.autodoc.maxTolVersion,TolPackage::_.currentTolVersion)>=0);
    172         ok2
    173     })
    174   });
    175   Text last = If(!Card(pkgSel),"",
    176   {
    177     Set pkgSort = Sort(pkgSel, Real(Text a, Text b) {
    178       Compare.VersionString(b, a) });
    179     pkgSort[1]
    180   });
    181   Real _trace("LocalLastCompatible", "End", 1);
    182   last
    183 };
    184 
    185 //////////////////////////////////////////////////////////////////////////////
    186 Text _.autodoc.member.LocalPath =
    187 "Devuelve el path completo del fichero local correspondiente a un paquete "
    188 "comprimido.";
    189 Text LocalPath(Text package.version)
    190 //////////////////////////////////////////////////////////////////////////////
    191 {
    192   TolPackage::Client::_.localRoot+package.version+"/"+package.version+".zip"
    193 };
    194 
    195 //////////////////////////////////////////////////////////////////////////////
    196 Text _.autodoc.member.LocalOza =
    197 "Devuelve el path completo del fichero local OIS correspondiente a un "
    198 "paquete.";
    199 Text LocalOza(Text package.version)
    200 //////////////////////////////////////////////////////////////////////////////
    201 {
    202   TolPackage::Client::_.localRoot+package.version+"/"+package.version+".oza"
    203 };
    204 
    205 //////////////////////////////////////////////////////////////////////////////
    206 Text _.autodoc.member.LocalResourcePath =
    207 "Devuelve el path completo del directorio local de un recurso ajeno a TOL "
    208 "necesario para el paquete especificado.";
    209 Text LocalResourcePath(Text package.version, Text resource)
    210 //////////////////////////////////////////////////////////////////////////////
    211 {
    212   TolPackage::Client::_.localRoot+package.version+"/"+resource
    213 };
    214 
    215 //////////////////////////////////////////////////////////////////////////////
    216 Text _.autodoc.member.LocalInstallPackage =
    217 "Instala un paquete desde el archivo local comprimido dado por el "
    218 "argumento:\n"
    219 "  Text pkg.path.zip = \"<directory>/<name>.<high>.<low>.zip\"\n";
    220 Real LocalInstallPackage(Text pkg.path.zip)
    221 //////////////////////////////////////////////////////////////////////////////
    222 {
    223   Real _trace("LocalInstallPackage", "Begin", 1);
    224   Real _trace("LocalInstallPackage", "pkg.path.zip='"+pkg.path.zip+"'", 5);
    225   Real OSFilCopy(pkg.path.zip, _.localRoot);
    226   Text pkg.name.zip = GetFileName(pkg.path.zip);
    227   Real _trace("LocalInstallPackage", "pkg.name.zip='"+pkg.name.zip+"'", 5);
    228   Text pkg.name = Replace(pkg.name.zip,".zip","");
    229   Real _trace("LocalInstallPackage", "pkg.name='"+pkg.name+"'", 5);
    230   Real OSDirRemove(_.localRoot+pkg.name);
    231   Real PackArchive::UnpackFull("ZipArchive",_.localRoot+pkg.name,True);
    232   Real _trace("LocalInstallPackage", "End", 1);
    233   FileExist(_.localRoot+pkg.name+"/"+pkg.name+".oza")
    234 };
    235 
    236 //////////////////////////////////////////////////////////////////////////////
    237 Text _.autodoc.member.LocalExportPackage =
    238 "Exports a locally installed package to a zip file.\n"
    239 "This is usefull to move packages from one machine to other\n";
    240 Real LocalExportPackage(Text pkg.ver, Text dir.dest)
    241 //////////////////////////////////////////////////////////////////////////////
    242 {
    243   Text dir.loc = ReplaceSlash(_.localRoot);
    244   Text pkg.loc = dir.loc+pkg.ver;
    245   Text zip.loc = pkg.loc+".zip";
    246   Text zip.dest = dir.dest+pkg.ver+".zip";
    247 
    248   //Ensures that local.oza is locally created
    249   Set LocalInfo(pkg.ver);
    250 
    251   //Compacts the package as a ZIP file
    252   Real PackArchive::PackFull("ZipArchive", pkg.loc, False);
    253 
    254   //Moves the ZIP file to destination directory
    255   Real OSFilMove(zip.loc, zip.dest);
    256 
    257   FileExist(zip.dest)
    258 };
    259 
    260 //////////////////////////////////////////////////////////////////////////////
    261 Text _.autodoc.member.LocalClean =
    262 "Elimina un paquete local concreto.\n"
    263 "Si no se especifica número de versión se borrarán todas las versiones "
    264 "locales de dicho paquete.";
    265 Real LocalClean(Text package)
    266 //////////////////////////////////////////////////////////////////////////////
    267 {
    268   Real _trace("LocalClean", "Begin", 1);
    269   Text pkgPrefix = PackagePrefix(package);
    270 
    271   Real ok = If(TextFind(package,"."),
    272   {
    273     Real OSDirRemove(_.localRoot+package)
    274   },
    275   {
     7Text _.autodoc.member.Client =
     8  "Sistema cliente de gestión de paquetes TOL";
     9//////////////////////////////////////////////////////////////////////////////
     10@LocalBlock Client =
     11//////////////////////////////////////////////////////////////////////////////
     12[[
     13  // [API]
     14  //  # Text _.localRoot
     15  //  * @Catalog GetCatalog(Real void)
     16  //  * Real UpdateCatalog(Real void)
     17  //  % Set GetPackageInfo(Text name.version) //[OLD] LocalInfo
     18  //  * Real InstallZip(Text file) //[OLD] LocalInstallPackage
     19  //  % Real ExportPackage(Text id, Text dest) //[OLD] LocalExportPackage
     20  //  * Real UninstallPackage(Text package) //[OLD] LocalClean
     21  //  # Real Initialize(Real void)
     22  // [API Compatibilidad]
     23  //  # Text LocalLastCompatible(Text package)
     24  //    => GetCatalog(?)::ObtainLastCompatible(package)
     25  //  # Real RemoteInstall(Text repository, Text package, Real showError)
     26  //    => TolPackage::InstallLastCompatible(pattern)
     27  //  $ Real RemoteUpdateAll(Real void)
     28  //    => TolPackage::UpdateAll(?)
     29  //  $ Real RemoteUpgradeAll(Real void)
     30  //    => TolPackage::UpgradeAll(?)
     31  //  & Text CppTools.Path(NameBlock pkg)
     32  //  & Real CppTools.Check(NameBlock package, Text dllFile, Text chechMethod)
     33  // <Leyenda>
     34  //  #: Obligatorios por ser usados en language.cpp
     35  //  &: Obligarorios por ser usados en la carga de paquetes con DLLs.
     36  //  %: Utilizados en la GUI de TolPackage.
     37  //  $: Recomendados por ser muy utilizados.
     38
     39  // La ruta "_.localRoot" es donde se instalan los paquetes y de allí
     40  // intentan cargarse tras comprobar la versión más adecuada.
     41  Text _.localRoot = _.localRoot<<"Client/";
     42  Set _.catalog = Copy(Empty);
     43
     44  ////////////////////////////////////////////////////////////////////////////
     45  @Catalog GetCatalog(Real void)
     46  ////////////////////////////////////////////////////////////////////////////
     47  {
     48    If(Card(_.catalog), _.catalog[1])
     49  };
     50
     51  ////////////////////////////////////////////////////////////////////////////
     52  Real UpdateCatalog(Real void)
     53  ////////////////////////////////////////////////////////////////////////////
     54  {
     55    @Catalog catalog = GetCatalog(?);
     56    catalog::Update(?)
     57  };
     58
     59  ////////////////////////////////////////////////////////////////////////////
     60  Set GetPackageInfo(Text name.version) // GUI
     61  ////////////////////////////////////////////////////////////////////////////
     62  {
     63    @Catalog catalog = GetCatalog(?);
     64    Set record = catalog::GetRecord(name.version);
     65    @Catalog::FormatRecord_Autodoc(record)
     66  };
     67
     68  // Métodos Local* y Remote* mantenidos por compatibilidad
     69
     70  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     71  Text LocalLastCompatible(Text package)
     72  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     73  {
     74    @Catalog catalog = GetCatalog(?);
     75    AvoidErr.NonDecAct(catalog::ObtainLastCompatible(package))
     76  };
     77
     78  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     79  Real RemoteInstall(Text repository, Text package, Real showError)
     80  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     81  {
     82    WriteLn("[TolPackage::Client] Se intentará descargar el paquete '"
     83      <<package<<"'.");
     84    InstallLastCompatible(package)
     85  };
     86
     87  ////////////////////////////////////////////////////////////////////////////
     88  Real RemoteUpdateAll(Real void)
     89  ////////////////////////////////////////////////////////////////////////////
     90  {
     91    WriteLn("Método obsoleto. Utilize en su lugar: TolPackage::UpdateAll.");
     92    UpdateAll(?)
     93  };
     94
     95  ////////////////////////////////////////////////////////////////////////////
     96  Real RemoteUpgradeAll(Real void)
     97  ////////////////////////////////////////////////////////////////////////////
     98  {
     99    WriteLn("Método obsoleto. Utilize en su lugar: TolPackage::UpgradeAll.");
     100    UpgradeAll(?)
     101  };
     102
     103  // Métodos:
     104
     105  ////////////////////////////////////////////////////////////////////////////
     106  Real InstallZip(Text file) //[OLD] LocalInstallPackage
     107  ////////////////////////////////////////////////////////////////////////////
     108  {
     109    Real OSFilCopy(file, _.localRoot);
     110    Text packageName = Replace(GetFileName(file), ".zip", "");
     111    Text folder = _.localRoot<<packageName;
     112    Real OSDirRemove(folder);
     113    Real PackArchive::UnpackFull("ZipArchive", folder, True);
     114    FileExist(folder<<"/"<<packageName+".oza")
     115  };
     116
     117  ////////////////////////////////////////////////////////////////////////////
     118  Real ExportPackage(Text identifier, Text destinationRoot) // GUI
     119  ////////////////////////////////////////////////////////////////////////////
     120  {
     121    Text pkg.loc = _.localRoot<<identifier;
     122    Text zip.loc = pkg.loc+".zip";
     123    Text zip.dest = destinationRoot+pkg.ver+".zip";
     124    //Ensures that local.oza is locally created
     125    //Set LocalInfo(pkg.ver);
     126    //Compacts the package as a ZIP file
     127    Real PackArchive::PackFull("ZipArchive", ReplaceSlash(pkg.loc), False);
     128    //Moves the ZIP file to destination directory
     129    Real OSFilMove(zip.loc, zip.dest);
     130    FileExist(zip.dest)
     131  };
     132
     133  ////////////////////////////////////////////////////////////////////////////
     134  Real UninstallPackage(Text package) //[OLD] LocalClean
     135  ////////////////////////////////////////////////////////////////////////////
     136  {
     137    // Se trata el hecho de que pueda haberse indicado la ruta del archivo
     138    Text pattern = Replace(GetFileName(package), ".zip", "");
     139    Text parts = Tokenizer(pattern, ".")[3];
     140    Set parts := parts << For(1, 3-Card(parts), Text (Real i) { "*" });
     141    Text txtPattern = parts[1]<<"."<<parts[2]<<"."<<parts[3];
    276142    Set dir = GetDir(_.localRoot)[2];
    277     Set sel = Select(dir,Real(Text sub)
    278     {
    279       TextBeginWith(sub,pkgPrefix)
     143    Set sel = EvalSet(GetDir(_.localRoot)[2], Real (Text subdir) {
     144      If(TextMatch(sub ,txtPattern), OSDirRemove(_.localRoot<<subdir), 0)
    280145    });
    281     SetMin(EvalSet(sel,Real(Text pkg)
    282     {
    283       OSDirRemove(_.localRoot+pkg)
    284     }))
    285   });
    286   Real _trace("LocalClean", "End", 1);
    287   ok
    288 };
    289 
    290 //////////////////////////////////////////////////////////////////////////////
    291 Text _.autodoc.member.LocalClean.All =
    292 "Elimina todos los paquetes disponibles localmente.";
    293 Real LocalCleanAll(Text unused)
    294 //////////////////////////////////////////////////////////////////////////////
    295 {
    296   Real OSDirRemove(_.localRoot);
    297   Real OSDirMake(_.localRoot)
    298 };
    299 
    300 //////////////////////////////////////////////////////////////////////////////
    301   Set GetRepositoryInfo(Text url)
    302 //////////////////////////////////////////////////////////////////////////////
    303 {
    304   Real _trace("GetRepositoryInfo", "Begin", 1);
    305   Text pkgInfo = GetUrlContents(url);
    306   Real old.show = Show(False,"ALL");
    307   Set pkgLst = IncludeText(pkgInfo);
    308   Real Show(old.show,"ALL");
    309   Real _trace("GetRepositoryInfo", "End", 1);
    310   pkgLst
    311 };
    312 
    313 
    314 /////////////////////////////////////////////////////////////////// ///////////
    315   Real CheckRepositoryPing(Text url)
    316 //////////////////////////////////////////////////////////////////////////////
    317 {
    318   Real _trace("CheckRepositoryPing", "Begin", 1);
    319   Real ok = If(TolConfigManager::Config::Upgrading::TolPackage::LocalOnly, False,
    320   {
    321     Real key = Floor(Rand(111111111,
    322                           999999999+1-1.E-15)); //IntRand(111111111,999999999);
    323     Set info = GetRepositoryInfo(url+"?"+_common_php_arguments+
    324       "&action=ping&key="<<key);
    325     Real ok = Case(
    326       !Card(info),False,
    327       Grammar(info[1])!="Real",False,
    328       1==1, info[1]==key);
    329   //WriteLn("_trace [CheckRepositoryPing] url="<<url+" info="<<info+" ok="<<ok);
    330     ok
    331   });
    332   Real _trace("CheckRepositoryPing", "End", 1);
    333   ok
    334 };
    335 
    336 //////////////////////////////////////////////////////////////////////////////
    337   Real ChecktolProjectPing(Real void)
    338 //////////////////////////////////////////////////////////////////////////////
    339 {
    340   CheckRepositoryPing(TolPackage::_.official)
    341 };
    342 
    343 //////////////////////////////////////////////////////////////////////////////
    344 Text _.autodoc.member.GetMinTolVersionForPackage =
    345 "Devuelve la versión de TOL mínima que requiere un paquete dado"
    346 "Si no se encuentra el paquete se devuelve la cadena vacía.";
    347 Text GetMinTolVersionForPackage(Text package)
    348 //////////////////////////////////////////////////////////////////////////////
    349 {
    350   Real _trace("GetMinTolVersionForPackage", "Begin", 1);
    351 //WriteLn("_trace [GetMinTolVersionForPackage] 1 package='"<<package+"'");
    352   Text found = If(!ChecktolProjectPing(?), "",
    353   {
    354   //WriteLn("_trace [GetMinTolVersionForPackage] 2");
    355     Set repositories =
    356       TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    357     Real K = Card(repositories);
    358     Real k = 1;
    359     Text found = "";
    360   //WriteLn("_trace [GetMinTolVersionForPackage] 3 K="<<K);
    361     While(And(found=="", k<=K),
    362     {
    363     //WriteLn("_trace [GetMinTolVersionForPackage] 4 repositories["<<k+"]="<<repositories[k]);
    364       Set pkgLst = GetRepositoryInfo(repositories[k]+"?"+_common_php_arguments+
    365         "&action=versions&limit=1&package="+package);
    366     //WriteLn("_trace [GetMinTolVersionForPackage] 5 pkgInfo="<<pkgInfo);
    367     //WriteLn("_trace [GetMinTolVersionForPackage] 6 pkgLst="<<pkgLst);
    368     //WriteLn("_trace [GetMinTolVersionForPackage] 7 Card(pkgLst)="<<Card(pkgLst));
    369       Text If(Card(pkgLst)>0, found := pkgLst[1]->te_min_tol_version);
    370       Real k := k+1
    371     });
    372     found
    373   });
    374   Real _trace("GetMinTolVersionForPackage", "End", 1);
    375   found
    376 };
    377 
    378 //////////////////////////////////////////////////////////////////////////////
    379 Text _.autodoc.member.GetMaxTolVersionForPackage =
    380 "Devuelve la versión de TOL máxima que requiere un paquete dado"
    381 "Si no se encuentra el paquete se devuelve la cadena vacía.";
    382 Text GetMaxTolVersionForPackage(Text package)
    383 //////////////////////////////////////////////////////////////////////////////
    384 {
    385   Real _trace("GetMaxTolVersionForPackage", "Begin", 1);
    386 //WriteLn("_trace [GetMaxTolVersionForPackage] 1 package='"<<package+"'");
    387   Text found = If(!ChecktolProjectPing(?), "",
    388   {
    389   //WriteLn("_trace [GetMaxTolVersionForPackage] 2");
    390     Set repositories =
    391       TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    392     Real K = Card(repositories);
    393     Real k = 1;
    394     Text found = "";
    395   //WriteLn("_trace [GetMaxTolVersionForPackage] 3 K="<<K);
    396     While(And(found=="", k<=K),
    397     {
    398     //WriteLn("_trace [GetMaxTolVersionForPackage] 4 repositories["<<k+"]="<<repositories[k]);
    399       Set pkgLst = GetRepositoryInfo(repositories[k]+"?"+_common_php_arguments+
    400         "&action=versions&limit=1&package="+package);
    401     //WriteLn("_trace [GetMaxTolVersionForPackage] 5 pkgInfo="<<pkgInfo);
    402     //WriteLn("_trace [GetMaxTolVersionForPackage] 6 pkgLst="<<pkgLst);
    403     //WriteLn("_trace [GetMaxTolVersionForPackage] 7 Card(pkgLst)="<<Card(pkgLst));
    404       Text If(Card(pkgLst)>0, found := pkgLst[1]->te_max_tol_version);
    405       Real k := k+1
    406     });
    407     found
    408   });
    409   Real _trace("GetMaxTolVersionForPackage", "End", 1);
    410   found
    411 };
    412 
    413 
    414 //////////////////////////////////////////////////////////////////////////////
    415 Text _.autodoc.member.RemoteFindRepository =
    416 "Devuelve el repositorio al que pertenece un paquete dado de entre aquellos "
    417 "repositorios dados de alta en : \n"
    418 "  Set TolConfigManager::Config::Upgrading::TolPackage::Repositories\n"
    419 "Si no se encuentra el paquete en ninguno de ellos se devuelve la cadena "
    420 "vacía.";
    421 Text RemoteFindRepository(Text package)
    422 //////////////////////////////////////////////////////////////////////////////
    423 {
    424   Real _trace("RemoteFindRepository", "Begin", 1);
    425 //WriteLn("_trace [RemoteFindRepository] 1 package='"<<package+"'");
    426   Text found = If(!ChecktolProjectPing(?), "",
    427   {
    428   //WriteLn("_trace [RemoteFindRepository] 2");
    429     Set repositories =
    430       TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    431     Real K = Card(repositories);
    432     Real k = 1;
    433     Text found = "";
    434   //WriteLn("_trace [RemoteFindRepository] 3 K="<<K);
    435     While(And(found=="", k<=K),
    436     {
    437     //WriteLn("_trace [RemoteFindRepository] 4 repositories["<<k+"]="<<repositories[k]);
    438       Set pkgLst = GetRepositoryInfo(repositories[k]+"?"+_common_php_arguments+
    439         "&action=versions&limit=1&package="+package);
    440     //WriteLn("_trace [RemoteFindRepository] 6 pkgLst="<<pkgLst);
    441     //WriteLn("_trace [RemoteFindRepository] 7 Card(pkgLst)="<<Card(pkgLst));
    442       Text If(Card(pkgLst)>0, found := repositories[k]);
    443       Real k := k+1
    444     });
    445     found
    446   });
    447   Real _trace("RemoteFindRepository", "Begin", 1);
    448   found
    449 };
    450 
    451 //////////////////////////////////////////////////////////////////////////////
    452 Text _.autodoc.member.RemoteReleaseDate =
    453 "Devuelve la fecha de la última actualización compatible con la versión "
    454 "actual de TOL de un paquete en un repositorio dado. "
    455 "Si no se especifica ningún repositorio se buscará en todos los "
    456 "repositorios dados de alta en \n"
    457 "  Set TolConfigManager::Config::Upgrading::TolPackage::Repositories\n"
    458 "Si no se encuentra el paquete se devuelve la fecha desconocida.";
    459 Date RemoteReleaseDate(Text repository, Text package)
    460 //////////////////////////////////////////////////////////////////////////////
    461 {
    462   Real _trace("RemoteReleaseDate", "Begin", 1);
    463   Date dte =If(!ChecktolProjectPing(?), UnknownDate,
    464   {
    465     Text rep = If(repository=="",repository,RemoteFindRepository(package));
    466     If(rep=="", UnknownDate,
    467     {
    468       Set pkgLst = GetRepositoryInfo(rep+"?"+_common_php_arguments+
    469         "&action=versions&limit=1&package="+package);
    470       If(!Card(pkgLst), TheEnd,
    471         pkgLst[1]->dh_release_date_remote)
    472     })
    473   });
    474   Real _trace("RemoteReleaseDate", "End", 1);
    475   dte
    476 };
    477 
    478 //////////////////////////////////////////////////////////////////////////////
    479 Text _.autodoc.member._DownloadPackageOrZip =
    480 "Descarga desde el repositorio remoto al path indicado, un paquete "
    481 "determinado y lo descomprime si unZip es cierto\n";
    482 Real _DownloadPackageOrZip(
    483   Text repository, Text package, Real showError, Text localRoot, Real unZip)
    484 //////////////////////////////////////////////////////////////////////////////
    485 {
    486   Real _trace("_DownloadPackageOrZip", "Begin", 1);
    487   Real ok = If(!ChecktolProjectPing(?), 0,
    488   {
    489     Real OSDirMake(localRoot);
    490   //WriteLn("_trace [_DownloadPackageOrZip] 1 repository='"<<repository+"'");
    491     Real ok = True;
    492     Text package.orig = package;
    493     Set pkg.tok = Tokenizer(package,".");
    494     Real pkg.tok.num = Card(pkg.tok );
    495     Text package := pkg.tok[1];
    496     Text package.version = Case(
    497       pkg.tok.num==3, pkg.tok[1]+"."+pkg.tok[2]+"."+pkg.tok[3],
    498       pkg.tok.num==2, pkg.tok[1]+"."+pkg.tok[2],
    499       pkg.tok.num==1, pkg.tok[1]);
    500     Set pkgLst = GetRepositoryInfo(repository+"?"+_common_php_arguments+
    501       "&action=versions&limit=1&package="+package.version);
    502     Real ok := Card(pkgLst);
    503     Text If(ok,
    504     {
    505       Text package.version := pkgLst[1]->co_name_version
    506     });
    507     If(!ok, 0, {
    508   //WriteLn("_trace [_DownloadPackageOrZip] 2.1 package.orig='"<<package.orig+"'");
    509   //WriteLn("_trace [_DownloadPackageOrZip] 2.2 package='"<<package+"'");
    510   //WriteLn("_trace [_DownloadPackageOrZip] 2.3 package.version='"<<package.version+"'");
    511 
    512     Text pack = package.version+".zip";
    513     Text oza = package.version+"/"+package.version+".oza";
    514     Text localPack = localRoot+"/"+pack;
    515     Text localOza = localRoot+"/"+oza;
    516     Text localDir = localRoot+"/"+package.version;
    517 
    518     Text encoded = GetUrlContents(repository+"?"+_common_php_arguments+
    519       "&action=download"+
    520       "&format=base64"+
    521       "&package="+package.version);
    522   //WriteLn("_trace [_DownloadPackageOrZip] 3 encoded='"<<encoded+"'");
    523     Real DecodeBase64ToFile(localPack, encoded);
    524     Real ok = FileExist(localPack);   
    525     Case(
    526     !FileExist(localPack), False,
    527     !unZip, True,
    528     1==1,
    529     {
    530     //WriteLn("_trace DownloadPackage 4 UnpackFull("<<localDir+")");
    531       Real PackArchive::UnpackFull("ZipArchive", localDir, True);
    532       If(!FileExist(localOza), False,
    533       {
    534       //WriteLn("_trace DownloadPackage 5");
    535       //Real RemoteUpdateVersSyncInfo(showError);
    536       //Real RemoteUpdatePackSyncInfo(showError);
    537         True
     146    If(Card(sel), SetSum(sel), 0)
     147  };
     148
     149  // Métodos CppTools
     150
     151  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     152  Text CppTools.Path(NameBlock pkg)
     153  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     154  {
     155    Text packageFullName = pkg::_.autodoc.name+"."<<
     156      pkg::_.autodoc.version.high+"."<<pkg::_.autodoc.version.low;
     157    _CppTools.CalcPath(packageFullName)
     158  };
     159
     160  ////////////////////////////////////////////////////////////////////////////
     161  Text _CppTools.CalcPath(Text packageFullName)
     162  ////////////////////////////////////////////////////////////////////////////
     163  {
     164    Text packageName = Tokenizer(packageFullName,".")[1];
     165    Text dllRoot.rel = GetAbsolutePath(_.localRoot+packageFullName+
     166      "/CppTools/"+GetHardSoftPlattform(0));
     167    Text dllRoot.deb = dllRoot.rel+"_dbg";
     168    Text dllFile.rel = dllRoot.rel+"/"+packageName+"."+GetSharedLibExt(0);
     169    Text dllFile.deb = dllRoot.deb+"/"+packageName+"."+GetSharedLibExt(0);
     170    If(!TextEndAt(Version, "{DEBUG}"), dllFile.rel, {
     171      If(OSDirExist(dllFile.deb),dllFile.deb, {
     172        WriteLn("Cannot find debug library "+dllFile.deb+
     173          ".\n Trying to load "+dllFile.rel,"W");
     174        dllFile.rel
    538175      })
    539176    })
    540   })});
    541   Real _trace("_DownloadPackageOrZip", "End", 1);
    542   ok
    543 };
    544 
    545 //////////////////////////////////////////////////////////////////////////////
    546 Text _.autodoc.member.DownloadPackage =
    547 "Descarga desde el repositorio remoto al directorio localRoot indicado, "
    548 "un paquete determinado y lo descomprime.\n";
    549 Real DownloadPackage(
    550   Text repository, Text package, Real showError, Text localRoot)
    551 //////////////////////////////////////////////////////////////////////////////
    552 {
    553   _DownloadPackageOrZip(repository, package, showError, localRoot, True)
    554 };
    555 
    556 //////////////////////////////////////////////////////////////////////////////
    557 Text _.autodoc.member.DownloadPackageZip =
    558 "Descarga desde el repositorio remoto al directorio localRoot indicado, "
    559 "un paquete comprimido.\n";
    560 Real DownloadPackageZip(
    561   Text repository, Text package, Real showError, Text localRoot)
    562 //////////////////////////////////////////////////////////////////////////////
    563 {
    564   _DownloadPackageOrZip(repository, package, showError, localRoot, False)
    565 };
    566 
    567 //////////////////////////////////////////////////////////////////////////////
    568 Text _.autodoc.member.RemoteInstallPackage =
    569 "Instala desde el repositorio remoto al local un paquete determinado "
    570 "para que esté disponible llamando a #Require. \n"
    571 "En un mismo repositorio local puede haber distintas veriones de un mismo "
    572 "paquete que se distinguirán unas de otras por el texto posterior al "
    573 "primer punto. Antes del punto el nombre del paquete suele de seguir la "
    574 "nomenclatura tipo WIKI AaaBbb \n"
    575 "Si no se especifica ninguna versión se instalará la última disponible."
    576 "Si ya existía una copia en el repositorio local será substituida sin "
    577 "mayores contemplaciones por lo que el usuario debe saber lo que pide. \n"
    578 "Sólo es necesario instalar una vez un paquete y todas las sesiones TOL "
    579 "que se lancen desde ese momento podrán usarlos.";
    580 //////////////////////////////////////////////////////////////////////////////
    581 Real RemoteInstallPackage(Text repository, Text package, Real showError)
    582 //////////////////////////////////////////////////////////////////////////////
    583 {
    584   DownloadPackage(
    585     repository, package, showError,
    586     TolPackage::Client::_.localRoot)
    587 };
    588 
    589 //////////////////////////////////////////////////////////////////////////////
    590 Text _.autodoc.member.RemoteInstallFullRepository =
    591 "Instala la última versión compatible con la versión actual de TOL de todos "
    592 "los paquetes disponibles en un repositorio remoto.\n";
    593 //////////////////////////////////////////////////////////////////////////////
    594 Real RemoteInstallFullRepository(Text repository, Real showError)
    595 //////////////////////////////////////////////////////////////////////////////
    596 {
    597   Real _trace("RemoteInstallFullRepository", "Begin", 1);
    598   Real ok = If(!ChecktolProjectPing(?), 0,
    599   {
    600     Set pkgLst = GetRepositoryInfo(repository+"?"+_common_php_arguments+
    601       "&action=versions");
    602     If(!Card(pkgLst), False,
    603     SetMin(EvalSet(pkgLst, Real(Set pkg)
    604     {
    605       RemoteInstallPackage(repository, pkg->co_name_version, showError)
    606     })))
    607   });
    608   Real _trace("RemoteInstallFullRepository", "End", 1);
    609   ok
    610 };
    611 
    612 //////////////////////////////////////////////////////////////////////////////
    613 Text _msg.cannotFindPackage(Text package)
    614 //////////////////////////////////////////////////////////////////////////////
    615 {
    616   Text minTolVersion = GetMinTolVersionForPackage(package);
    617   If(minTolVersion=="",
    618   {
    619     Set rep = TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    620     I2(
    621     "Cannot find package "+package+" in any repository for any TOL "
    622     "version.",
    623     "No se encuentra el paquete "+package+" en ningún repositorio "
    624     "para ninguna versión de TOL.")+"\n"+
    625     I2("Instaled repositories","Repositorios instalados")+" : \n"+
    626     SetSum(EvalSet(rep,Text(Text r) { "  "<<r+"\n" }))
    627   },
    628   {
    629     I2(
    630     "Cannot find package "+package+" for current TOL version ",
    631     "No se encuentra el paquete "+package+" "
    632     "para la versión de TOL en curso ")+TolPackage::_.currentTolVersion+
    633     ".\n"+I2("You needs to use ", "Es necesario usar ")+minTolVersion
    634   })
    635 };
    636 
    637 
    638 //////////////////////////////////////////////////////////////////////////////
    639 Text _.autodoc.member.RemoteInstall =
    640 "Instala desde el repositorio remoto al local un paquete determinado "
    641 "para que esté disponible llamando a #Require. \n"
    642 "En un mismo repositorio local puede haber distintas veriones de un mismo "
    643 "paquete que se distinguirán unas de otras por el texto posterior al "
    644 "primer punto. Antes del punto el nombre del paquete suele de seguir la "
    645 "nomenclatura tipo WIKI AaaBbb \n"
    646 "Si no se especifica ninguna versión se instalará la última disponible."
    647 "Si no se especifica ningún paquete se instalará la última versión de "
    648 "todos los disponibles en el repositorio.\n"
    649 "Si no se especifica ningún repositorio se buscará en todos los "
    650 "repositorios dados de alta en \n"
    651 "  Set TolConfigManager::Config::Upgrading::TolPackage::Repositories\n"
    652 "Si ya existía una copia en el repositorio local será substituida sin "
    653 "mayores contemplaciones por lo que el usuario debe saber lo que pide. \n"
    654 "Sólo es necesario instalar una vez un paquete y todas las sesiones TOL "
    655 "que se lancen desde ese momento podrán usarlos.";
    656 //////////////////////////////////////////////////////////////////////////////
    657 Real RemoteInstall(Text repository, Text package, Real showError)
    658 //////////////////////////////////////////////////////////////////////////////
    659 {
    660   Real _trace("RemoteInstall", "Begin", 1);
    661 //WriteLn("_trace [RemoteInstall] 1 repository='"<<repository+"'");
    662 //WriteLn("_trace [RemoteInstall] 2 package='"<<package+"'");
    663   Real ok = If(!ChecktolProjectPing(?), 0,
    664   {
    665     Case(
    666     And(repository!="",package!=""),
    667     {
    668     //WriteLn("_trace [RemoteInstall] 3.1");
    669       RemoteInstallPackage(repository, package, showError)
    670     },
    671     And(repository=="",package!=""),
    672     {
    673     //WriteLn("_trace [RemoteInstall] 3.2");
    674       Text rep = If(repository!="",repository,RemoteFindRepository(package));
    675     //WriteLn("_trace [RemoteInstall] 3.2.1 rep ="<<rep);
    676       If(rep=="",
    677       {
    678         If(showError,
    679         {
    680           Error("[RemoteInstall ] "+_msg.cannotFindPackage(package))
    681         });
    682         false
    683       },
    684       {
    685       //WriteLn("_trace [RemoteInstall] 3.2.2 ");
    686         RemoteInstallPackage(rep, package, showError)
    687       })
    688     },
    689     And(repository!="",package==""),
    690     {
    691     //WriteLn("_trace [RemoteInstall] 3.3");
    692       RemoteInstallFullRepository(repository, showError)
    693     },
    694     And(repository=="",package==""),
    695     {
    696     //WriteLn("_trace [RemoteInstall] 3.4");
    697       Set repositories =
    698         TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    699       SetMin(EvalSet(repositories, Real(Text rep)
    700       {
    701         RemoteInstallFullRepository(rep, showError)
    702       }))
    703     })
    704   });
    705   Real _trace("RemoteInstall", "End", 1);
    706   ok
    707 };
    708 
    709 //////////////////////////////////////////////////////////////////////////////
    710 Text _.autodoc.member.RemoteUpdateVersSyncInfo =
    711 "Actualiza la información necesaria para la sincronización de versiones de "
    712 "paquetes locales con el repositorio remoto para aquellos que son "
    713 "compatibles con la versión actual de TOL.\n"
    714 "Devuelve el número de versiones de paquetes compatibles disponibles de "
    715 "forma remota.";
    716 Real RemoteUpdateVersSyncInfo(Real void)
    717 //////////////////////////////////////////////////////////////////////////////
    718 {
    719   Real _trace("RemoteUpdateVersSyncInfo", "Begin", 1);
    720   Real ok = If(!ChecktolProjectPing(?), 0,
    721   {
    722     Set repositories =
    723       TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    724     Set _.versSyncInfo := SetConcat(EvalSet(repositories,Set(Text rep)
    725     {
    726       GetRepositoryInfo(rep+"?"+_common_php_arguments+"&action=versions")
    727     }));
    728     Real SetIndexByName(_.versSyncInfo);
    729     Set pkgLst = GetDir(TolPackage::Client::_.localRoot)[2];
    730     Set EvalSet(pkgLst, Real(Text pkg)
    731     {
    732       Real found = FindIndexByName(_.versSyncInfo, pkg);
    733       Date If(found,
    734       {
    735         Set info = LocalInfo(pkg);
    736         _.versSyncInfo[found]->dh_release_date_local := info::_.autodoc.releaseDate
     177  };
     178
     179  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     180  Real CppTools.Check(NameBlock package, Text dllFile, Text chechMethod)
     181  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     182  {
     183    Text packageName = package::_.autodoc.name;
     184    Real ok = ObjectExist("Code", "package::CppTools::"+chechMethod);
     185    WriteLn("["+packageName+"] Loading library "+dllFile+
     186      " -> "<<If(ok,"OK","FAIL"),If(ok,"S","E"));
     187    ok
     188  };
     189
     190  ////////////////////////////////////////////////////////////////////////////
     191  // Se obtiene la ruta donde se encuentran los paquetes distribuidos por
     192  // defecto para que sean instalados en caso necesario.
     193  Text _.defaultPackageDir = GetAbsolutePath("../DefaultPackages/");
     194  // La lista de paquetes que se cargarán por defecto se dejan en un archivo
     195  // aparte para facilitar su consulta y edición.
     196  Set _.defaultPackages =
     197    IncludeTOL("../DefaultPackages/DefaultPackages.tol");
     198
     199  ////////////////////////////////////////////////////////////////////////////
     200  Text _.autodoc.member._.DefaultFetch =
     201    "Download the default packages from OTAN repository and copy into "
     202    "DefaultPackage directory. This function is only called during tol "
     203    "packaging.";
     204  ////////////////////////////////////////////////////////////////////////////
     205  Real _.DefaultFetch( Real void )
     206  ////////////////////////////////////////////////////////////////////////////
     207  {
     208    Text destDir = TolPackage::Client::_.defaultPackageDir;
     209    If( !OSDirExist( destDir ), {
     210        Real OSDirMake( destDir )
     211      } );
     212    NameBlock catalog = TolPackage::Server::GetCatalog(?);
     213    Set result = EvalSet( _.defaultPackages, Real( Set pkgInfo ) {
     214        Text pkg = pkgInfo[1];
     215        WriteLn( "Downloading last " << pkg <<
     216                 " compatible with " << Version );
     217        Text pkg.id = catalog::ObtainIdentifier( pkg, Version, UnknownDate );
     218        Text zipFile = TolPackage::Server::DownloadPackageAt( pkg.id, destDir );
     219        Real ok = FileExist( zipFile );
     220        Text msgStatus = "   ==> " << pkg << ": " << If( ok, "SUCCESS", "FAIL" );
     221        WriteLn( msgStatus );
     222        ok
     223      } );
     224    Real SetSum( result )
     225  };
     226
     227  ////////////////////////////////////////////////////////////////////////////
     228  Real _.DefaultRequire( Real void )
     229  ////////////////////////////////////////////////////////////////////////////
     230  {
     231    Set toRequire = Select(_.defaultPackages, Real(Set elem) { elem[2] });
     232    Set done = EvalSet( toRequire, Real ( Set elem ) {
     233        NameBlock Require( elem[1] );
     234        Real 1
     235      } );
     236    Real Card( done )
     237  };
     238
     239  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     240  Real _initialized = False;
     241  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     242  Text _.autodoc.member.Initialize =
     243    "Inicializa el cliente del servicio de paquetes TOL";
     244  Real Initialize(Real void)
     245  //||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||//
     246  {
     247    If(_initialized, 0, {
     248      Real _initialized := True;
     249      Real OSDirMake(_AsOSDir(_.localRoot));
     250      // [A] Se construye el catálogo local
     251      @Catalog catalog = @Catalog::Local(_.localRoot);
     252      Set _.catalog := [[ catalog ]];
     253      // [B] Se instalan los paquetes por defecto si es necesario
     254      Set localZips = Select(GetDir(_.defaultPackageDir)[1],
     255        Real (Text filename) { TextMatch(filename, "*.zip") });
     256      Set install = EvalSet(localZips, Real (Text filename) {
     257        Text packageName = Replace(GetFileName(filename), ".zip", "");
     258        If(catalog::FindRecord(packageName), 0, {
     259          InstallZip(_.defaultPackageDir<<filename)
     260        })
    737261      });
    738       True
    739     });
    740     Real Ois.Store(_.versSyncInfo,_.localRoot+"/VersSyncInfo.oza");
    741     Card(_.versSyncInfo)
    742   });
    743   Real _trace("RemoteUpdateVersSyncInfo", "End", 1);
    744   ok
    745 };
    746 
    747 //////////////////////////////////////////////////////////////////////////////
    748 Text _.autodoc.member.RemoteUpdatePackSyncInfo =
    749 "Actualiza la información necesaria para la sincronización de paquetes "
    750 "locales con el repositorio remoto para aquellos que son "
    751 "compatibles con la versión actual de TOL.\n"
    752 "Devuelve el número de paquetes compatibles disponibles de forma remota.";
    753 Real RemoteUpdatePackSyncInfo(Real showWarnings)
    754 //////////////////////////////////////////////////////////////////////////////
    755 {
    756   Real _trace("RemoteUpdatePackSyncInfo", "Begin", 1);
    757   Text _MID = "[RemoteUpdatePackSyncInfo] ";
    758   Real ok = If(!ChecktolProjectPing(?), 0,
    759   {
    760     Set repositories =
    761       TolConfigManager::Config::Upgrading::TolPackage::Repositories;
    762     Set _.packSyncInfo := SetConcat(EvalSet(repositories,Set ev.rep(Text rep)
    763     {
    764       GetRepositoryInfo(rep+"?"+_common_php_arguments+"&action=packages")
    765     }));
    766     Real SetIndexByName(_.packSyncInfo);
    767     Set verLst = GetDir(TolPackage::Client::_.localRoot)[2];
    768     Set verCls = Classify(verLst,Real ev.class(Text a, Text b)
    769     {
    770       Compare(Tokenizer(a,".")[1], Tokenizer(b,".")[1])
    771     });
    772     Set EvalSet(verCls, Real ev.check(Set cls)
    773     {
    774       Text pkg = Tokenizer(cls[1],".")[1];
    775       Real found = FindIndexByName(_.packSyncInfo, pkg);
    776       Real If(found,
    777       {
    778         Set ord = Sort(cls,Real ev.sort(Text a, Text b) {
    779           Compare.VersionString(b, a) });
    780         Text ver = ord[1];
    781         Set info = LocalInfo(ver);
    782         Date _.packSyncInfo[found]->co_last_version_local :=
    783           pkg+"."<<info::_.autodoc.version.high+"."<<info::_.autodoc.version.low;
    784         Date _.packSyncInfo[found]->dh_release_date_local := info::_.autodoc.releaseDate;
    785         True
    786       });
    787       True
    788     });
    789     Set _.packForUpdate := Select(_.packSyncInfo, Real(TolPackage::@PackageSynchro pkg)
    790     {
    791       Real _trace("RemoteUpdatePackSyncInfo", "pkg="<<pkg, 5);
    792       Real need = Case(
    793         pkg->co_last_version_local == "", False,
    794         pkg->co_last_version_local != pkg->co_last_version_remote, False,
    795         pkg->dh_release_date_local == TheBegin, False,
    796         DateDif(S(0),pkg->dh_release_date_remote,pkg->dh_release_date_local) <= 2, False,
    797         1==1, True);
    798       Real _trace("RemoteUpdatePackSyncInfo", "need="<<need, 5);
    799       If(And(showWarnings,need),
    800       {
    801         WriteLn("  Local package "<<pkg->co_last_version_local+
    802                 " created at "<<pkg->dh_release_date_local+
    803                 " could be updated to newer remote patch since "<<pkg->dh_release_date_remote)
    804       });
    805       need
    806     });
    807     If(And(showWarnings,Card(_.packForUpdate)),
    808     {
    809       WriteLn(_MID+"There are "<<Card(_.packForUpdate)+" packages that you could update "
    810               "from remote repositories to new patches of the same version.\n"
    811               "You can view them at:\n "
    812               "  Set TolPackage::Client::_.packForUpdate\n"
    813               "You could update all them running this TOL sentence: \n"
    814               "  Real TolPackage::Client::RemoteUpdateAll(0)\n",
    815               "W")
    816     });
    817     Set _.packForUpgrade := Select(_.packSyncInfo, Real(TolPackage::@PackageSynchro pkg)
    818     {
    819       Real need = And(pkg->co_last_version_local != "",
    820           Compare.VersionString(pkg->co_last_version_local,pkg->co_last_version_remote)<0);
    821       If(And(showWarnings,need),
    822       {
    823         WriteLn("  Local package "<<pkg->co_last_version_local+
    824                 " could be upgraded to "<<pkg->co_last_version_remote)
    825       });
    826       need
    827     });
    828     If(And(showWarnings,Card(_.packForUpgrade)),
    829     {
    830       WriteLn(_MID+"There are "<<Card(_.packForUpgrade)+" packages that you could upgrade "
    831               "from remote repositories to new versions.\n"
    832               "You can view them at:\n "
    833               "  Set TolPackage::Client::_.packForUpgrade\n"
    834               "You can upgrade all them running this TOL sentence: \n"
    835               "  Real TolPackage::Client::RemoteUpgradeAll(0)\n",
    836               "W")
    837     });
    838     Set _.packForInstall := Select(_.packSyncInfo, Real(TolPackage::@PackageSynchro pkg)
    839     {
    840       pkg->co_last_version_local == "" 
    841     });
    842     Set _.packInstalled := Select(_.packSyncInfo, Real(TolPackage::@PackageSynchro pkg)
    843     {
    844       pkg->co_last_version_local != "" 
    845     });
    846     Real Ois.Store(_.packSyncInfo,_.localRoot+"/PackSyncInfo.oza");
    847     Card(_.packSyncInfo)
    848   });
    849   Real _trace("RemoteUpdateVersSyncInfo", "End", 1);
    850   ok
    851 };
    852 
    853 
    854 //////////////////////////////////////////////////////////////////////////////
    855 Text _.autodoc.member.RemoteUpdateAll =
    856 "Actualiza automáticamente todos los paquetes disponibles desde los "
    857 "repositorios remotos para los que la copia local haya caducado.\n";
    858 Real RemoteUpdateAll(Real updateSyncInfo)
    859 //////////////////////////////////////////////////////////////////////////////
    860 {
    861   Real _trace("RemoteUpdateAll", "Begin", 1);
    862   Real If(Or(updateSyncInfo,!Card(_.packSyncInfo)),
    863     RemoteUpdatePackSyncInfo(False));
    864   Real ok = If(!Card(_.packForUpdate), 0,
    865   SetSum(EvalSet(_.packForUpdate, Real(TolPackage::@PackageSynchro pkg)
    866   {
    867     RemoteInstallPackage(pkg->te_url, pkg->co_last_version_local, True)
    868   })));
    869   Real _trace("RemoteUpdateAll", "End", 1);
    870   ok
    871 };
    872 
    873 //////////////////////////////////////////////////////////////////////////////
    874 Text _.autodoc.member.RemoteUpgradeAll =
    875 "Actualiza automáticamente todos los paquetes disponibles desde los "
    876 "repositorios remotos para los que exista una versión más moderna.\n";
    877 Real RemoteUpgradeAll(Real updateSyncInfo)
    878 //////////////////////////////////////////////////////////////////////////////
    879 {
    880   Real _trace("RemoteUpgradeAll", "Begin", 1);
    881   Real If(Or(updateSyncInfo,!Card(_.packSyncInfo)),
    882     RemoteUpdatePackSyncInfo(False));
    883   Real ok = If(!Card(_.packForUpgrade), 0,
    884   SetSum(EvalSet(_.packForUpgrade, Real(TolPackage::@PackageSynchro pkg)
    885   {
    886     RemoteInstallPackage(pkg->te_url, pkg->co_last_version_remote, True)
    887   })));
    888   Real _trace("RemoteUpgradeAll", "End", 1);
    889   ok
    890 };
    891 
    892 ////////////////////////////////////////////////////////////////////////////////
    893 Text _.autodoc.member.GetCompatibleVersion.one =
    894 "Gets the latest version of a package that is compatible with current "
    895 "tol version.";
    896 Text GetCompatibleVersion.one(Text package)
    897 ////////////////////////////////////////////////////////////////////////////////
    898 {
    899   Real _trace("GetCompatibleVersion.one", "Begin", 1);
    900   Text pkgPrefix = PackagePrefix(package);
    901   Real If(!Card(_.versSyncInfo),
    902    TolPackage::Client::RemoteUpdateVersSyncInfo(True));
    903  
    904   Set sel_compatible = Select(_.versSyncInfo,
    905   Real(TolPackage::@VersionSynchro reg)
    906   {
    907     And(TextBeginWith(reg->co_name_version, pkgPrefix),
    908         TolPackage::_.currentTolVersion>=reg->te_min_tol_version,
    909         TolPackage::_.currentTolVersion<=reg->te_max_tol_version)
    910   });
    911   If(!Card(sel_compatible),
    912   {
    913     WriteLn("[GetCompatibleVersion.one] Cannot find a version of package "<<
    914     package+" compatible with TOL "+TolPackage::_.currentTolVersion,"E");
    915     Real Stop;
    916     ""
    917   },
    918   {
    919     Set last_compatible = Sort(sel_compatible,
    920     Real(TolPackage::@VersionSynchro a, TolPackage::@VersionSynchro b)
    921     {
    922       Compare.VersionString(b->co_name_version,a->co_name_version)
    923     })[1];
    924     Real _trace("GetCompatibleVersion.one", "End", 1);
    925     last_compatible->co_name_version
    926   })
    927 };
    928 
    929 ////////////////////////////////////////////////////////////////////////////////
    930 Text _.autodoc.member.GetCompatibleVersion.all =
    931 "Gets the latest versions of a set of packages that are compatible with "
    932 "current tol version.";
    933 Set GetCompatibleVersion.all(Set package.list)
    934 ////////////////////////////////////////////////////////////////////////////////
    935 {
    936   EvalSet(package.list, Text (Text pv)
    937   {
    938     GetCompatibleVersion.one(pv)
    939   })
    940 };
    941 
    942 ////////////////////////////////////////////////////////////////////////////////
    943 Text _.autodoc.member.GetDeepDependencies.one =
    944 "Gets the list of deep depencies of a given version of a package";
    945 Set GetDeepDependencies.one(Text package.version)
    946 ////////////////////////////////////////////////////////////////////////////////
    947 {
    948   Real _trace("GetDeepDependencies.one("+package.version+")", "Begin", 1);
    949   Real If(!Card(_.versSyncInfo),
    950    TolPackage::Client::RemoteUpdateVersSyncInfo(True));
    951   Set sel = Select(_.versSyncInfo, Real(TolPackage::@VersionSynchro reg)
    952   {
    953     reg->co_name_version == package.version
    954   });
    955   Set s = If(!Card(sel), sel,
    956   {
    957     Text depExpr = sel[1]->te_dependencies;
    958     Set dep = If(depExpr=="",Copy(Empty),
    959     {
    960       Tokenizer(depExpr,",")
    961     });
    962     Unique(SetConcat(EvalSet(dep,GetDeepDependencies.one))<<[[ sel[1]->co_name_version ]])
    963   });
    964   Real _trace("GetDeepDependencies.one", "End", 1);
    965   s
    966 };
    967 
    968 ////////////////////////////////////////////////////////////////////////////////
    969 Text _.autodoc.member.GetDeepDependencies.all =
    970 "Gets the list of deep depencies of a list of all versions of required "
    971 "packages.";
    972 Set GetDeepDependencies.all(Set package.version.list)
    973 ////////////////////////////////////////////////////////////////////////////////
    974 {
    975   Real _trace("GetDeepDependencies.all", "Begin", 1);
    976   Set tab = EvalSet(package.version.list, GetDeepDependencies.one);
    977   Set all = Unique(SetConcat(tab));
    978   Real _trace("GetDeepDependencies.all", "End", 1);
    979   all
    980 };
    981 
    982 ////////////////////////////////////////////////////////////////////////////////
    983 Text _.autodoc.member.GetDeepDependencies.all.last =
    984 "Gets the list of deep depencies of a list of last versions of required "
    985 "packages.";
    986 Set GetDeepDependencies.all.last(Set package.version.list)
    987 ////////////////////////////////////////////////////////////////////////////////
    988 {
    989   Real _trace("GetDeepDependencies.all.last", "Begin", 1);
    990   Set tab = SetConcat(EvalSet(package.version.list, GetDeepDependencies.one));
    991   Set cls = Classify(tab,Real(Text a, Text b)
    992   {
    993     Compare(Tokenizer(a,".")[1],Tokenizer(b,".")[1])
    994   });
    995   Set srt = EvalSet(cls,Set(Set c)
    996   {
    997     Sort(c,Real(Text a, Text b) { Compare.VersionString(b,a) })
    998   });
    999   Set last = EvalSet(srt,Text(Set c) { c[1] });
    1000   Real _trace("GetDeepDependencies.all.last", "End", 1);
    1001   last
    1002 };
    1003 
    1004 ////////////////////////////////////////////////////////////////////////////////
    1005 Text _.autodoc.member.GetVersionInfo =
    1006 "Gets the TolPackage::@VersionSynchro related to a version of a package";
    1007 Set GetVersionInfo(Set package.version.list)
    1008 ////////////////////////////////////////////////////////////////////////////////
    1009 {
    1010   Real _trace("GetVersionInfo", "Begin", 1);
    1011   Real If(!Card(_.versSyncInfo),
    1012    TolPackage::Client::RemoteUpdateVersSyncInfo(True));
    1013   Set s = EvalSet(package.version.list, TolPackage::@VersionSynchro(Text pv)
    1014   {
    1015     _.versSyncInfo[pv]
    1016   });
    1017   Real _trace("GetVersionInfo", "End", 1);
    1018   s
    1019 };
    1020 
    1021 ////////////////////////////////////////////////////////////////////////////////
    1022 Text _.autodoc.member.GetCompatibleDeepDependencies =
    1023 "Gets the TolPackage::@VersionSynchro related to all deep dependencies of a "
    1024 "list of packages for the last version that is compatible with current tol "
    1025 "version";
    1026 Set GetCompatibleDeepDependencies(Set package.list)
    1027 ////////////////////////////////////////////////////////////////////////////////
    1028 {
    1029   Real _trace("GetCompatibleDeepDependencies", "Begin", 1);
    1030   Set package.version.list = GetCompatibleVersion.all(package.list);
    1031   Set dep = GetVersionInfo(GetDeepDependencies.all(package.version.list));
    1032   Real _trace("GetCompatibleDeepDependencies", "End", 2);
    1033   dep
    1034 };
    1035 
    1036 ////////////////////////////////////////////////////////////////////////////////
    1037 Text _.autodoc.member.DownloadCompatibleDeepDependencies =
    1038 "Downloads to a local directory all deep dependencies of a list of packages "
    1039 "for the last version that is compatible with a tol version.\n"
    1040 "Arguments : \n"
    1041 "  Text localRoot      : Local directory where packages will be downloaded\n"
    1042 "  Real cleanLocalRoot : If true, local directory will be cleaned before to download\n"
    1043 "  Set package.list    : List of packages without explicit version\n"
    1044 "Returns true if all packages are found and downloaded.";
    1045 Real DownloadCompatibleDeepDependencies(
    1046   Text localRoot,
    1047   Real cleanLocalRoot,   
    1048   Set package.list)
    1049 ////////////////////////////////////////////////////////////////////////////////
    1050 {
    1051   Real _trace("DownloadCompatibleDeepDependencies", "Begin", 1);
    1052   Real If(cleanLocalRoot, OSDirRemove(localRoot));
    1053   Set dep = GetCompatibleDeepDependencies(package.list);
    1054   Real ok = SetMin(EvalSet(dep, Real(TolPackage::@VersionSynchro vsi)
    1055   {
    1056     DownloadPackage(vsi->te_url,vsi->co_name_version,True,localRoot)
    1057   }));
    1058   Real _trace("DownloadCompatibleDeepDependencies", "End", 1);
    1059   ok
    1060 };
    1061 
    1062 
    1063 ////////////////////////////////////////////////////////////////////////////////
    1064   Text CppTools.CalcPath(Text packageFullName)
    1065 ////////////////////////////////////////////////////////////////////////////////
    1066 {
    1067   Text packageName = Tokenizer(packageFullName,".")[1];
    1068   Text dllRoot.rel = GetAbsolutePath(
    1069      _.localRoot+packageFullName+
    1070      "/CppTools/"+ GetHardSoftPlattform(0));
    1071   Text dllRoot.deb = dllRoot.rel+"_dbg";
    1072   Text dllFile.rel = dllRoot.rel+"/"+packageName+"."+GetSharedLibExt(0);
    1073   Text dllFile.deb = dllRoot.deb+"/"+packageName+"."+GetSharedLibExt(0);
    1074   If(!TextEndAt(Version,"{DEBUG}"),dllFile.rel,
    1075   {
    1076     If(OSDirExist(dllFile.deb),dllFile.deb,
    1077     {
    1078       WriteLn("Cannot find debug library "+dllFile.deb+
    1079               ".\n Trying to load "+dllFile.rel,"W");
    1080       dllFile.rel
    1081     })
    1082   })
    1083 };
    1084 
    1085 ////////////////////////////////////////////////////////////////////////////////
    1086   Text CppTools.Path(NameBlock pkg)
    1087 ////////////////////////////////////////////////////////////////////////////////
    1088 {
    1089   Text packageFullName =
    1090     pkg::_.autodoc.name+"."<<
    1091     pkg::_.autodoc.version.high+"."<<
    1092     pkg::_.autodoc.version.low;
    1093   CppTools.CalcPath(packageFullName)
    1094 };
    1095 
    1096 ////////////////////////////////////////////////////////////////////////////////
    1097   Real CppTools.Check(NameBlock package, Text dllFile, Text chechMethod)
    1098 ////////////////////////////////////////////////////////////////////////////////
    1099 {
    1100   Text packageName = package::_.autodoc.name;
    1101   Real ok = ObjectExist("Code","package::CppTools::"+chechMethod);
    1102   WriteLn("["+packageName+"] Loading library "+dllFile+
    1103           " -> "<<If(ok,"OK","FAIL"),If(ok,"S","E"));
    1104   ok
    1105 };
    1106 
    1107 ////////////////////////////////////////////////////////////////////////////////
    1108   Real CppTools.HasDll(Text packageFullName)
    1109 ////////////////////////////////////////////////////////////////////////////////
    1110 {
    1111   Text dllFile = CppTools.CalcPath(packageFullName);
    1112   OSFilExist(dllFile)
    1113 };
    1114 
    1115 ////////////////////////////////////////////////////////////////////////////////
    1116   Real CppTools.HasLockedDll(Text packageFullName)
    1117 ////////////////////////////////////////////////////////////////////////////////
    1118 {
    1119   Text dllFile = CppTools.CalcPath(packageFullName);
    1120   If(!OSFilExist(dllFile), False,
    1121   {
    1122     Real open = FOpen(dllFile,"r+b",True,False);
    1123     If(open, FClose(open));
    1124     Not(open)
    1125   })
    1126 };
    1127 
    1128 ////////////////////////////////////////////////////////////////////////////////
    1129 Text _.autodoc.member.CheckDefaultPackages =
    1130 "
    1131 Perform initial default package install provided in DefaultList.tol
    1132 and DefaultPackage directory. The contents of DefaultPackage must be
    1133 set during tol distribution/instalation by invoking the function
    1134 DefaultFetch.
    1135 ";
    1136 Real CheckDefaultPackages( Real verbose )
    1137 ////////////////////////////////////////////////////////////////////////////////
    1138 {
    1139   Set _.defaultList := Include( _.defaultListFile )[1];
    1140   Set pkgLst = GetDir(_.defaultPackagePath)[ 1 ];
    1141   Set EvalSet( pkgLst, Real( Text pkg ) {
    1142       If( verbose,
    1143           WriteLn( "Checking default package '" << pkg << "'" ) );
    1144       Real If( TextEndAt( pkg, ".zip" ), {
    1145           Text pkg.version = Sub( pkg, 1, TextLength( pkg ) - 4 );
    1146           Real idx = TextFind( pkg.version, "." );
    1147           If( idx < 2, {
    1148               WriteLn(  "The file '" << pkg << "' is not a package" );
    1149               Real 0
    1150             }, {
    1151               Text pkg.name = Sub( pkg.version, 1, idx -1 );
    1152               Text pkg.local = LocalOza( pkg.version );
    1153               Real If( FileExist( pkg.local ), {
    1154                   If( verbose, WriteLn( "Package '" << pkg <<
    1155                                         "' is already installed"  ) );
    1156                   Real 0
    1157                 }, {
    1158                   If( verbose, WriteLn( "Package '" << pkg <<
    1159                                     "' will be installed" ) );
    1160                   LocalInstallPackage( _.defaultPackagePath + pkg )
    1161                 } );
    1162               Real idxi = FindIndexByName( _.defaultList, pkg.name );
    1163               Set pkg.info = If( idxi, _.defaultList[ idxi ], {
    1164                   If( verbose,
    1165                       WriteLn( "'" + pkg +
    1166                                "' is not configured at DefaultList.tol" ) );
    1167                   Set [[ 0, 0 ]]
    1168                 } );
    1169               Real If( pkg.info[ 1 ], {
    1170                   Set IncludeText( "#Require " + pkg.name );
    1171                   Real 0
    1172                 }, Real 0 )
    1173             } )
    1174         }, {
    1175           WriteLn( "The file '" << pkg << "' is not a package" );
    1176           Real 0
    1177         } )
    1178     } );
    1179   Real 1
    1180 };
    1181 
    1182 ////////////////////////////////////////////////////////////////////////////////
    1183 Text _.autodoc.member.DefaultFetch =
    1184 "
    1185 Download the default packages from OTAN repository and copy into
    1186 DefaultPackage directory. This function is only called during tol
    1187 packaging.
    1188 ";
    1189 Real DefaultFetch( Real void )
    1190 ////////////////////////////////////////////////////////////////////////////////
    1191 {
    1192   Text otan =
    1193     "http://packages.tol-project.org/OfficialTolArchiveNetwork/repository.php";
    1194   Real OSDirRemove( TolPackage::Client::_.defaultPackagePath );
    1195   Real OSDirMake( TolPackage::Client::_.defaultPackagePath );
    1196   Set result = EvalSet( TolPackage::Client::_.defaultList, Real( Set pkgInfo ) {
    1197       Text pkg = Name( pkgInfo );
    1198       WriteLn( "Downloading last " << pkg <<
    1199                " compatible with " << Version );
    1200       Real ok = TolPackage::Client::DownloadPackageZip
    1201         ( otan, pkg, 0, TolPackage::Client::_.defaultPackagePath );
    1202       Text msgStatus = "   ==> " << pkg << ": " << If( ok, "SUCCESS", "FAIL" );
    1203       WriteLn( msgStatus );
    1204       ok
    1205     } );
    1206   Real SetSum( result )
    1207 }
    1208 
     262      Real If(Card(install), If(SetSum(install), catalog::Update(?)));
     263      // [C] Se cargan los paquetes por defecto
     264      _.DefaultRequire(?)
     265     })
     266  }
    1209267]];
    1210 
    1211 
    1212 
     268//////////////////////////////////////////////////////////////////////////////
  • tol/stdlib/TolPackage/common.tol

    r9062e36 r6f9ab22  
    1 /* -*- mode: C++ -*- */
    2 //////////////////////////////////////////////////////////////////////////////
    3 // FILE   : common.tol
    4 // PURPOSE: TolPackage common tools
    5 // Funciones y estructuras comunes al lado de servidor y cliente
    6 //////////////////////////////////////////////////////////////////////////////
    7 
    8 //////////////////////////////////////////////////////////////////////////////
    9 //Información de un paquete que es relevante para la sincronización de las
    10 //copias locales con el repositorio remoto.
    11   Struct @VersionSynchro {
    12 //////////////////////////////////////////////////////////////////////////////
    13   Text te_url,                  //URL of repository
    14   Text co_name,                 //Generic name of package
    15   Text co_name_version,         //Name of versioned package
    16   Text te_extra_info,           //Extra information
    17   Text te_min_tol_version,      //Minimum compatible TOL version
    18   Text te_max_tol_version,      //maximum compatible TOL version
    19   Text te_dependencies,         //Required packages
    20   Date dh_release_date_remote,  //Publication date in remote repository
    21   Date dh_release_date_local,   //Local installing date
    22   Real nu_bytes                 //Size of remote compressed archive
    23 };
    24 
    25 //////////////////////////////////////////////////////////////////////////////
    26 //Información de un paquete que es relevante para la sincronización de las
    27 //copias locales con el repositorio remoto.
     1
     2  // [API útil]
     3  //  * Text _.autodoc.get.identifier(NameBlock package)
     4  //  * NameBlock Require(Text identifier)
     5  //  * Real AddRepository(Text url)
     6  // [API Client+Server]
     7  //  * Real InstallPackage(Text identifier)
     8  //  * Real InstallCompatible(Text pattern, Text tolVersion, Date date)
     9  //  * Real InstallLastCompatible(Text pattern)
     10  //  * Real UpdateAll(Real void)
     11  //  * Real UpgradeAll(Real void)
     12  // [API compatibilidad]
     13  //  % Set _.GetVersSyncInfo(Real void)
     14  //  % Set _.GetPackSyncInfo(Text tolVersion)
     15  //  % Set GetInstallationList(Set packages)
     16  //  * Set AtListA(Text listId)
     17  // <Leyenda>
     18  //  %: Utilizados en la GUI de TolPackage.
     19
     20  ////////////////////////////////////////////////////////////////////////////
     21  Text _.autodoc.get.identifier(NameBlock package)
     22  ////////////////////////////////////////////////////////////////////////////
     23  {
     24    package::_.autodoc.name<<"."
     25      <<package::_.autodoc.version.high<<"."<<package::_.autodoc.version.low
     26  };
     27
     28  ////////////////////////////////////////////////////////////////////////////
     29  NameBlock Require(Text identifier)
     30  ////////////////////////////////////////////////////////////////////////////
     31  {
     32    Real Eval("Real {
     33      #Require "<<identifier<<";
     34    1}");
     35    Eval(Tokenizer(identifier, ".")[1])
     36  };
     37
     38  ////////////////////////////////////////////////////////////////////////////
     39  Text _.autodoc.member.AddRepository =
     40    "Añade un repositorio a la lista de configuración del usuario:\n"
     41    "  Set TolConfigManager::Config::Upgrading::TolPackage::Repositories\n";
     42  Real AddRepository(Text url)
     43  ////////////////////////////////////////////////////////////////////////////
     44  {
     45    Set TolConfigManager::Config::Upgrading::TolPackage::Repositories :=
     46      Unique(TolConfigManager::Config::Upgrading::TolPackage::Repositories <<
     47      [[url]]);
     48    TolConfigManager::SaveConfig(TolConfigManager::Config)
     49  };
     50
     51  ////////////////////////////////////////////////////////////////////////////
     52  Text _AsOSDir(Text dir)
     53  ////////////////////////////////////////////////////////////////////////////
     54  {
     55    // OSDir* utiliza direcciones no acabadas en /
     56    Real length = TextLength(dir);
     57    If(Text Sub(dir, length, length)=="/", Sub(dir, 1, length-1), dir)
     58  };
     59
     60  ////////////////////////////////////////////////////////////////////////////
     61  Real InstallPackage(Text identifier)
     62  ////////////////////////////////////////////////////////////////////////////
     63  {
     64    Real Server::Initialize(?);
     65    Text file = Server::DownloadPackage(identifier);
     66    Real If(TextLength(file), {
     67      Real Client::InstallZip(file);
     68      Real Client::UpdateCatalog(?);
     69    1}, 0)
     70  };
     71
     72  ////////////////////////////////////////////////////////////////////////////
     73  Real InstallCompatible(Text pattern, Text tolVersion, Date date)
     74  ////////////////////////////////////////////////////////////////////////////
     75  {
     76    Real Server::Initialize(?);
     77    Text file = Server::DownloadCompatible(pattern, tolVersion, date);
     78    Real If(TextLength(file), {
     79      Real Client::InstallZip(file);
     80      Real Client::UpdateCatalog(?);
     81    1}, 0)
     82  };
     83
     84  ////////////////////////////////////////////////////////////////////////////
     85  Real InstallLastCompatible(Text pattern)
     86  ////////////////////////////////////////////////////////////////////////////
     87  {
     88    Real Server::Initialize(?);
     89    Text file = Server::DownloadLastCompatible(pattern);
     90    Real If(TextLength(file), {
     91      Real Client::InstallZip(file);
     92      Real Client::UpdateCatalog(?);
     93    1}, 0)
     94  };
     95
     96  ////////////////////////////////////////////////////////////////////////////
     97  Real UpdateAll(Real void)
     98  ////////////////////////////////////////////////////////////////////////////
     99  {
     100    @Catalog client = Client::GetCatalog(?);
     101    @Catalog server = Server::GetCatalog(?);
     102    Set updateList = server::ObtainUpdateList(client, Version, UnknownDate);
     103    If(Card(updateList), SetSum(EvalSet(updateList, Real (Set record) {
     104      WriteLn("[UpdateAll] Se actualiza "<<record::identifier);
     105      InstallPackage(record::identifier)
     106    })), 0)
     107  };
     108
     109  ////////////////////////////////////////////////////////////////////////////
     110  Real UpgradeAll(Real void)
     111  ////////////////////////////////////////////////////////////////////////////
     112  {
     113    @Catalog client = Client::GetCatalog(?);
     114    @Catalog server = Server::GetCatalog(?);
     115    Set upgradeList = server::ObtainUpgradeList(client, Version, UnknownDate);
     116    If(Card(upgradeList), SetSum(EvalSet(upgradeList, Real (Set record) {
     117      WriteLn("[UpgradeAll] Se mejora a "<<record::identifier);
     118      InstallPackage(record::identifier)
     119    })), 0)
     120  };
     121
     122  // Estructuras
     123
     124  ////////////////////////////////////////////////////////////////////////////
     125  // Para la gestión de orígenes de código. (Builder)
     126  Struct @PackageSource
     127  ////////////////////////////////////////////////////////////////////////////
     128  {
     129    Text name;
     130    Text type;
     131    Text source
     132  };
     133
     134  ////////////////////////////////////////////////////////////////////////////
     135  // Para la transmisión de información desde los repositorios. (Server)
     136  // Información de un paquete que es relevante para la sincronización de las
     137  // copias locales con el repositorio remoto.
     138  Struct @VersionSynchro
     139  ////////////////////////////////////////////////////////////////////////////
     140  {
     141    Text te_url,                  //URL of repository
     142    Text co_name,                 //Generic name of package
     143    Text co_name_version,         //Name of versioned package
     144    Text te_extra_info,           //Extra information
     145    Text te_min_tol_version,      //Minimum compatible TOL version
     146    Text te_max_tol_version,      //Maximum compatible TOL version
     147    Text te_dependencies,         //Required packages
     148    Date dh_release_date_remote,  //Publication date in remote repository
     149    Date dh_release_date_local,   //Local installing date
     150    Real nu_bytes                 //Size of remote compressed archive
     151  };
     152
     153  ////////////////////////////////////////////////////////////////////////////
     154  // Para la transmisión de información desde los repositorios. (Server)
     155  // Información de un paquete que es relevante para la sincronización de las
     156  // copias locales con el repositorio remoto.
    28157  Struct @PackageSynchro {
    29 //////////////////////////////////////////////////////////////////////////////
    30   Text te_url,                  //URL of repository
    31   Text co_name,                 //Generic name of package
    32   Text te_brief,                //Brief description of package
    33   Text te_extra_info,           //Extra information
    34   Text te_min_tol_version,      //Minimum compatible TOL version
    35   Text te_max_tol_version,      //maximum compatible TOL version
    36   Text co_last_version_remote,  //Name of last remote version
    37   Text co_last_version_local,   //Name of last local version
    38   Date dh_release_date_remote,  //Publication date in remote repository
    39   Date dh_release_date_local,   //Local installing date
    40   Real nu_bytes                 //Size of compressed file
    41 };
    42 
    43 //////////////////////////////////////////////////////////////////////////////
    44 //Información de chequeo de dependencias de un paquete
    45   Struct @TolVerReqChk {
    46 //////////////////////////////////////////////////////////////////////////////
    47   Text co_name_version,
    48   Text te_min_tol_version,
    49   Text te_max_tol_version,
    50   Text te_min_tol_version_deep,
    51   Text te_max_tol_version_deep,
    52   Real min_ok,
    53   Real max_ok,
    54   Real all_ok
    55 };
    56 
    57 //////////////////////////////////////////////////////////////////////////////
    58 Text _.official =
    59   "http://packages.tol-project.org/OfficialTolArchiveNetwork/repository.php";
    60 //////////////////////////////////////////////////////////////////////////////
    61 
    62 Set _.currentTolVersionTokens = Copy(Empty);
    63 Text _.currentTolVersion = "";
    64 Date _.currentTolReleaseDate = UnknownDate;
    65 
    66 //////////////////////////////////////////////////////////////////////////////
    67 Text _.autodoc.member.Initialize =
    68 "Inicializa el servicio de paquetes TOL";
    69 Real Initialize(Real void)
    70 //////////////////////////////////////////////////////////////////////////////
    71 {
    72   If(Card(_.currentTolVersionTokens),False,
    73   {
    74     Set _.currentTolVersionTokens := Tokenizer(Version," ");
    75     Text _.currentTolVersion :=
    76     {
    77      _.currentTolVersionTokens[1]+" "+_.currentTolVersionTokens[2]
    78     };
    79     Date _.currentTolReleaseDate :=
    80     {
    81       TextToDate(
    82        _.currentTolVersionTokens[3]+" "+_.currentTolVersionTokens[4],
    83       "%Y-%m-%d %h:%i:%s")
    84    };
    85    True
    86  })
    87 };
    88 
    89 //////////////////////////////////////////////////////////////////////////////
    90 Text _.autodoc.member.GetCurrentNameVersion =
    91 "Devuelve el nombre de versión actual de un paquete ya cargado";
    92   Text GetCurrentNameVersion(Text packageName, Real specificVersion)
    93 //////////////////////////////////////////////////////////////////////////////
    94 {
    95   NameBlock p = Eval(Tokenizer(packageName,".")[1]);
    96   Text name.version = If(!specificVersion,packageName,
    97     packageName+"."<<p::_.autodoc.version.high+"."<<p::_.autodoc.version.low)
    98 };
    99 
    100 //////////////////////////////////////////////////////////////////////////////
    101 Text _.autodoc.member.GetDeepDependencies =
    102 "Devuelve la lista de dependencias directas e indirectas de un paquete ya "
    103 "cargado";
    104 Set GetDeepDependencies(Text packageName, Real specificVersion)
    105 //////////////////////////////////////////////////////////////////////////////
    106 {
    107 //WriteLn("TRACE GetDeepDependencies 1");
    108   NameBlock p = Eval(Tokenizer(packageName,".")[1]);
    109   Set dep = If(!ObjectExist("Set","p::_.autodoc.dependencies"),Empty,
    110    p::_.autodoc.dependencies);
    111 //WriteLn("TRACE GetDeepDependencies 2");
    112 //WriteLn("TRACE GetDeepDependencies 3");
    113   If(!Card(dep), Copy(Empty),
    114   {
    115     Set aux=EvalSet(dep, Set(Text r)
    116     {
    117       Text name.version =
    118         TolPackage::GetCurrentNameVersion(r, specificVersion);
    119       [[name.version]] <<
    120       TolPackage::GetDeepDependencies(r,specificVersion)
    121     });
    122     Unique(SetConcat(aux))
    123   })
    124 };
    125 
    126 //////////////////////////////////////////////////////////////////////////////
    127 Text _.autodoc.member.PackageInfo.Extract =
    128 "Extrae la información documental de un paquete.";
    129 Set PackageInfo.Extract(NameBlock pkg)
    130 //////////////////////////////////////////////////////////////////////////////
    131 {
    132   Set info = [[
    133     Text _.autodoc.name            = pkg::_.autodoc.name;
    134     Text _.autodoc.brief           = pkg::_.autodoc.brief;
    135     Text _.autodoc.description     = pkg::_.autodoc.description;
    136     Text _.autodoc.url             = pkg::_.autodoc.url;
    137     Set  _.autodoc.keys            = pkg::_.autodoc.keys;
    138     Set  _.autodoc.authors         = pkg::_.autodoc.authors;
    139     Text _.autodoc.minTolVersion   = pkg::_.autodoc.minTolVersion;
    140     Text _.autodoc.maxTolVersion   = pkg::_.autodoc.maxTolVersion;
    141     Real _.autodoc.version.high    = pkg::_.autodoc.version.high;
    142     Real _.autodoc.version.low     = pkg::_.autodoc.version.low;
    143     Date _.autodoc.releaseDate     = pkg::_.autodoc.releaseDate;
    144     Set  _.autodoc.dependencies    = pkg::_.autodoc.dependencies;
    145     Set  _.autodoc.nonTolResources = pkg::_.autodoc.nonTolResources;
    146     Text _.autodoc.versionControl  = pkg::_.autodoc.versionControl;
    147     Text _.autodoc.extra_info      = pkg::_.autodoc.extra_info
    148   ]];
    149   Real SetIndexByName(info);
    150   info
    151 };
    152 
    153 //////////////////////////////////////////////////////////////////////////////
    154 Text _.autodoc.member.PackageInfo.AutoFill =
    155 "Rellena automaticamente algunos campos de información documental del "
    156 "paquete añadiendo los miembros que falten y cambiando su valor si es "
    157 "necesario.";
    158 Set PackageInfo.AutoFill(NameBlock pkg, Date releaseDate)
    159 //////////////////////////////////////////////////////////////////////////////
    160 {
    161   Text name = Name(pkg);
    162   Text name.version = name+"."<<
    163     pkg::_.autodoc.version.high+"."<<pkg::_.autodoc.version.low;
    164   Set dep = TolPackage::GetDeepDependencies(name, True);
    165 
    166   Real If(!ObjectExist("Text", "pkg::_.autodoc.name"),
    167   {
    168     AddMember(pkg,{Text _.autodoc.name = name })
    169   },
    170   {
    171     Text pkg::_.autodoc.name := name;
    172     True
    173   });
    174   Real If(!ObjectExist("Set", "pkg::_.autodoc.dependencies"),
    175   {
    176     AddMember(pkg,{Set _.autodoc.dependencies = dep })
    177   },
    178   {
    179     Set pkg::_.autodoc.dependencies := dep;
    180     True
    181   });
    182   Real If(!ObjectExist("Date","pkg::_.autodoc.releaseDate"),
    183   {
    184     Real AddMember(pkg,{Date _.autodoc.releaseDate = releaseDate})
    185   },
    186   {
    187     Date pkg::_.autodoc.releaseDate := releaseDate;
    188     True
    189   });
    190   Real If(!ObjectExist("Set", "pkg::_.autodoc.authors"),
    191   {
    192     AddMember(pkg,{Set _.autodoc.authors = Copy(Empty) })
    193   });
    194   Real If(!ObjectExist("Set", "pkg::_.autodoc.keys"),
    195   {
    196     AddMember(pkg,{Set _.autodoc.keys = Copy(Empty) })
    197   });
    198   Real If(!ObjectExist("Set", "pkg::_.autodoc.nonTolResources"),
    199   {
    200     AddMember(pkg,{Set _.autodoc.nonTolResources = Copy(Empty) })
    201   });
    202   Real If(!ObjectExist("Text", "pkg::_.autodoc.versionControl"),
    203   {
    204     AddMember(pkg,{Text _.autodoc.versionControl = "" })
    205   });
    206   Real If(!ObjectExist("Text", "pkg::_.autodoc.maxTolVersion"),
    207   {
    208     Real AddMember(pkg,{Text _.autodoc.maxTolVersion = "v999999999999999999" })
    209   });
    210   Real If(!ObjectExist("Text", "pkg::_.autodoc.extra_info"),
    211   {
    212     Real AddMember(pkg,{Text _.autodoc.extra_info = "" })
    213   });
    214   PackageInfo.Extract(pkg)
    215 };
    216 
    217 //////////////////////////////////////////////////////////////////////////////
    218 Text _.autodoc.member.PackageInfo.Build =
    219 "Builds the info.oza file with documental information about a loaded "
    220 "package.";
    221 Real PackageInfo.Build(NameBlock pkg, Text dirPath, Date releaseDate_)   
    222 //////////////////////////////////////////////////////////////////////////////
    223 {
    224   Date releaseDate = Date If(""<<releaseDate_!="Unknown",
    225   {
    226     releaseDate_
    227   },
    228   {
    229     Text name = Name(pkg);
    230     Text name.version = name+"."<<
    231      pkg::_.autodoc.version.high+"."<<pkg::_.autodoc.version.low;
    232     Date gmt = Copy(NowGmt);
    233     Date loc = Copy(Now);
    234     Real lag = Round(DateDif(S(0),loc,gmt)/10)*10;
    235     Text oza = dirPath+name.version+".oza";
    236     Date local = FileTime(oza);
    237     Succ(local,S(0),lag)
    238   });
    239   Set info = PackageInfo.AutoFill(pkg,releaseDate);
    240   Real OSDirMake(dirPath);
    241   Real Ois.Store(info,dirPath+"info.oza")
    242 };
    243 
     158  ////////////////////////////////////////////////////////////////////////////
     159    Text te_url,                  //URL of repository
     160    Text co_name,                 //Generic name of package
     161    Text te_brief,                //Brief description of package
     162    Text te_extra_info,           //Extra information
     163    Text te_min_tol_version,      //Minimum compatible TOL version
     164    Text te_max_tol_version,      //Maximum compatible TOL version
     165    Text co_last_version_remote,  //Name of last remote version
     166    Text co_last_version_local,   //Name of last local version
     167    Date dh_release_date_remote,  //Publication date in remote repository
     168    Date dh_release_date_local,   //Local installing date
     169    Real nu_bytes                 //Size of compressed file
     170  };
     171
     172  // Lists
     173
     174  ////////////////////////////////////////////////////////////////////////////
     175  Set _.GetVersSyncInfo(Real void) // Compatibilidad GUI
     176  ////////////////////////////////////////////////////////////////////////////
     177  {
     178    @Catalog client = Client::GetCatalog(?);
     179    @Catalog server = Server::GetCatalog(?);
     180    SetConcat(EvalSet(server::_.records, Set (Set list) {
     181      EvalSet(list, Set (Set record) {
     182        Text dependencies = If(Card(record::freeDependencies), {
     183          SetSum([[ record::freeDependencies[1] ]]
     184            << For(2, Card(record::freeDependencies), Text (Real i) {
     185              ", "<<record::freeDependencies[i]
     186          }))
     187        }, "");
     188        Text localIdentifier = client::ObtainIdentifier_Show(record::name,
     189          Version, UnknownDate, 0);
     190        Date localRelease = If(TextLength(localIdentifier), {
     191          Set localRecord = client::GetRecord(localIdentifier);
     192          localRecord::release
     193        }, TheBegin);
     194        @VersionSynchro(record::repository, record::name, record::identifier,
     195          "<...>", record::minTolVersion, record::maxTolVersion,
     196          dependencies, record::release, localRelease, ?)
     197      })
     198    }))
     199  };
     200
     201  ////////////////////////////////////////////////////////////////////////////
     202  Set _.GetPackSyncInfo(Text tolVersion) // Compatibilidad GUI
     203  ////////////////////////////////////////////////////////////////////////////
     204  {
     205    @Catalog client = Client::GetCatalog(?);
     206    @Catalog server = Server::GetCatalog(?);
     207    EvalSet(server::GetCompatibleList(tolVersion, UnknownDate),
     208      Set (Set record) {
     209      Text localIdentifier = client::ObtainIdentifier_Show(record::name,
     210        Version, UnknownDate, 0);
     211      Date localRelease = If(TextLength(localIdentifier), {
     212        Set localRecord = client::GetRecord(localIdentifier);
     213        localRecord::release
     214      }, TheBegin);
     215      @PackageSynchro(record::repository, record::name, "<...>", "<...>",
     216        record::minTolVersion, record::maxTolVersion, record::identifier,
     217        localIdentifier, record::release, localRelease, ?)
     218    })
     219  };
     220
     221  ////////////////////////////////////////////////////////////////////////////
     222  Set GetInstallationList(Set patterns) // GUI
     223  ////////////////////////////////////////////////////////////////////////////
     224  {
     225    TolPackage::@Catalog catalog = TolPackage::Server::GetCatalog(?);
     226    Set deepDs = Unique(SetConcat(EvalSet(patterns, Set (Text pattern) {
     227      [[pattern]]<<catalog::GetDeepDependencies(pattern, Version, UnknownDate)
     228    })));
     229    Set catalog::IdentifyPackages(deepDs, Version, UnknownDate)
     230  };
     231
     232  ////////////////////////////////////////////////////////////////////////////
     233  Set _ListA = Ois.Load(GetAbsolutePath("listA.oza"))[1];
     234  ////////////////////////////////////////////////////////////////////////////
     235  Set AtListA(Text listId)
     236  ////////////////////////////////////////////////////////////////////////////
     237  {
     238    Real index = FindIndexByName(_ListA, listId);
     239    If(index, _ListA[index], {
     240      Set parts = Tokenizer(listId, ".");
     241      Real index2 = FindIndexByName(_ListA, parts[1]);
     242      If(index2, {
     243        Set info = DeepCopy(_ListA[index2]);
     244        Real info::_.autodoc.version.high := Eval(parts[2]);
     245        Real info::_.autodoc.version.low := Eval(parts[3]);
     246        Text identifier = parts[1]<<"."<<parts[2]<<"."<<parts[3];
     247        PutName(identifier, info)
     248      }, Copy(Empty))
     249    })
     250  };
     251
     252
     253  ////////////////////////////////////////////////////////////////////////////
  • tol/stdlib/TolPackage/server.tol

    r9062e36 r6f9ab22  
    22//////////////////////////////////////////////////////////////////////////////
    33// FILE   : server.tol
    4 // PURPOSE: TolPackage server side tools
    5 //////////////////////////////////////////////////////////////////////////////
    6 
    7 Text _.autodoc.member.Server=
    8 "Sistema servidor de gestión de paquetes TOL";
    9 
    10 //////////////////////////////////////////////////////////////////////////////
    11 NameBlock Server = [[
    12 //////////////////////////////////////////////////////////////////////////////
    13 
    14 Text _.localRoot = TolPackage::_.localRoot +"Server/";
    15 
    16 Set _.supportedPlatforms =
     4// PURPOSE: TolPackage server tools
     5//////////////////////////////////////////////////////////////////////////////
     6
     7Text _.autodoc.member.Server =
     8  "Sistema servidor de paquetes TOL desde repositorios  remotos.";
     9//////////////////////////////////////////////////////////////////////////////
     10@LocalBlock Server =
     11//////////////////////////////////////////////////////////////////////////////
    1712[[
    18   "Windows_x86_32",
    19   "Linux_x86_32"
     13  // [API]
     14  //  * @Catalog GetCatalog(Real void)
     15  //  * Real UpdateCatalog(Real void)
     16  //  * Text DownloadPackage(Text identifier)
     17  //  * Text DownloadCompatible(Text pattern, Text tolVersion, Date date)
     18  //  * Text DownloadLastCompatible(Text pattern)
     19  //  * Text DownloadPackageAt(Text identifier, Text path)
     20  //  * Real Initialize(Real void)
     21  // [API DB]
     22  //  * Real DB.DeletePackage(NameBlock repository.db, Text identifier)
     23  //  * Real DB.IdentifyRepository(NameBlock repository.db, Text url)
     24  //  * Real DB.UploadPackage(NameBlock repository.db, Text pkg.path.zip)
     25  // [API antigua]
     26  //  * Text _.localRoot;
     27  //  - Set _.supportedPlatforms
     28  //  * Real Initialize(Real void)
     29  //  - Text FormatSet(Set set)
     30  //    => _SqlFormatSet
     31  //  - Text FormatSetOfText(Set set)
     32  //    => _SqlFormatSetOfText
     33  //  - Text BuildPackage(Text name, Text sourceRoot, Text destination,
     34  //      Real removeDir)
     35  //    => Builder::BuildPackage
     36  //  - Real UploadPackage(NameBlock repository.db, Text pkg.path.zip)
     37  //    => Builder::UploadPackageXX -> DB.UploadPackage
     38  //  - Real BuildAndUploadPackage
     39  //  - Real RemovePackageVersion(Text name, Real nu_version_high,
     40  //      Real nu_version_low, NameBlock repository.db)
     41  //    => Builder::DestroyPackageXX -> DB.DeletePackage
     42  //  - Real Set CheckTolDependencies(NameBlock repository.db, Real fix)
     43  // <notas>
     44  //  + Se mueven las funciones de construcción de paquetes a Builder
     45  //  + Se incorporan las funciones de acceso y consulta de los repositorios
     46
     47  Text _.localRoot = _.localRoot<<"Server/";
     48  Set _.catalog = Copy(Empty);
     49
     50  ////////////////////////////////////////////////////////////////////////////
     51  @Catalog GetCatalog(Real void)
     52  ////////////////////////////////////////////////////////////////////////////
     53  {
     54    Real Initialize(?);
     55    If(Card(_.catalog), _.catalog[1])
     56  };
     57
     58  ////////////////////////////////////////////////////////////////////////////
     59  Real UpdateCatalog(Real void)
     60  ////////////////////////////////////////////////////////////////////////////
     61  {
     62    If(Card(_.catalog), {
     63      @Catalog catalog = GetCatalog(?);
     64      catalog::Update(?)
     65    }, {
     66      // Si no existía no se rehace
     67      @Catalog catalog = GetCatalog(?);
     68    1})
     69  };
     70
     71  ////////////////////////////////////////////////////////////////////////////
     72  Text DownloadPackage(Text identifier)
     73  ////////////////////////////////////////////////////////////////////////////
     74  {
     75    DownloadPackageAt(identifier, _.localRoot)
     76  };
     77
     78  ////////////////////////////////////////////////////////////////////////////
     79  Text DownloadCompatible(Text pattern, Text tolVersion, Date date)
     80  ////////////////////////////////////////////////////////////////////////////
     81  {
     82    @Catalog catalog = GetCatalog(?);
     83    Text compatibleId = catalog::ObtainIdentifier(pattern, tolVersion,
     84      date);
     85    If(TextLength(compatibleId), DownloadPackage(compatibleId), "")
     86  };
     87
     88  ////////////////////////////////////////////////////////////////////////////
     89  Text DownloadLastCompatible(Text pattern)
     90  ////////////////////////////////////////////////////////////////////////////
     91  {
     92    DownloadCompatible(pattern, Version, UnknownDate)
     93  };
     94
     95  ////////////////////////////////////////////////////////////////////////////
     96  Text DownloadPackageAt(Text identifier, Text path)
     97  ////////////////////////////////////////////////////////////////////////////
     98  {
     99    @Catalog catalog = GetCatalog(?);
     100    Set record = catalog::GetRecord(identifier);
     101    If(Card(record), {
     102      Text encoded = GetUrlContents(record::repository
     103        <<"?tol_package_version=1.1"
     104        <<"&action=download&format=base64"
     105        <<"&package="<<identifier);
     106      Real OSDirMake(_AsOSDir(path));
     107      Text zipFile = path<<identifier<<".zip";
     108      Real DecodeBase64ToFile(zipFile, encoded);
     109      zipFile     
     110    }, {
     111      WriteLn("No se encuentra el paquete '"<<identifier<<"'.", "E");
     112      ""
     113    })
     114  };
     115
     116  // [DB] Funciones para la interacción con la base de datos
     117
     118  ////////////////////////////////////////////////////////////////////////////
     119  Real DB.DeletePackage(NameBlock repository.db, Text identifier)
     120  //[OLD] Server::RemovePackageVersion
     121  ////////////////////////////////////////////////////////////////////////////
     122  {
     123    Set parts = Tokenizer(identifier, ".");
     124    If(Card(parts)==3, {
     125      Real repository.db::Open(0);
     126      Text delete.query = "
     127        DELETE FROM package_f_contents
     128        WHERE co_name = '"<<parts[1]<<"'
     129          AND nu_version_high = "<<parts[2]<<"
     130          AND nu_version_low = "<<parts[3]<<"
     131      ";
     132      Real reg = DBExecQuery(delete.query);
     133      Real repository.db::Close(0);
     134      reg
     135    }, 0)
     136  };
     137
     138  ////////////////////////////////////////////////////////////////////////////
     139  Real DB.IdentifyRepository(NameBlock repository.db, Text url)
     140  ////////////////////////////////////////////////////////////////////////////
     141  {
     142    Real repository.db::Open(0);
     143    Real DBExecQuery("set client_encoding to '""latin1""'");
     144    Text repository.query = "
     145      SELECT id_repository, co_repository, ds_repository,
     146        co_access, co_version_control, te_url
     147      FROM repository_d_def AS D,
     148        repository_d_access AS A,
     149        repository_d_version_control AS V
     150      WHERE A.id_access          = D.id_access
     151        AND V.id_version_control = D.id_version_control
     152        AND (    te_url          = '"<<url<<"'
     153              OR te_url          = '"<<url<<"repository.php' )
     154    ";
     155    Set repository = DBTable(repository.query);
     156    (repository[1])::id_repository
     157  };
     158
     159  ////////////////////////////////////////////////////////////////////////////
     160  Real DB.UploadPackage(NameBlock repository.db, Text pkg.path.zip)
     161  //[OLD] Server::UploadPackage
     162  ////////////////////////////////////////////////////////////////////////////
     163  {
     164    Text _MID = "[UploadPackage] ";
     165    Text root = GetFilePath(pkg.path.zip);
     166    Text pkg.name.zip = GetFileName(pkg.path.zip);
     167    Text pkg.name = Replace(pkg.name.zip,".zip","");
     168    Set name.tok = Tokenizer(pkg.name,".");
     169    Real nu_version_high = Eval(name.tok[2]);
     170    Real nu_version_low = Eval(name.tok[3]);
     171    Real PackArchive::UnpackFull("ZipArchive",root+pkg.name,False);
     172    Text oza = root+pkg.name+"/info.oza";
     173    Set pkg = Include(oza);
     174    Text name = pkg::_.autodoc.name;
     175    Real If(pkg::_.autodoc.version.high!=nu_version_high,
     176    {
     177      WriteLn("Wrong version high number "<<
     178        nu_version_high+"!="<<pkg::_.autodoc.version.high,"W");
     179      Real pkg::_.autodoc.version.high := nu_version_high
     180    });
     181    Real If(pkg::_.autodoc.version.low!=nu_version_low,
     182    {
     183      WriteLn("Wrong version low number "<<
     184        nu_version_low+"!="<<pkg::_.autodoc.version.low,"W");
     185      Real pkg::_.autodoc.version.low := nu_version_low
     186    });
     187    Real repId = DB.IdentifyRepository(repository.db, pkg::_.autodoc.url);
     188    If(Not(repId), {
     189      WriteLn(_MID+"Unknown repository '"+pkg::_.autodoc.url+"'","E");
     190      False
     191    }, {
     192      Text bl_contents = EncodeBase64FromFile(pkg.path.zip);
     193      Real nu_bytes = FileBytes(pkg.path.zip);
     194      Real id_format = 1;
     195      Text te_max_tol_version = pkg::_.autodoc.maxTolVersion;
     196      Text te_extra_info = "";
     197      Text insert.query = "
     198        INSERT INTO package_f_contents (
     199          id_repository, co_name, nu_version_high, nu_version_low,
     200          te_brief, te_description,
     201          te_keys, te_authors, te_min_tol_version, dh_release_date, 
     202          te_dependencies, te_non_tol_resources, te_version_control,
     203          bl_contents, nu_bytes, id_format, te_max_tol_version, te_extra_info)
     204        VALUES (
     205          "<<repId<<",
     206          '"<<pkg::_.autodoc.name<<"',
     207          "<<pkg::_.autodoc.version.high<<",
     208          "<<pkg::_.autodoc.version.low<<",
     209          '"<<pkg::_.autodoc.brief<<"',
     210          '"<<Replace(pkg::_.autodoc.description, "\n", "<BR>")<<"',
     211          '"<<_SqlFormatSetOfText(pkg::_.autodoc.keys)<<"',
     212          '"<<_SqlFormatSetOfText(pkg::_.autodoc.authors)<<"',
     213          '"<<pkg::_.autodoc.minTolVersion<<"',
     214          '"<<_SqlFormatDate(pkg::_.autodoc.releaseDate)<<"',
     215          '"<<_SqlFormatSetOfText(pkg::_.autodoc.dependencies)<<"',
     216          '"<<_SqlFormatSet(pkg::_.autodoc.nonTolResources)<<"',
     217          E'"<<_SqlFormatVersionControl(pkg::_.autodoc.versionControl)<<"',
     218          decode('"<<bl_contents<<"', 'base64'),
     219          "<<nu_bytes<<",
     220          "<<id_format<<",
     221          '"<<pkg::_.autodoc.maxTolVersion<<"',
     222          '"<<te_extra_info<<"'
     223        )
     224      ";
     225      Real num_reg = DBExecQuery(insert.query);
     226      If(!num_reg, WriteLn(_MID+
     227        "Package is already in the repository. Please upgrade the "
     228        "version numbers or delete the register of existent package.","E"));
     229      Real repository.db::Close(0);
     230      num_reg
     231    })
     232  };
     233
     234  ////////////////////////////////////////////////////////////////////////////
     235  Text _SqlFormatSet(Set set)
     236  ////////////////////////////////////////////////////////////////////////////
     237  {
     238    Text bl = " ";
     239    Text name = Name(set);
     240    "Set { "+If(name=="", "", Name(set)<<" = ")+bl+If(Card(set), {
     241      "[["+bl+SetSum(For(1, Card(set), Text (Real k) {
     242        Text gk = Grammar(set[k]);
     243        Text nk = Name(set[k]);
     244        Text dec = "  "+gk+" { "+If(nk=="","",nk+" = ");
     245        If(k>1,","+bl,"")+Case(
     246          gk=="Text", dec+"\""+set[k]+"\" } ",
     247          gk=="Real", dec<<set[k]+" } ",
     248          gk=="Date", dec<<set[k]+" } ",
     249          gk=="Set",  _SqlFormatSet(set[k]),
     250          True, {
     251            WriteLn("[TolPackage::Server::_SqlFormatSet] "
     252            " Unexpected object "+If(nk,nk+" ","")+"of invalid type "+gk,"E"),
     253            ""}
     254        )
     255      }))+bl+"]]"
     256    }, "Copy(Empty)")<<" }"
     257  };
     258
     259  ////////////////////////////////////////////////////////////////////////////
     260  Text _SqlFormatSetOfText(Set set)
     261  ////////////////////////////////////////////////////////////////////////////
     262  {
     263    If(Card(set), {
     264      SetSum(For(1, Card(set), Text (Real k) {
     265        Text gk = Grammar(set[k]);
     266        If(k>1, ",", "") << If(gk=="Text", set[k], {
     267          Text nk = Name(set[k]);
     268          WriteLn("[TolPackage::_SqlFormatSetOfText] "
     269            " Unexpected object "+If(nk,nk+" ","")+"of invalid type "+gk,"E"),
     270          ""
     271        })
     272      }))
     273    }, "")
     274  };
     275 
     276  ////////////////////////////////////////////////////////////////////////////
     277  Text _SqlFormatDate(Date date)
     278  ////////////////////////////////////////////////////////////////////////////
     279  {
     280    FormatDate(date,"%c%Y-%m-%d %h:%i:%s")
     281  };
     282
     283  ////////////////////////////////////////////////////////////////////////////
     284  Text _SqlFormatVersionControl(Text versionControl)
     285  ////////////////////////////////////////////////////////////////////////////
     286  {
     287    ReplaceTable(versionControl, [[ [["\n", "<BR>"]], [["'", "\""]], //\"
     288      [[";", ","]] ]])
     289  };
     290
     291  ////////////////////////////////////////////////////////////////////////////
     292  Real _initialized = False;
     293  ////////////////////////////////////////////////////////////////////////////
     294  Real Initialize(Real void)
     295  ////////////////////////////////////////////////////////////////////////////
     296  {
     297    If(_initialized, 0, {
     298      Real _initialized := True;
     299      Real OSDirMake(_AsOSDir(_.localRoot));
     300      // [A] Se construye el catálogo remoto
     301      Real t1 = Copy(Time);
     302      Set _.catalog := [[ @Catalog::Remote(TolConfigManager::Config
     303        ::Upgrading::TolPackage::Repositories) ]];
     304      Real t2 = Copy(Time);
     305      Real t21 = Round((t2 -t1)*100)/100;
     306      WriteLn("[TolPackage::Server] Catalog "<<t21<<" s.");
     307    1})
     308  }
    20309]];
    21 
    22 //////////////////////////////////////////////////////////////////////////////
    23 Text _.autodoc.member.Initialize =
    24 "Inicializa el servidor del servicio de paquetes TOL";
    25 Real Initialize(Real void)
    26 //////////////////////////////////////////////////////////////////////////////
    27 {
    28   Real OSDirMake(_.localRoot);
    29   Set EvalSet(_.supportedPlatforms, Real(Text platform)
    30   {
    31     Real OSDirMake(_.localRoot+platform)
    32   });
    33   True
    34 };
    35 
    36 
    37 //////////////////////////////////////////////////////////////////////////////
    38 Text _.autodoc.member.FormatSet=
    39 "Builds the TOL expression of a Set";
    40 Text FormatSet(Set set)
    41 //////////////////////////////////////////////////////////////////////////////
    42 {
    43   Text bl = " ";
    44   Text name = Name(set);
    45   "Set { "+If(name=="","",Name(set)+" = ")+bl+
    46   If(!Card(set),"Copy(Empty)",
    47   {
    48     "[["+bl+
    49     SetSum(For(1,Card(set),Text(Real k)
    50     {
    51       Text gk = Grammar(set[k]);
    52       Text nk = Name(set[k]);
    53       Text dec = "  "+gk+" { "+If(nk=="","",nk+" = ");
    54       If(k>1,","+bl,"")+
    55       Case(
    56       gk=="Text", dec+"\""+set[k]+"\" } ",
    57       gk=="Real", dec<<set[k]+" } ",
    58       gk=="Date", dec<<set[k]+" } ",
    59       gk=="Set",  FormatSet(set[k]),
    60       1==1,
    61       {
    62         WriteLn("[TolPackage::Server::FormatSet] "
    63         " Unexpected object "+If(nk,nk+" ","")+"of invalid type "+gk,"E"),
    64         ""
    65       })
    66     }))+bl+"]]"
    67   })+
    68   " }"
    69 };
    70 
    71 
    72 //////////////////////////////////////////////////////////////////////////////
    73 Text _.autodoc.member.SqlFormatSetOfText =
    74 "Builds the SQL expression of a Set of texts without quotes nor brackets";
    75 Text SqlFormatSetOfText(Set set)
    76 //////////////////////////////////////////////////////////////////////////////
    77 {
    78   If(!Card(set),"",
    79   {
    80     SetSum(For(1,Card(set),Text(Real k)
    81     {
    82       Text gk = Grammar(set[k]);
    83       If(k>1,",","")+
    84       Case(
    85       gk=="Text", set[k],
    86       1==1,
    87       {
    88         Text nk = Name(set[k]);
    89         WriteLn("[TolPackage::Server::SqlFormatSetOfText] "
    90         " Unexpected object "+If(nk,nk+" ","")+"of invalid type "+gk,"E"),
    91         ""
    92       })
    93     }))
    94   })
    95 };
    96 
    97 
    98 
    99 //////////////////////////////////////////////////////////////////////////////
    100 Text _.autodoc.member.BuildPackage =
    101 "Construye el archivo comprimido correspondiente a un paquete TOL a partir "
    102 "del código situado en el directorio fuente:\n"
    103 "  \"<sourceRoot>/<name>\"\n"
    104 "\n"
    105 "El resultado se almacena en el directorio de destino con el nombre de "
    106 "la versión específica que conste en el NameBlock del paquete:"
    107 "\n"
    108 "  \"<destination>/<name>.<high>.<low>.zip\"\n"
    109 "\n";
    110 Text BuildPackage(
    111   Text name,         //Nombre del paquete (sin versión)
    112   Text sourceRoot,   //Directorio raíz del código fuente
    113   Text destination,  //Directorio de destino del paquete
    114   Real removeDir)    //Si es cierto se borra el directorio descomprimido
    115 //////////////////////////////////////////////////////////////////////////////
    116 {
    117   Date release.gmt = Copy(NowGmt);
    118   Text _MID = "[BuildPackage] ";
    119   Set pkgCnt = If( ObjectExist( "NameBlock", name ), [[ NameBlock Eval( name ) ]], {
    120         WriteLn(_MID+sourceRoot+name+" -> "+destination);
    121         Set Eval("Set IncludeTOL(\""+
    122                  sourceRoot+name+"/"+name+".tol\",True)")
    123       } );
    124   NameBlock pkg = pkgCnt[1];
    125   Text name.version = name+"."<<
    126     pkg::_.autodoc.version.high+"."<<pkg::_.autodoc.version.low;
    127 
    128   Text minTolVersion = If(!ObjectExist("Text","pkg::_.autodoc.minTolVersion"),
    129    "v000000000000000000",  pkg::_.autodoc.minTolVersion);
    130   Text maxTolVersion = If(!ObjectExist("Text","pkg::_.autodoc.maxTolVersion"),
    131    "v999999999999999999",  pkg::_.autodoc.maxTolVersion);
    132 
    133   Real okTolVersion = And(
    134     Compare.VersionString(minTolVersion,TolPackage::_.currentTolVersion)<=0,
    135     Compare.VersionString(maxTolVersion,TolPackage::_.currentTolVersion)>=0);
    136   Real If(!okTolVersion,
    137   {
    138     Error("[TolPackage::Server::BuildPackage] cannot create package "<<name.version+
    139     "with current TOL version "<<Version+". It requires a version in interval "+
    140     "["<<pkg::_.autodoc.minTolVersion+","<<pkg::_.autodoc.maxTolVersion+"]");
    141     Real Stop
    142   });
    143   Text ppRoot_ = destination+name.version;
    144   Text ppRoot = ppRoot_+"/";
    145   Real TolPackage::PackageInfo.Build(pkgCnt[1],ppRoot,release.gmt);
    146   Set nonTolResources = pkg::_.autodoc.nonTolResources;
    147 
    148 
    149   Real OSDirMake(ppRoot);
    150   Real Ois.Store(pkgCnt,ppRoot+name.version+".oza");
    151 
    152   Real cleanResource(Text dest)
    153   {
    154     Set dir = GetDir(dest);
    155     Set sub = dir[2];
    156     Set EvalSet(sub,Real(Text s)
    157     {
    158       Text dest_new = dest+"/"+s;
    159       Text ls = ToLower(s);
    160       If(Or(ls==".svn",ls=="svn",ls=="cvs",ls==".cvs"),
    161         OSDirRemove(dest_new),
    162         cleanResource(dest_new))
    163     });
    164     True
    165   };
    166 
    167   Real processResourceText(Text resource)
    168   {
    169     Text orig = sourceRoot+"/"+name+"/"+resource;
    170     Text dest = ppRoot+"/"+resource;
    171     Real OSDirMake(dest);
    172     If(OSUnix, OSDirRemove(dest));
    173   //WriteLn("TRACE dir copy '"+orig+"' -> '"+dest+"'");
    174     Real OSDirCopy(orig,dest);
    175     cleanResource(dest)
    176   };
    177   Real processResourceSet(Set resourceSet)
    178   {
    179     Set EvalSet(resourceSet, processResourceText);
    180     True
    181   };
    182   Set EvalSet(nonTolResources, Real (Anything res)
    183   {
    184     Text gra = Grammar(res);
    185     WriteLn(_MID+"Processing resource "+gra+" "<<res);
    186     Eval("processResource"+gra+"(res)")
    187   });
    188   Text ppr = ReplaceSlash(ppRoot_);
    189   Real PackArchive::PackFull("ZipArchive", ppr, removeDir);
    190   ppRoot_+".zip"
    191 };
    192 
    193 
    194 //////////////////////////////////////////////////////////////////////////////
    195 Text _.autodoc.member.UploadPackage =
    196 "Sube al repositorio remoto un paquete desde el archivo local comprimido "
    197 "creado con TolPackage::Server::BuildPackage y dado por el argumento:\n"
    198 "  Text pkg.path.zip = \"<directory>/<name>.<high>.<low>.zip\"\n";
    199 Real UploadPackage(NameBlock repository.db, Text pkg.path.zip)
    200 //////////////////////////////////////////////////////////////////////////////
    201 {
    202   Text _MID = "[UploadPackage] ";
    203   Text root = GetFilePath(pkg.path.zip);
    204   Text pkg.name.zip = GetFileName(pkg.path.zip);
    205   Text pkg.name = Replace(pkg.name.zip,".zip","");
    206   Set name.tok = Tokenizer(pkg.name,".");
    207   Real nu_version_high = Eval(name.tok[2]);
    208   Real nu_version_low = Eval(name.tok[3]);
    209   Real PackArchive::UnpackFull("ZipArchive",root+pkg.name,False);
    210   Text oza = root+pkg.name+"/info.oza";
    211   Set pkg = Include(oza);
    212   Text name = pkg::_.autodoc.name;
    213   Real If(pkg::_.autodoc.version.high!=nu_version_high,
    214   {
    215     WriteLn("Wrong version high number "<<
    216       nu_version_high+"!="<<pkg::_.autodoc.version.high,"W");
    217     Real pkg::_.autodoc.version.high := nu_version_high
    218   });
    219   Real If(pkg::_.autodoc.version.low!=nu_version_low,
    220   {
    221     WriteLn("Wrong version low number "<<
    222       nu_version_low+"!="<<pkg::_.autodoc.version.low,"W");
    223     Real pkg::_.autodoc.version.low := nu_version_low
    224   });
    225   Real repository.db::Open(0);
    226   Real DBExecQuery("set client_encoding to '""latin1""'");
    227   Text repository.query = "
    228   SELECT
    229     id_repository, co_repository, ds_repository,
    230     co_access, co_version_control, te_url
    231   FROM
    232     repository_d_def AS D,
    233     repository_d_access AS A,
    234     repository_d_version_control AS V
    235   WHERE
    236       A.id_access          = D.id_access
    237   AND V.id_version_control = D.id_version_control
    238   AND (    te_url          = '"+pkg::_.autodoc.url+"'
    239         OR te_url          = '"+pkg::_.autodoc.url+"repository.php' )
    240   ";
    241 //WriteLn("TRACE "+_MID+"repository.query=\n"+repository.query);
    242   Set repository = DBTable(repository.query);
    243   If(!Card(repository),
    244   {
    245     WriteLn(_MID+"Unknown repository '"+pkg::_.autodoc.url+"'","E");
    246     False
    247   },
    248   {
    249     Set dep = pkg::_.autodoc.dependencies;
    250     Set aut = pkg::_.autodoc.authors;
    251     Set key = pkg::_.autodoc.keys;
    252     Set res = pkg::_.autodoc.nonTolResources;
    253     Text verCnt = ReplaceTable(pkg::_.autodoc.versionControl,[[
    254       [["\n","<BR>"]],
    255       [["'","\""]] ,
    256       [[";",","]] ]]);
    257     Text bl_contents = EncodeBase64FromFile(pkg.path.zip);
    258     Real nu_bytes = FileBytes(pkg.path.zip);
    259     Real id_format = 1;
    260     Text te_max_tol_version = pkg::_.autodoc.maxTolVersion;
    261     Text te_extra_info = "";
    262   //Text exist.query =
    263     Text insert.query = "
    264     INSERT INTO package_f_contents(
    265       id_repository, co_name, nu_version_high, nu_version_low,
    266       te_brief, te_description,
    267       te_keys, te_authors, te_min_tol_version, dh_release_date, 
    268       te_dependencies, te_non_tol_resources, te_version_control,
    269       bl_contents, nu_bytes, id_format, te_max_tol_version, te_extra_info)
    270     VALUES (
    271      "<<(repository[1])::id_repository+", "+
    272      "'"+name+"', \n"+
    273      ""<<pkg::_.autodoc.version.high+", \n"+
    274      ""<<pkg::_.autodoc.version.low+", \n"+
    275      "'"<<pkg::_.autodoc.brief+"', \n"+
    276      "'"+Replace(pkg::_.autodoc.description,"\n","<BR>")+"', \n"+
    277      "'"<<TolPackage::Server::SqlFormatSetOfText(pkg::_.autodoc.keys)+"', \n"+
    278      "'"<<TolPackage::Server::SqlFormatSetOfText(pkg::_.autodoc.authors)+"', \n"+
    279      "'"<<pkg::_.autodoc.minTolVersion+"', \n"+
    280      "'"<<FormatDate(pkg::_.autodoc.releaseDate,"%c%Y-%m-%d %h:%i:%s")+"', \n"+
    281      "'"<<TolPackage::Server::SqlFormatSetOfText(dep)+"', \n"+
    282      "'"<<TolPackage::Server::FormatSet(res)+"', \n"+
    283      "E'"<<verCnt+"', \n"+
    284      "decode('"<<bl_contents+"','base64'), \n"+
    285      ""<<nu_bytes+", \n"+
    286      ""<<id_format+", \n"+
    287      "'"<<te_max_tol_version+"', \n"+
    288      "'"<<te_extra_info+"' \n"+
    289     ");";
    290   //WriteLn("TRACE "+_MID+"insert.query=\n" + insert.query);
    291 
    292     Real num_reg = DBExecQuery(insert.query);
    293     If(!num_reg, WriteLn(_MID+
    294       "Package is already in the repository. Please upgrade the "
    295       "version numbers or delete the register of existent package.","E"));
    296     Real repository.db::Close(0);
    297     num_reg
    298   })
    299 };
    300 
    301 //////////////////////////////////////////////////////////////////////////////
    302 Text _.autodoc.member.BuildAndUploadPackage =
    303 "Construye el archivo comprimido correspondiente a un paquete TOL a partir "
    304 "del código situado en el directorio fuente:\n"
    305 "  \"<sourceRoot>/<name>\"\n"
    306 "\n"
    307 "y luego lo sube al repositorio remoto.\n"
    308 "La copia temporal del archivo comprimido del paquete se queda en el "
    309 "directorio del servidor a efectos de depuración si surgen problemas "
    310 "pero se puede borrar si se desea.\n"
    311 "Por último se chequeará la instalación según lo indicado:"
    312 "  Si checkInstallMode = \"local\" se usa la copia local comprimida.\n"
    313 "  Si checkInstallMode = \"remote\" se instala desde el repositorio.\n"
    314 "  En otro caso no se instala nada.\n"
    315 "Devuelve un código que indica en qué fase ha habido problemas:\n"
    316 "  0 todo parece haber ido bien\n"
    317 "  1 hubo fallos en la construcción (entonces la subida no se intenta)\n"
    318 "  2 no hubo fallos en la construcción pero sí en la subida (la instalación no se intenta)\n"
    319 "  3 no hubo fallos en la construcción ni en la subida pero la instalación ha dado errores\n";
    320 Real BuildAndUploadPackage(
    321   Text name,                //Nombre del paquete (sin versión)
    322   Text sourceRoot,          //Directorio raíz del código fuente
    323   Text repository.url,      //URL del repositorio
    324   NameBlock repository.db,  //Conexión a la base de datos
    325   Text checkInstallMode)    //Modo de chequeo de la instalación
    326 //////////////////////////////////////////////////////////////////////////////
    327 {
    328   Real nErr0 = Copy(NError);
    329   Text tmp = _.localRoot;
    330   Real OSDirMake(tmp);
    331   Text pkg.path.zip = TolPackage::Server::BuildPackage(
    332     name, sourceRoot, tmp, True);
    333   Real nErr1 = Copy(NError);
    334   If(nErr1>nErr0,
    335   {
    336     WriteLn("Es posible que no se haya podido construir el paquete correctamente","W");
    337     1
    338   },
    339   {
    340     Real TolPackage::Server::UploadPackage(
    341       repository.db, pkg.path.zip);
    342     Real nErr2 = Copy(NError);
    343     If(nErr2>nErr1,
    344     {
    345       WriteLn("Es posible que no se haya podido enviar el paquete al repositorio","W");
    346       2
    347     },
    348     {
    349       Text pkg.name = Replace(GetFileName(pkg.path.zip),".zip","");
    350       Real ok = Case(
    351       ToLower(checkInstallMode) == "remote",
    352       {
    353         TolPackage::Client::RemoteInstallPackage(repository.url, pkg.name, True)
    354       },
    355       ToLower(checkInstallMode) == "local",
    356       {
    357         Real TolPackage::Client::LocalInstallPackage(pkg.path.zip)
    358       },
    359       1==1,True);
    360       Real nErr3 = Copy(NError);
    361       If(And(ok,nErr3==nErr2), 0,
    362       {
    363         WriteLn("La instalación en modo '"+checkInstallMode+"' ha dado problemas","W");
    364         3
    365       })
    366     })
    367   })
    368 };
    369 
    370 //////////////////////////////////////////////////////////////////////////////
    371 Text _.autodoc.member.RemovePackageVersion =
    372 "Borra una versión de un paquete del repositorio.\n"
    373 "Esta función no es reversible, así que debe usarse con mucho cuidado.\n"
    374 ;
    375 Real RemovePackageVersion(
    376   Text name,                //Nombre del paquete (sin versión)
    377   Real nu_version_high,     //Primer número de versión
    378   Real nu_version_low,      //Segundo número de versión
    379   NameBlock repository.db)  //Conexión a la base de datos
    380 //////////////////////////////////////////////////////////////////////////////
    381 {
    382   Real repository.db::Open(0);
    383   Real reg = DBExecQuery(
    384   "DELETE FROM package_f_contents\n"
    385   "WHERE \n"
    386   "  co_name = '"+name+"' AND\n"
    387   "  nu_version_high = "<<nu_version_high+" AND\n"
    388   "  nu_version_low = "<<nu_version_low+";\n");
    389   Real repository.db::Close(0);
    390   reg
    391 };
    392 
    393 
    394 //////////////////////////////////////////////////////////////////////////////
    395 Text _.autodoc.member.CheckTolDependencies =
    396 "Comprueba que las versiones mínima y máxima especificadas para cada "
    397 "paquete son coherentes con las especificadas por los paquetes requeridos "
    398 "directa o indirectamente.\n";
    399 Set CheckTolDependencies(NameBlock repository.db, Real fix)
    400 //////////////////////////////////////////////////////////////////////////////
    401 {
    402   Text url=TolPackage::_.official+"action=checkTolDependencies&filter=False";
    403   Text pkgInfo = GetUrlContents(url);
    404   Set pkgLst = IncludeText(pkgInfo);
    405   Real repository.db::Open(0);
    406   Set EvalSet(pkgLst,Real(TolPackage::@TolVerReqChk chk)
    407   {
    408     If(Not(chk->min_ok),
    409     {
    410       Text msg = "Minimum specified TOL version for package "<<
    411         chk->co_name_version+" is "+chk->te_min_tol_version +
    412         "lesser than indirectly recommended "+chk->te_min_tol_version_deep+"\n";
    413       Real If(fix,
    414       {
    415         Text msg := msg + "Fixing field package_f_contents."
    416           "te_min_tol_version to '"+chk->te_min_tol_version_deep+"' in database of repository.";
    417         DBExecQuery("UPDATE package_f_contents "
    418         "SET te_min_tol_version='"+chk->te_min_tol_version_deep+"'")
    419       });
    420       WriteLn(msg+"Please, fix it if posible in your TOL code by settting \n"+
    421       "Text "+chk->co_name_version+"::te_min_tol_version = \""+
    422       chk->te_min_tol_version_deep+"\";\n","W")
    423     });
    424     If(Not(chk->max_ok),
    425     {
    426       Text msg = "Maximum specified TOL version for package "<<
    427         chk->co_name_version+" is "+chk->te_max_tol_version +
    428         "greater than indirectly recommended "+chk->te_max_tol_version_deep+"\n";
    429       Real If(fix,
    430       {
    431         Text msg := msg + "Fixing field package_f_contents."
    432           "te_max_tol_version to '"+chk->te_max_tol_version_deep+"' in database of repository.";
    433         DBExecQuery("UPDATE package_f_contents "
    434         "SET te_max_tol_version='"+chk->te_max_tol_version_deep+"'")
    435       });
    436       WriteLn(msg,"W")
    437     });
    438     True
    439   });
    440   Real repository.db::Close(0);
    441   pkgLst
    442 } 
    443  
    444 
    445 ]];
    446 
    447 /* */
     310//////////////////////////////////////////////////////////////////////////////
Note: See TracChangeset for help on using the changeset viewer.