Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.installer / src / main / packaging / gvspkg @ 47815

History | View | Annotate | Download (62.8 KB)

1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
#
4
# 
5
# Hay que guardar una copia de este fichero en el svn en
6
# org.gvsig.desktop/org.gvsig.desktop.installer/src/main/packaging
7
#
8
import sys
9
import os
10
import os.path
11
import fnmatch
12
import shutil
13
import zipfile
14
import stat
15
import getopt
16
from os.path import dirname
17
import shutil
18
from os import system
19
import ConfigParser
20
import StringIO
21
import re
22
import urllib2
23
import time
24

    
25
DEBUG = False
26
VERBOSE = False
27
SEARCH_VERSIONS = list()
28

    
29
class Platform:
30
  def __init__(self,os,arch,exe,onlinefamily=None, portableSufix=""):
31
    self.osfamily = None
32
    self.osname = None
33
    self.osversion = None
34
    self.os = os
35
    self.arch = arch
36
    self.exe_extension = exe
37
    self.portableSufix = portableSufix
38
    if "_" in self.os:
39
      ss=self.os.split("_")
40
      self.osfamily = ss[0]
41
      if len(ss)>1:
42
        self.osname = ss[1]
43
        if len(ss)>2:
44
          self.osversion= ss[2]
45
    else:
46
      self.osfamily = self.os
47
    if onlinefamily == None:
48
      self.onlinefamily = self.osfamily
49
    else:
50
      self.onlinefamily = onlinefamily
51

    
52
  def getOS(self):
53
    return self.os
54

    
55
  def getOSFamily(self):
56
    return self.osfamily
57

    
58
  def getOSFamilyForOnlineInstaller(self):
59
    return self.onlinefamily
60

    
61
  def getOSName(self):
62
    return self.osname
63

    
64
  def getOSVersion(self):
65
    return self.osversion
66

    
67
  def getArch(self):
68
    return self.arch
69

    
70
  def getExeExtension(self):
71
    return self.exe_extension
72

    
73
  def getPortableSufix(self):
74
    return self.portableSufix
75

    
76
platforms = (
77
  Platform("lin","x86_64",".run"),
78
  Platform("win","x86_64",".exe"),
79
  #Platform("darwin_macos_10.11","x86_64",".run",onlinefamily="lin", portableSufix=".app"),
80
  Platform("lin","x86",".run"),
81
  Platform("win","x86",".exe"),
82
  #Platform("lin_ubuntu_14.04","x86_64",".run",onlinefamily="lin"),
83
  #Platform("lin_ubuntu_14.04","x86",".run",onlinefamily="lin")
84
)
85

    
86

    
87
def log(msg):
88
  f=open("/tmp/gvspkg.log","a")
89
  f.write(time.ctime())
90
  f.write(": ")
91
  f.write(msg)
92
  f.write("\n")
93
  f.close()
94

    
95
def message(msg):
96
    if VERBOSE:
97
        print msg
98
        sys.stdout.flush()
99
    log(msg)
100

    
101
def msgerror(msg, err=None):
102
    print "ERROR: ", msg
103
    log("ERROR: "+msg)
104
    if err!=None :
105
      print "ERROR: ", str(err)
106
      sys.stdout.flush()
107
      log("ERROR: "+ str(err))
108

    
109

    
110
def msgwarn(msg):
111
    print "WARNING: ", msg
112
    sys.stdout.flush()
113
    log("WARNING: "+ msg)
114

    
115
def debug(msg):
116
    if DEBUG:
117
        print "DEBUG: ", msg
118
        sys.stdout.flush()
119
        log("DEBUG: "+ msg)
120

    
121
def acquire_file(name):
122
  files = list()
123
  folder = os.getcwd()
124
  while folder not in ( None, "", "/"):
125
    pathname = os.path.join(folder,name)
126
    if os.path.exists(pathname):
127
      files.append(pathname)
128
    folder = os.path.dirname(folder)
129
  return files
130

    
131
def get_gvspkg_bin_folder():
132
    files = list()
133
    if os.environ.get("HOME") != None :
134
        files.append(os.path.join(os.environ['HOME'],".gvspkg.bin"))
135
    files.extend( acquire_file(".gvspkg.bin") )
136
    files.extend( acquire_file("gvspkg.bin") )
137
    if len(files)<1 :
138
      return None
139
    debug( "gvspkg.bin = %s" % files[-1])
140
    return files[-1]
141

    
142
def search_GVSPKG_ROOT():
143
  f = get_gvspkg_bin_folder()
144
  if f==None:
145
    return None
146
  return os.path.dirname(f)
147

    
148
RWALL = stat.S_IWOTH | stat.S_IROTH | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWGRP | stat.S_IRGRP
149
RWXALL = RWALL | stat.S_IXUSR | stat.S_IXOTH | stat.S_IXGRP
150

    
151
VERSION = os.path.basename(os.getcwd())
152
GVSPKG_ROOT = search_GVSPKG_ROOT()
153

    
154
def getVersion():
155
    return VERSION
156

    
157
def getSearchVersions():
158
    vers = list();
159
    vers.extend(SEARCH_VERSIONS)
160
    vers.append(VERSION)
161
    return vers
162

    
163
def getPackagesRoot():
164
    return GVSPKG_ROOT
165

    
166
def getPool():
167
    return getPackagesRoot() + "/pool"
168

    
169
def getWeb():
170
    return getPackagesRoot() + "/web"
171

    
172
def getDist():
173
    return getPackagesRoot() + "/dists/" +getVersion()
174

    
175
def findfiles(root,filename):
176
    result=list()
177
    for wroot, dirs, files in os.walk(root):
178
        for f in files :
179
            if fnmatch.fnmatch(f,filename):
180
                result.append(wroot+"/"+f)
181
    result.sort()
182
    return result
183

    
184
def getpackageUrl(path):
185
  return re.sub(".*/downloads/","http://downloads.gvsig.org/download/",path)
186

    
187
def mychmod(filename, perms):
188
    try:
189
        os.chmod(filename,perms)
190
    except Exception, ex:
191
        msgwarn("Can't change permissions of file '%s', error %s" % (filename, str(ex)))
192

    
193
def makedirs(path):
194
    if not os.path.isdir(path) :
195
      os.makedirs(path)
196

    
197
class Command:
198

    
199
    def __init__(self, args):
200
        self.args = args
201
        self.defaultoptions = None
202

    
203
    def load_options(self,filename):
204
        debug("loading option from %s" % filename)
205
        if not os.path.isfile(filename):
206
            debug("filename %s not found" % filename)
207
            return
208
        f=file(filename,"r")
209
        for line in f.readlines():
210
            line = line.strip()
211
            if line=="" or line.startswith("#"):
212
                continue
213
            if line[-1] == "\n":
214
                line = line[:-1]
215
            n = line.find("=")
216
            if n<0 :
217
                continue
218
            cmd = line[:n]
219
            args = line[n+1:].strip()
220

    
221
            if args != "":
222
              self.defaultoptions[cmd] = self.defaultoptions.get(cmd,[]) +  args.split(" ")
223
            debug("add options: %s=%r" % (cmd, args.split(" ")))
224

    
225
        f.close()
226

    
227
    def load_default_options(self):
228
        if self.defaultoptions != None:
229
            return
230
        self.defaultoptions = dict()
231
        options = list();
232
        if GVSPKG_ROOT != None:
233
          rootoptions = os.path.join(GVSPKG_ROOT,"gvspkg.bin/options")
234
        else:
235
          rootoptions = None
236
        if rootoptions != None and os.path.isfile(rootoptions):
237
            options.append(rootoptions)
238
        else:
239
            options.append("~/.gvspkg.bin/options")
240
        options.extend(acquire_file(".gvspkg.options"))
241
        options.extend(acquire_file("gvspkg.options"))
242
        for optionfile in options:
243
          self.load_options(optionfile)
244

    
245
    def getArgs(self,name):
246
        self.load_default_options()
247
        l = list()
248
        cmd = self.defaultoptions.get(name,None)
249
        if cmd != None:
250
          l.extend(cmd)
251
        l.extend(self.args[1:])
252
        return l
253

    
254
def isDigit(s):
255
    if len(s)>1:
256
        s=s[0]
257
    return s in ("0","1","2","3","4","5","6","7","8","9")
258

    
259

    
260

    
261
class PackageInfo(str):
262
    def __init__(self, filename):
263
        self._ini = None
264
        self.filename = filename[:-7]
265
        self.type = filename[-6:]
266
        s = os.path.basename(self.filename)
267
        s = s.split("-")
268
        #print "## PackageInfo ", repr(s)
269
        self.gvsig = s[0] + "-" + s[1]
270
        self.gvsig_version = s[2]
271
        self.code = s[3]
272
        try:
273
  # gvSIG-desktop-1.12.0-com.iver.cit.gvsig.cad-1.12.0-opencadtools-1418-final-all-all-j1_6.gvspkg
274
  #    0 -  1    -  2   -          3           -  4   - 5          -  6 - 7   - 8 - 9 - 10
275
  # gvSIG-desktop-1.12.0-com.iver.cit.gvsig.cad-1.12.0-1418-final-all-all-j1_6.gvspkg
276
  #    0 -  1    -  2   -          3           -  4   - 5  -  6  - 7 - 8 - 9
277

    
278
            if isDigit(s[5]) :
279
                self.version = s[4]
280
                self.build = s[5]
281
                self.status = s[6]
282
                self.os = s[7]
283
                self.arch = s[8]
284
            else:
285
                self.version = s[4] + "-" + s[5]
286
                self.build = s[6]
287
                self.status = s[7]
288
                self.os = s[8]
289
                self.arch = s[9]
290

    
291
        except Exception:
292
            self.build = "0"
293
            self.status = "unknow"
294
            self.os = "all"
295
            self.arch = "all"
296
        try:
297
            self.build = int(self.build)
298
        except:
299
            pass
300

    
301
    def getCode(self):
302
        return self.code
303

    
304
    def getOS(self):
305
        return self.os
306

    
307
    def getArch(self):
308
        return self.arch
309

    
310
    def getKey(self):
311
        return self.code+"-"+self.os+"-"+self.arch
312

    
313
    def getFullName(self):
314
        return os.path.basename(self.filename)
315

    
316
    def getFullVersion(self):
317
        try:
318
          r = re.compile("([0-9]+)[.]([0-9]+)[.]([0-9]+)-([a-zA-Z0-9]+)$")
319
          m = r.match(self.version)
320
          if m == None:
321
            clasificador="ZZZZZZZZ"
322
            r = re.compile("([0-9]+)[.]([0-9]+)[.]([0-9]+)$")
323
            m = r.match(self.version)
324
          else:
325
            clasificador=m.group(4)
326
          v1=int(m.group(1))
327
          v2=int(m.group(2))
328
          v3=int(m.group(3))
329
          return "%06d.%06d.%06d-%s-%06d" % (v1,v2,v3,clasificador,self.build)
330
        except:
331
          if "-" in self.version :
332
            return "%s-%06d" %(self.version,self.build)
333
          else:
334
            return "%s-ZZZZZZZZ-%06d" %(self.version,self.build)
335

    
336
    def getFilename(self):
337
        return self.filename + "." + self.type
338

    
339
    def isPki(self):
340
        return self.type.lower() == "gvspki"
341

    
342
    def isPkg(self):
343
        return self.type.lower() != "gvspki"
344

    
345
    def hasPki(self):
346
        return os.path.isfile( self.getPkiFilename() )
347

    
348
    def getPkiFilename(self):
349
        return self.filename + ".gvspki"
350

    
351
    def hasPkg(self):
352
        return os.path.isfile( self.getPkgFilename() )
353

    
354
    def getPkgFilename(self):
355
        return self.filename + ".gvspkg"
356

    
357
    def getIniOption(self, name, default=None):
358
      section = "general"
359
      ini = self.getIni()
360
      if ini.has_option(section, name):
361
        x = ini.get(section, name)
362
        x = x.replace("\\:", ":")
363
        return x
364
      return default
365

    
366
    def getDescription(self):
367
      return self.getIniOption("description")
368

    
369
    def getCategories(self):
370
      return self.getIniOption("categories")
371

    
372
    def getName(self):
373
      return self.getIniOption("name")
374

    
375
    def getOwner(self):
376
      ini = self.getIni()
377
      if ini.has_option("general","owner"):
378
        return ini.get("general","owner")
379
      return None
380

    
381
    def getUrl(self):
382
      ini = self.getIni()
383
      if ini.has_option("general","download-url"):
384
        return ini.get("general","download-url")
385
      return None
386

    
387
    def getSourceUrl(self):
388
      ini = self.getIni()
389
      if ini.has_option("general","source-url"):
390
        return ini.get("general","source-url")
391
      return None
392

    
393
    def getDependencies(self):
394
      ini = self.getIni()
395
      if ini.has_option("general","dependencies"):
396
        return ini.get("general","dependencies")
397
      return None
398

    
399
    def getType(self):
400
      ini = self.getIni()
401
      if ini.has_option("general","type"):
402
        return ini.get("general","type")
403
      return None
404

    
405
    def getOfficial(self):
406
      ini = self.getIni()
407
      if ini.has_option("general","official"):
408
        return ini.get("general","official")
409
      return None
410

    
411
    def getIni(self):
412
        if self._ini != None:
413
          return self._ini
414
        index_path = self.getPkiFilename()
415
        outputfolder="/tmp/gvspkg.%s" % os.getpid()
416
        os.mkdir(outputfolder)
417
        os.system('unzip -q %s -d %s' % (index_path,outputfolder))
418

    
419
        files = findfiles(outputfolder, "package.info")
420
        if len(files) != 1:
421
            msgerror("Can't locate package.info in pool '%s'." % (index_path))
422
            return None
423

    
424
        package_info = files[0]
425
        self._ini = ConfigParser.ConfigParser()
426
        f = file(package_info,"r")
427
        ss = f.read()
428
        self._ini.readfp(StringIO.StringIO("[general]\n"+ss))
429
        f.close()
430
        shutil.rmtree(outputfolder)
431
        return self._ini
432

    
433
    def match(self, names):
434
      for name in names:
435
        if self.getCode() == name:
436
          return True
437
        if self.getFullName() == name:
438
          return True
439
        if fnmatch.fnmatch(self.getFullName(),name):
440
          return True
441
      return False
442
        
443
    def __str__(self):
444
        return self.filename
445

    
446
    def __repr__(self):
447
        return "filename=%r:gvsig=%r:gvsig_version=%r:code=%r:version=%r:build=%r:status=%r" % (
448
                self.filename, self.gvsig, self.gvsig_version, self.code, self.version, self.build, self.status )
449

    
450
class IndexList(list):
451

    
452
    def load(self, fname):
453
        message( "Loading index list from '%s'." % fname)
454
        f=file(fname,"r")
455
        lines=f.readlines()
456
        f.close()
457
        for line in lines:
458
          if line[-1] == "\n":
459
            line = line[:-1]
460

    
461
          info = PackageInfo(line)
462
          self.append(info)
463

    
464
    def save(self,fname):
465
        message( "Saving index list from '%s'." % fname)
466
        f=file(fname,"w")
467
        for index in self:
468
          f.write("%s\n" % index.getFilename())
469
        f.close()
470
        mychmod(fname,RWALL)
471

    
472
    def build(self, pool, versions):
473
        message( "Creating index list for version '%s' from '%s'" % (versions, pool) )
474
        packages=dict()
475
        for root, dirs, files in os.walk(pool):
476
            for f in files :
477
                if f[-7:].lower()  in (".gvspki", ".gvspkg") :
478
                    fullpath = root+"/"+f
479
                    info = PackageInfo(fullpath)
480
                    if info.gvsig == "gvSIG-desktop" and info.gvsig_version in versions :
481
                        if packages.get(info.getKey()) == None:
482
                            debug( "build: add    " + repr(info))
483
                            packages[info.getKey()]=info
484
                        else:
485
                            oldinfo = packages[info.getKey()]
486
                            debug("build: %s %s %s" % ( info.getKey(), oldinfo.getFullVersion(),info.getFullVersion()))
487
                            if oldinfo.getFullVersion()<info.getFullVersion()  :
488
                                debug( "build: update "+ repr(oldinfo))
489
                                packages[info.getKey()]=info
490
                    else:
491
                        debug( "build: skip   "+ repr(info))
492
        self.extend(packages.values())
493
        self.sort()
494

    
495
def lsi(args):
496
    cmd = Command(args)
497
    try:
498
        opts, args = getopt.getopt(cmd.getArgs("lsi"), "l", ["long-format"])
499
    except getopt.GetoptError, err:
500
        # print help information and exit:
501
        print str(err) # will print something like "option -a not recognized"
502
        shorthelp(args)
503
        sys.exit(2)
504

    
505
    long_format=False
506
    for opt, arg in opts:
507
        if opt in ("-l", "--long-format"):
508
            long_format = True
509
        else:
510
            assert False, "unhandled option"
511

    
512
    indexes = IndexList()
513
    indexes.build(getPool(), getSearchVersions())
514

    
515
    for info in indexes:
516
        if info.hasPki():
517
            if long_format:
518
                print "["+os.path.basename(info.getPkiFilename())+"]"
519
                print "# ", info.getPkiFilename()
520
                show(["show", os.path.basename(info.getPkiFilename())])
521
            else:
522
                print info.getPkiFilename()
523

    
524

    
525
def installer_add(cmd,arg1,arg2):
526
    installer_add_use_zip(cmd,arg1,arg2)
527

    
528
def installer_add_use_zip(cmd,arg1,arg2):
529
    if cmd == "addjrelin":
530
      return
531

    
532
    if cmd == "addjrewin":
533
      return
534

    
535
    if cmd == "addpks":
536
       zip = zipfile.ZipFile(arg1,"a",zipfile.ZIP_STORED)
537
       zip.write(arg2,"package.gvspks")
538
       zip.close()
539

    
540
def installer_add_use_installkit(cmd,arg1,arg2):
541
    folder = "%s/gvspkg.bin" % GVSPKG_ROOT
542

    
543
    cmd = "%s/installkit %s/main.tcl %s %s %s" % (
544
        "/mnt/data0/public-files/gvsig-desktop/gvspkg.bin",
545
        folder,
546
        cmd,
547
        arg1,
548
        arg2
549
    )
550
    system(cmd)
551

    
552
def mkinstall(args):
553
    cmd = Command(args)
554
    try:
555
        opts, args = getopt.getopt(cmd.getArgs("mkinstall"), "N:lL:wW:", ["addjrewin", "addjrelin", "jrelin=", "jrewin=", "distribution-name="])
556
    except getopt.GetoptError, err:
557
        # print help information and exit:
558
        print str(err) # will print something like "option -a not recognized"
559
        shorthelp(args)
560
        sys.exit(2)
561

    
562
    #print "opts = ",opts
563
    #print "args = ",args
564
    addjrelin=False
565
    addjrewin=False
566
    jrelin=None
567
    jrewin=None
568
    distribution_name = "custom"
569
    for opt, arg in opts:
570
        if opt in ("-L", "--jrelin"):
571
            jrelin = arg
572
        elif opt in ("-W", "--jrewin"):
573
            jrewin = arg
574
        elif opt in ("-l", "--addjrelin"):
575
            addjrelin = True
576
        elif opt in ("-w", "--addjrewin"):
577
            addjrewin = True
578
        elif opt in ("-N", "--distrinution-name"):
579
            distribution_name = arg
580
        else:
581
            assert False, "unhandled option"
582

    
583

    
584
    if len(args) != 2 :
585
        shorthelp(args)
586
        sys.exit(4)
587

    
588
    bin_name = args[0]
589
    gvspks_name = args[1]
590
    custom_name = bin_name.replace("online", distribution_name)
591

    
592
    if not "online" in bin_name :
593
        print "gvspkg mkinstall: binary file name must contain 'online'"
594
        sys.exit(3)
595

    
596
    if addjrelin and addjrewin :
597
        print "gvspkg mkinstall: only one of addjrelin or addjrewin is allowed."
598
        sys.exit(4)
599

    
600
    message("Creating %s..." % custom_name)
601
    shutil.copyfile(bin_name, custom_name)
602
    mychmod(custom_name,RWALL)
603
    message("Adding %s..." % gvspks_name)
604
    installer_add("addpks", custom_name, gvspks_name)
605

    
606
    """
607
    if addjrelin:
608
        withjre_name = bin_name.replace("online", distribution_name+"-withjre")
609
        message("Creating %s..." % withjre_name)
610
        shutil.copyfile(custom_name, withjre_name)
611
        mychmod(withjre_name,RWALL)
612
        message("Adding %s..." % jrelin)
613
        installer_add("addjrelin", withjre_name, jrelin)
614

    
615

    
616
    if addjrewin:
617
        withjre_name = bin_name.replace("online", distribution_name+"-withjre")
618
        message("Creating %s..." % withjre_name)
619
        shutil.copyfile(custom_name, withjre_name)
620
        mychmod(withjre_name,RWALL)
621
        message("Adding %s..." % jrewin)
622
        installer_add("addjrewin", withjre_name, jrewin)
623
    """
624

    
625
def mks(args):
626
    cmd = Command(args)
627
    try:
628
        opts, args = getopt.getopt(cmd.getArgs("mks"), "ixscI:", ["index-only","include-default-selection", "clear-list", "exclude=", "excludepki=", "excludepkg=", "include="])
629
    except getopt.GetoptError, err:
630
        # print help information and exit:
631
        print str(err) # will print something like "option -a not recognized"
632
        shorthelp(args)
633
        sys.exit(2)
634

    
635
    excludes_pkg_by_os = dict()
636
    for platform in platforms:
637
      excludes_pkg_by_os[platform.getOS()] = list()
638
      
639
    default_selection = None
640
    index_only = False
641
    clear_list=False
642
    includes=list()
643
    excludes_pki=list()
644
    excludes_pkg=list()
645
    for opt, arg in opts:
646
        if opt in ("-c", "--clear-list"):
647
            clear_list = True
648
        elif opt in ("-s", "--include-default-selection"):
649
            default_selection = "defaultPackages"
650
        elif opt in ("-x", "--exclude"):
651
            excludes_pki.append(arg)
652
            excludes_pkg.append(arg)
653
        elif opt in ( "--excludepki"):
654
            excludes_pki.append(arg)
655
        elif opt in ( "--excludepkg"):
656
            if ":" in arg:
657
              osid, arg = arg.split(":")
658
              excludes_pkg_by_os[osid] = arg
659
            else:
660
              excludes_pkg.append(arg)
661
        elif opt in ( "--include", "-I"):
662
            if not os.path.isabs(arg) :
663
              arg = os.path.join(getPool(), arg)
664
            if arg.endswith(".*"):
665
              includes.append(PackageInfo(arg[:-2]+".gvspkg"))
666
              includes.append(PackageInfo(arg[:-2]+".gvspki"))
667
            else:
668
              includes.append(PackageInfo(arg))
669
        elif opt in ("-i", "--index-only"):
670
            index_only = True
671
        else:
672
            assert False, "unhandled option %r" % opt
673

    
674
    if default_selection!=None and  not os.path.isfile(default_selection) :
675
        msgwarn("No se ha encontrado el fichero %r. la opcion -s/--include-default-selection sera ignorada." % default_selection)
676
        default_selection = None
677

    
678

    
679
    indexes = IndexList()
680

    
681
    packages_txt = getDist() +"/packages.txt"
682
    packages_gvspki = getDist() +"/packages.gvspki"
683

    
684
    message( "Creating 'packages.gvspki' for version '%s'" % getVersion() + "...")
685
    if not os.path.exists(getDist()):
686
        msgerror("Can't locate version folder '%s'." % getDist())
687
        sys.exit(3)
688

    
689
    if os.path.exists(packages_txt) and not clear_list:
690
        indexes.load(packages_txt)
691
    else:
692
        indexes.build(getPool(), getSearchVersions())
693
        indexes.save(packages_txt)
694

    
695
    for pkg in includes:
696
      indexes.append(pkg)
697

    
698
    # El indice de paquetes lleva los paquetes para todas las plataformas y sistemas
699
    # ya que al conectarnos a el desde el administrador de complementos ya
700
    # se encarga la aplicacion de seleccionar los correspondientes a la plataforma
701
    # sobre la que esta rodando gvSIG.
702
    message( "Writing 'packages.gvspki' to '%s'" % packages_gvspki )
703
    set = zipfile.ZipFile(packages_gvspki,"w",zipfile.ZIP_STORED)
704
    for info in indexes:
705
        if not info.match(excludes_pki):
706
            debug("Add package '%s'" % info.getPkiFilename())
707
            try:
708
                if info.hasPki() :
709
                    set.write(info.getPkiFilename(), os.path.basename(info.getPkiFilename()))
710
            except Exception, ex:
711
                msgerror("Can't add index '%s', error %s" % (info, str(ex)))
712
        else:
713
            debug("Exclude package '%s'" % info.getFullName())
714
    if default_selection != None :
715
        set.write(default_selection,default_selection)
716
    set.write("packages.properties","packages.properties")
717
    set.close()
718
    mychmod(packages_gvspki,RWALL)
719

    
720
    md5sum(packages_gvspki,packages_gvspki+".md5")
721
    mychmod(packages_gvspki+".md5",RWALL)
722

    
723
    if not index_only :
724
      for platform in platforms:
725
        packages_gvspks = getDist() +"/packages-"+platform.getOS()+"-"+platform.getArch()+".gvspks"
726
        message( "Writing 'packages-"+platform.getOS()+"-"+platform.getArch()+".gvspks' to '%s'" % packages_gvspks )
727
        set = zipfile.ZipFile(packages_gvspks,"w",zipfile.ZIP_STORED)
728
        for info in indexes:
729
            if not info.match(excludes_pkg) and not info.match(excludes_pkg_by_os[platform.getOS()]):
730
                try:
731
                    if info.hasPkg():
732
                      if info.getOS() in ("all", platform.getOS()) :
733
                        if info.getArch() in ("all", platform.getArch()) :
734
                          set.write(info.getPkgFilename(), os.path.basename(info.getPkgFilename()))
735
                except Exception, ex:
736
                    msgerror("Can't add package '%s', error %s" % (info, str(ex)))
737
            else:
738
                debug("Exclude package '%s'" % info.getFullName())
739
        if default_selection != None :
740
            set.write(default_selection,default_selection)
741
        set.write("packages.properties","packages.properties")
742
        set.close()
743
        mychmod(packages_gvspks,RWALL)
744

    
745
        md5sum(packages_gvspks,packages_gvspks+".md5")
746
        mychmod(packages_gvspks+".md5",RWALL)
747

    
748
    message( "Createds package indexes.\n")
749

    
750
def mkmirror(args):
751
    cmd = Command(args)
752
    try:
753
        opts, args = getopt.getopt(cmd.getArgs("mkmirrot"), "b:", [ "build="])
754
    except getopt.GetoptError, err:
755
        # print help information and exit:
756
        print str(err) # will print something like "option -a not recognized"
757
        shorthelp(args)
758
        sys.exit(2)
759

    
760
    build = None
761
    for opt, arg in opts:
762
        if opt in ("-b", "--build"):
763
            build = arg
764
        else:
765
            assert False, "unhandled option %r" % opt
766

    
767
    if build == None:
768
        msgerror("Build number required.")
769
        sys.exit(3)
770
    domkmirror( getPackagesRoot(),getVersion(),build)
771

    
772
def linkfile(src,dst):
773
  if os.path.lexists(dst):
774
    os.remove(dst)
775
  os.symlink(src,dst)
776
  if os.path.lexists(src+".md5") :
777
    if os.path.lexists(dst+".md5"):
778
      os.remove(dst+".md5")
779
    os.symlink(src+".md5",dst+".md5")
780

    
781
def domkmirror(root_src, version, build):
782
  join = os.path.join
783

    
784
  build = str(build)
785
  root_target = join(root_src,"mirrors",version+"-"+build,"gvsig-desktop")
786
  build_src = join(root_src,"dists",version,"builds",build)
787
  build_target = join(root_target,"dists",version,"builds",build)
788
  pool_src = join(root_src,"pool")
789
  pool_target = join(root_target,"pool")
790

    
791
  makedirs(root_target)
792
  makedirs(build_target)
793
  makedirs(pool_target)
794
  files = os.listdir(build_src)
795
  linkfile(join(build_src,"packages.gvspki"), join(root_target,"dists",version,"packages.gvspki"))
796
  for f in files:
797
    f_src = join(build_src,f)
798
    f_target = join(build_target,f)
799
    if os.path.isfile(f_src):
800
      linkfile(f_src,f_target)
801

    
802
  z = zipfile.ZipFile(join(build_src,"packages.gvspki"))
803
  pkgs = z.namelist()
804
  for pkgname in pkgs:
805
    if pkgname!='defaultPackages':
806
      pkg = PackageInfo(pkgname)
807
      makedirs(join(root_target,"pool",pkg.getCode()))
808
      src = join(root_src,"pool",pkg.getCode(),pkg.getPkgFilename())
809
      target = join(root_target,"pool",pkg.getCode(),pkg.getPkgFilename())
810
      linkfile(src,target)
811
  cmd = "cd %s ; find . ! -type d >%s/files.lst" % (root_target, build_target)
812
  os.system(cmd)
813

    
814
def mkhtml(args):
815
    def getCode(info):
816
      return info.code
817

    
818

    
819
    cmd = Command(args)
820
    try:
821
        opts, args = getopt.getopt(cmd.getArgs("mkhtml"), "xsc", ["clear-list", "exclude=", "excludepki=", "excludepkg=", "include="])
822
    except getopt.GetoptError, err:
823
        # print help information and exit:
824
        print str(err) # will print something like "option -a not recognized"
825
        shorthelp(args)
826
        sys.exit(2)
827

    
828
    index_only = False
829
    clear_list=False
830
    includes=list()
831
    excludes_pki=list()
832
    excludes_pkg=list()
833
    for opt, arg in opts:
834
        if opt in ("-c", "--clear-list"):
835
            clear_list = True
836
        elif opt in ("-x", "--exclude"):
837
            excludes_pki.append(arg)
838
            excludes_pkg.append(arg)
839
        elif opt in ( "--excludepki"):
840
            excludes_pki.append(arg)
841
        elif opt in ( "--excludepkg"):
842
            excludes_pkg.append(arg)
843
        elif opt in ( "--include", "-I"):
844
            includes.append(PackageInfo(arg))
845
        else:
846
            assert False, "unhandled option %r" % opt
847

    
848
    message("Creating html pages...")
849
    indexes = IndexList()
850

    
851
    packages_txt = getDist() +"/packages.txt"
852

    
853
    if os.path.exists(packages_txt) and not clear_list:
854
        indexes.load(packages_txt)
855
    else:
856
        indexes.build(getPool(), getSearchVersions())
857
        indexes.save(packages_txt)
858

    
859
    for pkg in includes:
860
      indexes.append(pkg)
861

    
862
    allpackages = list()
863
    basepath = getWeb()
864
    for info in indexes:
865
        if not ( info.code in excludes_pki or info.getFullName() in excludes_pki ):
866
            try:
867
                if info.hasPki() :
868
                    mkpkihtml(basepath, info)
869
                    allpackages.append(info)
870
            except Exception, ex:
871
                msgerror("Can't create html '%s', error %s" % (info, str(ex)))
872

    
873
    html = '''
874
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
875
<html xmlns="http://www.w3.org/1999/xhtml">
876
<head>
877
  <meta http-equiv="Content-Type" content= "text/html; charset=us-ascii" />
878
      <title>"%s" package list</title>'''% getVersion() # Title
879

    
880
    html += '''
881
<!-- estilos para las tablas -->
882
  <style type="text/css" title="currentStyle">
883
    @import "css/demo_table.css";
884
    @import "css/thickbox.css";
885
    #pkglist{
886
        width:100%;
887
        clear:both;
888
        font-family:Arial,Helvetica,sans-serif;
889
    }
890
    #pkgdetails{
891
        width:600px !important;
892
        clear:both;
893
    }
894
    #pkgdetails table th{
895
        text-algin:right;
896
    }
897
  </style>
898
</head>'''
899

    
900
    html += '''
901
<body>
902
  <h1>%s package list</h1>
903
  <table id="pkglist" summary="%s package list" width="100%%" >
904
    <thead>
905
    <tr>
906
      <td>Package name</td>
907
      <td>Version</td>
908
      <td>O.S.</td>
909
      <td>Official</td>
910
      <td>Type</td>
911
      <td>Owner</td>
912
    </tr>
913
    </thead>
914
    <tbody>'''%(getVersion(),getVersion())
915

    
916
    # sort allpackages
917
    for item in sorted(allpackages, key=getCode):
918
      html += '''\n    <tr>
919
      <td><a class="thickbox" href="%s">%s</a></td>
920
      <td>%s</td>
921
      <td>%s</td>
922
      <td>%s</td>
923
      <td>%s</td>
924
      <td>%s</td>
925
    </tr>\n'''%(
926
  "../../../web/" + item.getFullName() + ".html?height=400&width=600",
927
        item.getName(),
928
  item.version,
929
  item.os,
930
  item.getOfficial(),
931
  item.getType(),
932
  item.getOwner()
933
      )
934
    html += """ </tbody>\n </table>
935
<!--javascript para la visualizacion de la tabla y carga dinamica del contenido del enlace -->
936
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
937
<script src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js" type="text/javascript"></script>
938
<script type="text/javascript" src="js/thickbox-compressed.js"></script>
939

    
940
<!-- inicializacion de la tabla con cosas chachis -->
941
<script type="text/javascript">
942
  $(document).ready(function() {
943
      $('#pkglist').dataTable( {
944
      "bPaginate": false,
945
      "bLengthChange": true,
946
      "bFilter": true,
947
      "bSort": true,
948
      "bInfo": true,
949
      "bAutoWidth": true
950
    });
951
 } );
952
</script>
953
</body>
954
</html>"""
955

    
956
    # generate index.html
957
    try:
958
      f=file(getDist()+"/web/index.html","w")
959
      f.write(html)
960
      f.close()
961
    except Exception, ex:
962
      raise ex
963

    
964
    message("html pages createds.\n")
965

    
966

    
967
def mkpkihtml(basepath, info):
968
  html='''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
969
<html xmlns="http://www.w3.org/1999/xhtml">
970
<head>
971
  <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
972
  <title>%s</title>
973
  <!-- estilos para las tablas -->
974
  <style type="text/css" title="currentStyle">
975
    @import "../dists/%s/web/css/demo_table.css";
976
    #pkgdetails{
977
      width:600px;
978
      clear:both;
979
    }
980
    #pkgdetails table th{
981
        text-algin:right;
982
    }
983
  </style>
984
</head>
985
<body>\n'''%(info.getIniOption("name"), getVersion())
986
  html += '  <table id="pkgdetails" summary=%s >\n'%info.getIniOption("name")
987
  html += '    <thead>\n  <tr>\n  <th>%s </th>\n  <td>%s</td>\n  </tr>\n  </thead>\n'%("Name", info.getIniOption("name"))
988
  html += '    <tbody><tr><th>%s </th><td>%s</td></tr>\n'%("Code", info.code)
989
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Version", info.version)
990
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("State", info.getIniOption("state"))
991
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Build", info.build)
992
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Owner", info.getOwner())
993

    
994
  #url = info.getUrl()
995
  url = info.getIniOption("download-url")
996
  if url != None:
997
    html += '    <tr><th valing="top">Downloads</th><td><a href ="%s">Binaries</a></td></tr>\n'%(url)
998
  else:
999
    html += '    <tr><th valing="top">Downloads</th><td>Binaries</td></tr>\n'
1000

    
1001
  sourceUrl = info.getSourceUrl()
1002

    
1003
  if sourceUrl != None:
1004
    html += '    <tr><td></td><td><a href ="%s">Sources</a></td></tr>\n'%(sourceUrl)
1005
  else:
1006
    html += "    <tr><td></td><td>Sources</td></tr>\n"
1007

    
1008
  if info.getDependencies() == None:
1009
    html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Dependencies", "")
1010
  else:
1011
    html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Dependencies", info.getDependencies().replace("\:",":"))
1012
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Type", info.getType())
1013
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Official", info.getOfficial())
1014
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("O.S.", info.getOS())
1015
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Architecture", info.getArch())
1016
  html += '    <tr><th valing="top">%s </th><td>%s</td></tr>\n'%("Categories", info.getCategories())
1017

    
1018
  description = info.getDescription()
1019
  if description == None:
1020
    description = ""
1021
  description = description.replace("\\n", "<br>")
1022
  description = description.replace("\:",":")
1023
  html += '    <tr valing="top"><th valing="top">%s </th><td>%s</td></tr>\n'%("Description", description)
1024
  html += """  </tbody>\n</table>\n"""
1025
  html += """
1026
  <!-- javascript para la visualizacion de la tabla -->
1027
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
1028
  <script src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js" type="text/javascript"></script>
1029
  <!-- inicializacion de la tabla con cosas chachis -->
1030
  <script type="text/javascript">
1031
    $(document).ready(function() {
1032
      $('#pkgdetails').dataTable( {
1033
        "bPaginate": false,
1034
        "bLengthChange": true,
1035
        "bFilter": false,
1036
        "bSort": false,
1037
        "bInfo": false,
1038
        "bAutoWidth": true
1039
      });
1040
    });
1041
  </script>
1042
  </body>\n</html>"""
1043

    
1044

    
1045
  try:
1046
    f = file(getWeb() + "/" + info.getFullName() + ".html","w")
1047
    f.write(html)
1048
    f.close()
1049
  except Exception, ex:
1050
    raise ex
1051

    
1052
def extract_make_portable(zfile, targetfolder):
1053
  print "Extracting 'make-portable' from %r to %r" % (zfile,targetfolder)
1054
  zf = zipfile.ZipFile(zfile)
1055
  data = zf.read("tools/make-portable")
1056
  f = open(os.path.join(targetfolder,"make-portable"),"wb")
1057
  f.write(data)
1058
  f.close()
1059
  zf.close()
1060

    
1061

    
1062
def extract_mkexec(zfile, targetfolder):
1063
  print "extract_mkexec: zfile=%s, target=%s" % (zfile, os.path.join(targetfolder,"mkexec"))
1064
  zf = zipfile.ZipFile(zfile)
1065
  data = zf.read("tools/mkexec")
1066
  f = open(os.path.join(targetfolder,"mkexec"),"wb")
1067
  f.write(data)
1068
  f.close()
1069
  zf.close()
1070

    
1071

    
1072
def prepare_portable(args):
1073
    cmd = Command(args)
1074
    try:
1075
        opts, args = getopt.getopt(cmd.getArgs("prepare-portable"), "b:s:", [ "build=", "state=" ])
1076
    except getopt.GetoptError, err:
1077
        # print help information and exit:
1078
        print str(err) # will print something like "option -a not recognized"
1079
        shorthelp(args)
1080
        sys.exit(2)
1081

    
1082
    build=None
1083
    state=None
1084
    for opt, arg in opts:
1085
        if opt in ("-b", "--build"):
1086
            build=arg
1087
        elif opt in ("-s", "--state"):
1088
            state=arg
1089
        else:
1090
            assert False, "unhandled option %r" % opt
1091

    
1092
    if build == None:
1093
      print "Requiered option --build not found."
1094
      shorthelp(args)
1095
      sys.exit(2)
1096

    
1097
    if state == None:
1098
      print "Requiered option --state not found."
1099
      shorthelp(args)
1100
      sys.exit(2)
1101

    
1102
    join = os.path.join
1103
    build_folder = join(getPackagesRoot(),"dists",getVersion(),"builds",build)
1104
    if not os.path.isdir(build_folder):
1105
      print "Can't access the build folder "+build_folder+"."
1106
      sys.exit(2)
1107

    
1108
    do_prepare_portable(build,state)
1109

    
1110
def do_prepare_portable(build,state):
1111
    join = os.path.join
1112
    build_folder = join(getPackagesRoot(),"dists",getVersion(),"builds",build)
1113
    portable_folder = join(build_folder,"misc","portable")
1114
    makedirs(portable_folder)
1115
    makedirs(join(portable_folder,"packages","custom"))
1116
    makedirs(join(portable_folder,"standard"))
1117
    makedirs(join(portable_folder,"patchs"))
1118
    shutil.copy(
1119
        join(getPackagesRoot(),"dists",getVersion(),"excludes.portable"),
1120
        join(portable_folder,"packages","excludes")
1121
    )
1122
    for platform in platforms :
1123
      fname_base = "gvSIG-desktop-%s-%s-%s-%s-%s" % (
1124
        getVersion(),build,state,platform.getOS(),platform.getArch()
1125
      )
1126
      fname_base_onlinefamily = "gvSIG-desktop-%s-%s-%s-%s-%s" % (
1127
        getVersion(),build,state,platform.getOSFamilyForOnlineInstaller(),platform.getArch()
1128
      )
1129
      linkfile(
1130
        join(build_folder,fname_base_onlinefamily + "-online.zip"),
1131
        join(portable_folder,"standard",fname_base_onlinefamily + "-online.zip")
1132
      )
1133
      linkfile(
1134
        join(build_folder,fname_base + ".gvspks"),
1135
        join(portable_folder,"standard",fname_base + ".gvspks")
1136
      )
1137
    extract_make_portable(
1138
      join(build_folder,fname_base_onlinefamily + "-online.zip"),
1139
      join(portable_folder)
1140
    )
1141
    mychmod(join(portable_folder,"make-portable"),RWXALL)
1142

    
1143
def zipfolder(source,target):
1144
  def zipdir(path, zip):
1145
      for root, dirs, files in os.walk(path):
1146
          for file in files:
1147
              zip.write(os.path.join(root, file))
1148
  zipf = zipfile.ZipFile(target, 'w')
1149
  zipdir(source, zipf)
1150
  zipf.close()
1151

    
1152
def removefile(filename):
1153
  if os.path.exists(filename):
1154
    os.remove(filename)
1155

    
1156
def mkportable(args):
1157
    cmd = Command(args)
1158
    try:
1159
        opts, args = getopt.getopt(cmd.getArgs("mkportable"), "b:s:", [ "build=", "state=" ])
1160
    except getopt.GetoptError, err:
1161
        # print help information and exit:
1162
        print str(err) # will print something like "option -a not recognized"
1163
        shorthelp(args)
1164
        sys.exit(2)
1165

    
1166
    build=None
1167
    state=None
1168
    for opt, arg in opts:
1169
        if opt in ("-b", "--build"):
1170
            build=arg
1171
        elif opt in ("-s", "--state"):
1172
            state=arg
1173
        else:
1174
            assert False, "unhandled option %r" % opt
1175

    
1176
    if build == None:
1177
      print "Requiered option --build not found."
1178
      shorthelp(args)
1179
      sys.exit(2)
1180

    
1181
    if state == None:
1182
      print "Requiered option --state not found."
1183
      shorthelp(args)
1184
      sys.exit(2)
1185

    
1186
    join = os.path.join
1187
    build_folder = join(getPackagesRoot(),"dists",getVersion(),"builds",build)
1188
    portable_folder = join(build_folder,"misc","portable")
1189
    target_folder = join(portable_folder,"target")
1190

    
1191
    if not os.path.isdir(build_folder):
1192
      print "Can't access the build folder "+build_folder+"."
1193
      sys.exit(2)
1194

    
1195
    if not os.path.isdir(portable_folder) :
1196
      do_prepare_portable(build,state)
1197
    os.system('cd %s ; ./make-portable' % (portable_folder))
1198

    
1199
    message("Moving portable zip files to build folder")
1200
    for platform in platforms :
1201
      fname = "gvSIG-desktop-%s-%s-%s-%s-%s%s.zip" %  (
1202
        getVersion(),build,state,platform.getOS(),platform.getArch(), platform.getPortableSufix()
1203
      )
1204
      if os.path.exists(join(target_folder,fname)) :
1205
        message("    Removing previos %s" % fname)
1206
        removefile(join(build_folder,fname))
1207
        message("    Moving zip %s" % fname)
1208
        shutil.move(join(target_folder,fname), build_folder)
1209
      else:
1210
        message("    Skip zip %s" % fname)
1211

    
1212
    message("Remove temporary folders")
1213
    shutil.rmtree(target_folder)
1214

    
1215
def mkexec(version, build, state, distribution_name, folder):
1216
  fname = "gvSIG-desktop-%s-%s-%s-lin-x86_64-online.zip" % (version,build,state)
1217
  extract_mkexec(os.path.join(folder,fname), folder)
1218
  mychmod(os.path.join(folder,"mkexec"),RWXALL)
1219
  cmd = 'cd %s ; ./mkexec "%s" "%s" "%s" "%s" "%s"' % (folder,version, build, state, distribution_name, folder)
1220
  print "mkexec: cmd=", cmd
1221
  os.system(cmd)
1222
  os.remove(os.path.join(folder,"mkexec"))
1223

    
1224
def mkdist(args):
1225
    cmd = Command(args)
1226
    try:
1227
        opts, args = getopt.getopt(cmd.getArgs("mkdist"), "b:s:", [ "build=", "state=", "distribution_name=" ])
1228
    except getopt.GetoptError, err:
1229
        # print help information and exit:
1230
        print str(err) # will print something like "option -a not recognized"
1231
        shorthelp(args)
1232
        sys.exit(2)
1233

    
1234
    build=None
1235
    state=None
1236
    distribution_name = "standard"
1237

    
1238
    for opt, arg in opts:
1239
        if opt in ("-b", "--build"):
1240
            build=arg
1241
        elif opt in ("-s", "--state"):
1242
            state=arg
1243
        elif opt in ("-N", "--distrinution-name"):
1244
            distribution_name = arg
1245
        else:
1246
            assert False, "unhandled option %r" % opt
1247

    
1248
    if build == None:
1249
      print "Requiered option --build not found."
1250
      shorthelp(args)
1251
      sys.exit(2)
1252

    
1253
    if state == None:
1254
      print "Requiered option --state not found."
1255
      shorthelp(args)
1256
      sys.exit(2)
1257

    
1258
    if not os.path.isdir("builds/"+build):
1259
      print "Can't access the build folder builds/"+build+"."
1260
      sys.exit(2)
1261

    
1262
    message( "Generating distribution for build "+ build + "...")
1263
    message("Recreating index of packages...")
1264
    executeCommand("mks", "-s", "-c")
1265

    
1266
    #executeCommand("mkhtml" )
1267

    
1268
    gvspki_filename = "builds/"+build+"/packages.gvspki"
1269
    message( "Coping packages.gvspki to "+ gvspki_filename + "\n")
1270
    shutil.copyfile("packages.gvspki", gvspki_filename)
1271
    shutil.copyfile("packages.gvspki.md5", gvspki_filename +".md5")
1272

    
1273
    for platform in platforms:
1274
        message( "Creating installers for platform "+platform.getOS()+"/"+platform.getArch()+"...")
1275
        gvspks_filename = "builds/"+build+"/gvSIG-desktop-" + VERSION + "-" + build+ "-" + state + "-"+platform.getOS()+"-"+platform.getArch()+".gvspks"
1276
        online_filename = "builds/"+build+"/gvSIG-desktop-" + VERSION + "-" + build+ "-" + state + "-"+platform.getOS()+"-"+platform.getArch() + "-online.jar"
1277

    
1278
        if not os.path.isfile(online_filename):
1279
          osfamily=platform.getOSFamilyForOnlineInstaller()
1280
          message("Coping standard online installer from os family (%s) to %s." % (osfamily, online_filename))
1281
          shutil.copyfile(
1282
            "builds/"+build+"/gvSIG-desktop-" + VERSION + "-" + build+ "-" + state + "-"+osfamily+"-"+platform.getArch() + "-online.jar",
1283
            online_filename
1284
          )
1285

    
1286
        if not os.path.isfile(online_filename):
1287
          msgwarn("Can't access the online installer for "+platform.getOS()+"/"+platform.getArch() + " ("+online_filename+").")
1288
          continue
1289

    
1290
        message( "Coping packages-"+platform.getOS()+"-"+platform.getArch()+".gvspks to "+ gvspks_filename)
1291
        shutil.copyfile("packages-"+platform.getOS()+"-"+platform.getArch()+".gvspks", gvspks_filename)
1292
        shutil.copyfile("packages-"+platform.getOS()+"-"+platform.getArch()+".gvspks.md5", gvspks_filename +".md5")
1293

    
1294
        message( "Add execution permissions to online installers....")
1295
        mychmod(online_filename,RWXALL)
1296

    
1297
        md5sum(online_filename,online_filename+".md5")
1298
        mychmod(online_filename+".md5",RWALL)
1299

    
1300

    
1301
        executeCommand("mkinstall" , online_filename, gvspks_filename)
1302

    
1303
        message( "Renaming files from custom to standard...")
1304
        target_filename = "builds/"+build+"/gvSIG-desktop-" + VERSION + "-" + build+ "-" + state + "-"+platform.getOS()+"-"+platform.getArch()+"-"+distribution_name + ".jar"
1305
        shutil.move(
1306
            "builds/"+build+"/gvSIG-desktop-" + VERSION + "-" + build+ "-" + state + "-"+platform.getOS()+"-"+platform.getArch() + "-custom.jar",
1307
            target_filename
1308
        )
1309
        mychmod(target_filename,RWXALL)
1310

    
1311
        md5sum(target_filename,target_filename+".md5")
1312
        mychmod(target_filename+".md5",RWALL)
1313

    
1314
        message( "Createds installers for platform "+platform.getOS()+"/"+platform.getArch()+"\n")
1315

    
1316
    mkexec(VERSION, build, state, distribution_name, os.path.join(os.getcwd(), "builds", build))
1317

    
1318
    #message( "Coping html index to browse paqueges of the distro.")
1319
    #shutil.rmtree("builds/"+build+"/web", ignore_errors=True)
1320
    #shutil.copytree("web", "builds/"+build+"/web")
1321
    #f = file("builds/"+build+"/web/index.html","r")
1322
    #contents = f.read()
1323
    #f.close()
1324
    #contents = contents.replace("href=\"../../../web/gvSIG-desktop-", "href=\"../../../../../web/gvSIG-desktop-")
1325
    #f = file("builds/"+build+"/web/index.html","w")
1326
    #f.write(contents)
1327
    #f.close()
1328

    
1329
    message( "\nCreation of distribution completed.\n")
1330

    
1331

    
1332
def show(args):
1333
    cmd = Command(args)
1334
    try:
1335
        opts, args = getopt.getopt(cmd.getArgs("show"), "S", [ "verify"])
1336
    except getopt.GetoptError, err:
1337
        # print help information and exit:
1338
        print str(err) # will print something like "option -a not recognized"
1339
        shorthelp(args)
1340
        sys.exit(2)
1341

    
1342
    eerify = False
1343
    for opt, arg in opts:
1344
        if opt in ("-V", "--verify"):
1345
            verify = True
1346
        else:
1347
            assert False, "unhandled option %r" % opt
1348

    
1349
    index_name=args[0]
1350
    message( "Show package.info from '%s'" % index_name)
1351
    files = findfiles(getPool(), index_name)
1352
    if len(files) != 1:
1353
        msgerror("Can't locate package '%s' in pool '%s'." % (index_name, getPool()))
1354
        return
1355
    index_path = files[0]
1356
    outputfolder="/tmp/gvspkg.%s" % os.getpid()
1357
    os.mkdir(outputfolder)
1358
    os.system('unzip -q %s -d %s' % (index_path,outputfolder))
1359

    
1360
    files = findfiles(outputfolder, "package.info")
1361
    if len(files) != 1:
1362
        msgerror("Can't locate package.info in pool '%s'." % (index_name))
1363
        return
1364

    
1365
    package_info = files[0]
1366
    f = file(package_info,"r")
1367
    s = f.read()
1368
    f.close()
1369
    print s
1370
    if verify:
1371
      verify_sign(package_info)
1372
    shutil.rmtree(outputfolder)
1373

    
1374
def editall(args):
1375
    cmd = Command(args)
1376
    try:
1377
        opts, args = getopt.getopt(cmd.getArgs("editall"), "Scx:I:r:", ["clear-list", "exclude=", "excludepki=", "excludepkg=", "include=", "replace=", "sign"])
1378
    except getopt.GetoptError, err:
1379
        # print help information and exit:
1380
        print str(err) # will print something like "option -a not recognized"
1381
        shorthelp(args)
1382
        sys.exit(2)
1383

    
1384
    index_only = False
1385
    clear_list=False
1386
    includes=list()
1387
    excludes_pki=list()
1388
    replaces = list()
1389
    excludes_pkg=list()
1390
    sign = False
1391
    interactive = True
1392
    for opt, arg in opts:
1393
        if opt in ("-c", "--clear-list"):
1394
            clear_list = True
1395
        elif opt in ("-x", "--exclude"):
1396
            excludes_pki.append(arg)
1397
            excludes_pkg.append(arg)
1398
        elif opt in ( "--excludepki"):
1399
            excludes_pki.append(arg)
1400
        elif opt in ( "--excludepkg"):
1401
            excludes_pkg.append(arg)
1402
        elif opt in ( "--include", "-I"):
1403
            includes.append(PackageInfo(arg))
1404
        elif opt in ("-r", "--replace"):
1405
            interactive = False
1406
            replaces.append(arg)
1407
        elif opt in ("-S", "--sign"):
1408
            sign = True
1409
        else:
1410
            assert False, "unhandled option %r" % opt
1411

    
1412
    indexes = IndexList()
1413

    
1414
    packages_txt = getDist() +"/packages.txt"
1415
    if os.path.exists(packages_txt) and not clear_list:
1416
        indexes.load(packages_txt)
1417
    else:
1418
        indexes.build(getPool(), getSearchVersions())
1419
        indexes.save(packages_txt)
1420

    
1421
    for pkg in includes:
1422
      indexes.append(pkg)
1423

    
1424
    allpackages = list()
1425
    for info in indexes:
1426
        if not ( info.code in excludes_pki or info.getFullName() in excludes_pki ):
1427
            try:
1428
                if info.hasPki() :
1429
                  print info.getPkiFilename()
1430
                  if interactive :
1431
                    edit_pkginfo_of_package(info.getPkiFilename(), edit_ui)
1432
                  elif len(replaces) < 1:
1433
                    edit_pkginfo_of_package(info.getPkiFilename(), edit_replace, replaces)
1434

    
1435
                  if sign:
1436
                    edit_pkginfo_of_package(info.getPkiFilename(), edit_sign)
1437

    
1438
            except Exception, ex:
1439
                msgerror("Can't add index '%s', error %s" % (info, str(ex)))
1440

    
1441
def edit(args):
1442
    cmd = Command(args)
1443
    try:
1444
        opts, args = getopt.getopt(cmd.getArgs("edit"), "Sr:", [ "replace=", "onlysign", "sign" ])
1445
    except getopt.GetoptError, err:
1446
        # print help information and exit:
1447
        print str(err) # will print something like "option -a not recognized"
1448
        shorthelp(args)
1449
        sys.exit(2)
1450

    
1451
    replaces = list()
1452
    interactive = True
1453
    sign = False
1454
    for opt, arg in opts:
1455
        if opt in ("-r", "--replace"):
1456
            interactive = False
1457
            replaces.append(arg)
1458
        elif opt in ("--onlysign"):
1459
            interactive = False
1460
            sign = True
1461
        elif opt in ("-S", "--sign"):
1462
            sign = True
1463
        else:
1464
            assert False, "unhandled option %r" % opt
1465

    
1466
    index_name=args[0]
1467
    message( "Show package.info from '%s'" % index_name)
1468
    files = findfiles(getPool(), index_name)
1469
    if len(files) != 1:
1470
        msgerror("Can't locate package '%s' in pool '%s'." % (index_name, getPool()))
1471
        return
1472
    index_path = files[0]
1473
    if interactive:
1474
      edit_pkginfo_of_package(index_path, edit_ui)
1475
    elif len(replaces) < 1:
1476
      edit_pkginfo_of_package(index_path, edit_replace, replaces)
1477

    
1478
    if sign:
1479
      edit_pkginfo_of_package(index_path, edit_sign)
1480

    
1481
def edit_ui(filename, args):
1482
      os.system('vi "%s"' % filename)
1483

    
1484
def edit_replace(filename, args):
1485
      replaces = args[0]
1486
      f = open(filename)
1487
      s = f.read()
1488
      f.close()
1489
      for replace in replaces:
1490
        x = replace.split(replace[0])
1491
        if len(x)==4:
1492
          s=re.sub(x[1],x[2],s)
1493
      f = open(filename,"w")
1494
      f.write(s)
1495
      f.close()
1496

    
1497
def edit_sign(filename, args):
1498
      os.system('java -cp "%s/commons-codec-1.6.jar:%s/org.gvsig.installer.lib.impl-1.0.1-SNAPSHOT.jar" org.gvsig.installer.lib.impl.utils.SignUtil sign %s' %  (
1499
        get_gvspkg_bin_folder(),
1500
        get_gvspkg_bin_folder(),
1501
        filename)
1502
      )
1503

    
1504
def verify_sign(filename):
1505
      os.system('java -cp "%s/commons-codec-1.6.jar:%s/org.gvsig.installer.lib.impl-1.0.1-SNAPSHOT.jar" org.gvsig.installer.lib.impl.utils.SignUtil verify %s' % (
1506
        get_gvspkg_bin_folder(),
1507
        get_gvspkg_bin_folder(),
1508
        filename)
1509
      )
1510

    
1511
def edit_pkginfo_of_package(pkg_path, operation, *args):
1512
    outputfolder="/tmp/gvspkg.%s" % os.getpid()
1513
    os.mkdir(outputfolder)
1514
    os.system('unzip -q %s -d %s' % (pkg_path,outputfolder))
1515

    
1516
    files = findfiles(outputfolder, "package.info")
1517
    if len(files) != 1:
1518
        msgerror("Can't locate package.info in pool '%s'." % (pkg_path))
1519
        return
1520

    
1521
    package_info = files[0]
1522
    code = package_info.split("/")[-2]
1523
    operation(package_info, args)
1524

    
1525
    # zip -Dr kk.zip org.gvsig.wfs
1526
    temp_index_name = "/tmp/packages.gvspki.%s" % os.getpid()
1527
    temp_index = zipfile.ZipFile(temp_index_name,"w",zipfile.ZIP_STORED)
1528
    temp_index.write(package_info, "%s/package.info" % (code))
1529
    temp_index.close()
1530
    shutil.rmtree(outputfolder)
1531
    os.remove(pkg_path)
1532
    shutil.move(temp_index_name,pkg_path)
1533

    
1534

    
1535
def crearpki(path_pkg, url_pkg):
1536
  z = zipfile.ZipFile(path_pkg,"r")
1537
  zi = z.infolist()
1538
  filename = None
1539
  contents = None
1540
  for info in zi :
1541
    if info.filename.endswith("/package.info"):
1542
      filename = info.filename
1543
      contents = z.read(filename)
1544
      if contents[-1:]!= "\n":
1545
        contents += "\n"
1546
      contents += "download-url=%s\n" % url_pkg.replace(":","\\:")
1547
      break
1548

    
1549
  z.close()
1550
  
1551
  if filename == None:
1552
    return
1553
  
1554
  fname = path_pkg[:-7]+".gvspki"
1555
  z = zipfile.ZipFile(fname,"w")
1556
  z.writestr(filename,contents)
1557
  z.close()
1558
  
1559
  return fname
1560
  
1561
def install(args):
1562
    cmd = Command(args)
1563
    try:
1564
        opts, args = getopt.getopt(cmd.getArgs("install"), "fS", [ "force","nohttps" ])
1565
    except getopt.GetoptError, err:
1566
        # print help information and exit:
1567
        print str(err) # will print something like "option -a not recognized"
1568
        shorthelp(args)
1569
        sys.exit(2)
1570

    
1571
    force = False
1572
    nohttps = False
1573
    for opt, arg in opts:
1574
        if opt in ("-f", "--force"):
1575
            force = True
1576
        if opt in ("-S", "--nohttps"):
1577
            nohttps = True
1578
        else:
1579
            assert False, "unhandled option %r" % opt
1580

    
1581
    url_pki = args[0]
1582
    if url_pki.endswith(".gvspki") and url_pki.startswith("https:") and nohttps :
1583
       url_pki = "http:" + url_pki[6:]
1584

    
1585
    message( "Download package index '%s'" % url_pki)
1586
    temppath_pki= os.path.join("/tmp",os.path.basename(url_pki))
1587
    if not downloadFile(url_pki,temppath_pki):
1588
      msgerror("Can't download index.")
1589
      msgerror("Can't install '%s'." % url_pki)
1590
      print # force a newline
1591
      return 1
1592
    if temppath_pki.endswith(".gvspki"):
1593
      pkg = PackageInfo(temppath_pki)
1594
      url_pkg = pkg.getUrl().replace("\\","")
1595
      if url_pkg[-7:] == ".gvspki" :
1596
        msgwarn("Suspicious download-url value. Ends with gvspki, expected gvspkg.")
1597
        msgwarn("download-url ='%s'." % url_pkg)
1598

    
1599
      if url_pkg.startswith("https:") and nohttps :
1600
         url_pkg = "http:" + url_pkg[6:]
1601

    
1602
      message( "Download package '%s'" % url_pkg)
1603
      temppath_pkg= os.path.join("/tmp",os.path.basename(url_pkg))
1604
      if not downloadFile(url_pkg,temppath_pkg):
1605
        msgerror("Can't download package from download-url ('%s')." % url_pkg)
1606
        msgerror("Can't install '%s'," % url_pki)
1607
        print # force a newline
1608
        return 1
1609

    
1610
    elif temppath_pki.endswith(".gvspkg"):
1611
      temppath_pkg = temppath_pki
1612
      pkg = PackageInfo(temppath_pki)
1613
      url = getpackageUrl(getPool()+"/"+pkg.getCode()+"/"+os.path.basename(temppath_pkg))
1614
      temppath_pki = crearpki(temppath_pkg,url)
1615

    
1616
    else:
1617
      msgerror("Can't install '%s', extension is not a gvspki or gvspkg.\n" % url_pki)
1618
      return 1
1619

    
1620
    folder = os.path.join(getPool(),pkg.getCode())
1621
    makedirs(folder)
1622
    pathname_pki = os.path.join(folder,os.path.basename(temppath_pki))
1623
    if not force and os.path.isfile(pathname_pki) :
1624
        msgwarn("The package index alreade exist in the pool. Use -f to forrce install.")
1625
        print # force a newline
1626
        return 1
1627
    pathname_pkg = os.path.join(folder,os.path.basename(temppath_pkg))
1628
    if  not force and os.path.isfile(pathname_pki) :
1629
        msgwarn("The package downloaded from download-url alredy exists in the pool. Use -f to force install.")
1630
        print # force a newline
1631
        return 1
1632
    message( "installing package '%s'" % os.path.basename(pathname_pki))
1633
    shutil.copyfile(temppath_pki, pathname_pki)
1634
    message( "installing package '%s'" % os.path.basename(pathname_pkg))
1635
    shutil.copyfile(temppath_pkg, pathname_pkg)
1636

    
1637
    md5sum(pathname_pki, pathname_pki+".md5")
1638
    md5sum(pathname_pkg, pathname_pkg+".md5")
1639
    
1640
def md5sum(fin, fout):
1641
    message( "Calculating md5sum of %s..." % fin )
1642
    system("md5sum -b %s >%s" % (fin, fout) )
1643

    
1644
def downloadFile(url,path):
1645
  try:
1646
    fsrc = urllib2.urlopen(url)
1647
  except urllib2.HTTPError,e:
1648
    msgerror("Error abriendo url '%s'." % url, e)
1649
    return False
1650
  fdst = file(path,"wb")
1651
  shutil.copyfileobj(fsrc,fdst)
1652
  fdst.close()
1653
  fsrc.close()
1654
  return True
1655

    
1656
def shorthelp(args):
1657
    print """
1658
usage: gvspkg [OPTIONS] COMMANDS
1659
OPTIONS:
1660

    
1661
-h,--help       Muestra esta ayuda
1662
-v,--verbose    Activa el modo verbose
1663
-d,--debug      Activa el modo debug.
1664
--version ver   Fija la version con la que van a trabajar.
1665
-r,--package-root root    Fija la carpeta del raiz del sistema de paquetes
1666

    
1667
COMMANDS:
1668

    
1669
mkinstall [OPTIONS] install-file packages-file
1670
    -L, --jrelin=path
1671
    -W, --jrewin=path
1672
    -l, --addjrelin
1673
    -w, --addjrewin
1674
    -N, --distribution-name=name
1675

    
1676
lsi [OPTIONS]
1677
    -l, --long-format
1678

    
1679
mks [OPTIONS]
1680
     -c, --clear-list
1681
     --excludepkg pkgcode
1682
     --excludepki pkgcode
1683
     --exclude pkgcode
1684
     -s, --include-default-selection
1685
     -i, --index-only
1686
     -I full-path-to-package, --include full-path-to-package
1687

    
1688
mkdist [OPTIONS]
1689
     -s STATE, --state=STATE
1690
     -b BUILD, --build=BUILD
1691
     -N, --distribution-name=name
1692

    
1693
mkmirror [OPTIONS]
1694
     -b, --build buildnumber
1695

    
1696
mkhtml [OPTIONS]
1697
     -c, --clear-list
1698
     --excludepkg pkgcode
1699
     --excludepki pkgcode
1700
     --exclude pkgcode
1701

    
1702
show OPTIONS package-index
1703
    --verify, -V
1704

    
1705
edit [OPTIONS] package-index
1706
     --replace=@search@replace@
1707
     --onlysign
1708
     --sign, -S
1709

    
1710
editall [OPTIONS]
1711
     -c, --clear-list
1712
     --excludepkg pkgcode
1713
     --excludepki pkgcode
1714
     --exclude pkgcode
1715
     --replace=@search@replace@
1716
     --sign, -S
1717

    
1718
install [OPTIONS] url-to-pki
1719
     -f, --force
1720

    
1721
prepare-portable [OPTIONS]
1722
     -b, --build
1723
     -s, --state
1724

    
1725
mkportable [OPTIONS]
1726
     -b, --build
1727
     -s, --state
1728

    
1729
La version actual a utilizar es:
1730
  %s
1731

    
1732
El directorio root de la estructura de packetes actual es:
1733
  %s
1734
    """ % (VERSION, GVSPKG_ROOT)
1735

    
1736

    
1737
def help(args):
1738
    print """
1739
usage: gvspkg [OPTIONS] COMMANDS
1740

    
1741
OPTIONS:
1742

    
1743
-h|--help
1744
    Muestra esta ayuda
1745

    
1746
-v|--verbose
1747
    Activa el modo verbose
1748

    
1749
-d|--debug
1750
    Activa el modo debug. Se muestran mensajes que pueden ser
1751
    utilies de cara a depuracion.
1752

    
1753
--version version
1754
    Fija la version con la que van a trabajar los comandos indicados.
1755

    
1756
-r|--package-root package-root
1757
    Fija la carpeta en la que va a buscar el raiz del sistema de paquetes
1758
    con el que trabajar
1759

    
1760
COMMANDS:
1761

    
1762
mkinstall [OPTIONS] install-file packages-file
1763

    
1764
    OPTIONS:
1765

    
1766
    -L | --jrelin=path
1767

    
1768
    -W | --jrewin=path
1769

    
1770
    -l | --addjrelin
1771

    
1772
    -w | --addjrewin
1773

    
1774
    -N | --distribution-name=name
1775
      Nombre usado como sufijo del nuevo binario a generar. Por defecto si no se
1776
      indica valdra "custom".
1777

    
1778

    
1779
lsi [OPTIONS]
1780
    Lista los indices disponibles de la version
1781

    
1782
    OPTIONS:
1783

    
1784
    -l | --long-format
1785
        Muestra para cada paquete la informacion del package.info
1786

    
1787
mks [OPTIONS]
1788
     Crea el fichero packages.gvspki con los indices de la
1789
     version y packages.gvspkg con los paquetes.
1790

    
1791
     OPTIONS:
1792

    
1793
     -c | --clear-list
1794
        Elimina la lista de paquetes a utilizar recreandola a partir
1795
        de los paquetes del pool tomando el ultimo build de cada paquete.
1796

    
1797
     --excludepkg pkgcode
1798
        No incluye el paquete indicado en el fichero gvspkg a generar
1799

    
1800
     --excludepki pkgcode
1801
        No incluye el paquete indicado en el fichero gvspki a generar
1802

    
1803
     --exclude pkgcode
1804
        No incluye el paquete indicado en los ficheros gvspkg y gvspki a generar
1805

    
1806
     -s | --include-default-selection
1807
        Incluye el fichero "defaultPackages", que se debe encontrar en el
1808
        directorio corriente, con los nombres de paquetes a seleccionar
1809
        por defecto.
1810

    
1811
     -i | --index-only
1812
        No crea el fichero gvspks, solo crea el gvspki
1813

    
1814
     -I full-path-to-package | --include full-path-to-package
1815
        Agrega el paquete indicado a la lista de paquetes aunque no coincida para
1816
        la version de gvSIG con la que se esta trabajando.
1817

    
1818
mkdist [OPTIONS]
1819
     Crea los ficheros de la distribucion standard para el buil dindicado a partir de
1820
     la distribucion online y los paquetes que hayan en el pool para esta version.
1821
     Ejecuta un "mks" y un "mkhtml" automaticamente para preparar el conjunto de paquetes
1822
     a incluir en la distribucion, y una vez preparados ejecuta un "mkinsrall" por
1823
     S.O. (win y lin), renombrando los ficheros generados segun corresponda.
1824

    
1825
     OPTIONS:
1826
     -s STATE | --state=STATE
1827
        Indica el estado de la distribucion a generar, devel, alpha, ..., debe estar
1828
        deacuerdo con lo que diga el cihero online a usar como base.
1829

    
1830
     -b BUILD | --build=BUILD
1831
        Indica el numero de build de la destribucion a generar. Es usado para localizar
1832
        los ficheros en la carpeta builds de la distribucion y para saber donde debe
1833
        dejar los ficheros generados.
1834

    
1835
     -N | --distribution-name=name
1836
        Nombre usado como sufijo del nuevo binario a generar. Por defecto si no se
1837
        indica valdra "standard".
1838

    
1839

    
1840
mkmirror [OPTIONS]
1841

    
1842
  Prepara una carpeta para hacer un mirror de un build en concreto.
1843

    
1844
     OPTIONS:
1845

    
1846
     -b | --build buildnumber
1847
       Indica el numero de build del que se quiere hacer un mirror.
1848

    
1849
mkhtml [OPTIONS]
1850
     ????
1851

    
1852
     OPTIONS:
1853

    
1854
     -c | --clear-list
1855
        Elimina la lista de paquetes a utilizar recreandola a partir
1856
        de los paquetes del pool tomando el ultimo build de cada paquete.
1857

    
1858
     --excludepkg pkgcode
1859
        No incluye el paquete indicado en el fichero gvspkg a generar
1860

    
1861
     --excludepki pkgcode
1862
        No incluye el paquete indicado en el fichero gvspki a generar
1863

    
1864
     --exclude pkgcode
1865
        No incluye el paquete indicado en los ficheros gvspkg y gvspki a generar
1866

    
1867
show OPTIONS package-index
1868
    Muestra el package.info del indice indicado como parametro.
1869

    
1870
    OPTIONS
1871

    
1872
    --verify | -V
1873
      Comprueba la forma del packete.
1874

    
1875
edit [OPTIONS] package-index
1876
    Edita el package.info del indice indicado como parametro.
1877

    
1878
     OPTIONS:
1879

    
1880
     --replace=@search@replace@
1881
       Reemplaza en el package.info de cada paquete la cadena "search" por "replace"
1882
       todas las veces que aparezca. "@" puede ser cualquier caracter que no aparezca
1883
       en "search" y "replace".
1884
       Esta opcion puede indicarse tatas veces como reemplazos se deseen efectuar.
1885

    
1886
     --onlysign
1887
       firma el package.info sin editarlo de forma interactiva (no invoca al editor antes
1888
       de firmarlo).
1889

    
1890
     --sign | -S
1891
       Firma el package.info tras terminar la edicion (bach o interactiva)
1892

    
1893
editall [OPTIONS]
1894
    Edita todos los package.info
1895

    
1896
     OPTIONS:
1897

    
1898
     -c | --clear-list
1899
        Elimina la lista de paquetes a utilizar recreandola a partir
1900
        de los paquetes del pool tomando el ultimo build de cada paquete.
1901

    
1902
     --excludepkg pkgcode
1903
        No incluye el paquete indicado en el fichero gvspkg a generar
1904

    
1905
     --excludepki pkgcode
1906
        No incluye el paquete indicado en el fichero gvspki a generar
1907

    
1908
     --exclude pkgcode
1909
        No incluye el paquete indicado en los ficheros gvspkg y gvspki a generar
1910

    
1911
     --replace=@search@replace@
1912
       Reemplaza en el package.info de cada paquete la cadena "search" por "replace"
1913
       todas las veces que aparezca. "@" puede ser cualquier caracter que no aparezca
1914
       en "search" y "replace".
1915
       Esta opcion puede indicarse tatas veces como reemplazos se deseen efectuar.
1916

    
1917
      --sign | -S
1918
        Firma todos los paquetes que sean oficiales
1919

    
1920
install [OPTIONS] url-to-pki
1921
    descarga de la url indicada un fichero gvspki e instala este junto con su correspondiente
1922
    pkg en el pool local.
1923

    
1924
     OPTIONS:
1925

    
1926
     -f | --force
1927
       fuerza la sobreescritura de los ficheros en caso de que estos ya existan.
1928

    
1929
Si en la carpeta corriente encuentra un fichero gvspkg.options cargara los
1930
flags indicados ahi como flags por defecto para cada comando. El formato del
1931
fichero es:
1932
  main=OPCION-POR-DEFECTO
1933
  mks=OPCOPNES-POR-DEFECTO
1934
Donde main indica las opciones por defecto generales, independientes del comando
1935
a ejecutar. "mks" indica las opciones por defecto a usar en el comando "mks", y
1936
asi sucesivamente, indicando el nombre del comando seguido de un "=" y las opciones
1937
por defecto para ese comando.
1938

    
1939
Por defecto la version la obtiene del nombre de la carpeta
1940
corriente (%s). Las opciones indicadas en el fichero gvspkg.options tienen prioridad
1941
sobre este valor.
1942

    
1943
El directorio root de la estructura de packetes lo buscara en el
1944
sitio indicado por la variable de entorno GVPKG_ROOT, y si esta no
1945
esta establecida usara "%s". Las opciones indicadas en el fichero gvspkg.options
1946
tienen prioridad sobre este valor.
1947

    
1948
    """ % (VERSION, GVSPKG_ROOT)
1949

    
1950
def executeCommand(*args):
1951
    command = "shorthelp"
1952
    if len(args)>0:
1953
        command=args[0]
1954

    
1955
    r=1
1956
    if command=="lsi" :
1957
        r=lsi(args)
1958
    elif command == "mks":
1959
        r=mks(args)
1960
    elif command == "edit":
1961
        r=edit(args)
1962
    elif command == "editall":
1963
        r=editall(args)
1964
    elif command == "show":
1965
        r=show(args)
1966
    elif command == "mkhtml":
1967
        r=mkhtml(args)
1968
    elif command == "mkinstall":
1969
        r=mkinstall(args)
1970
    elif command == "install":
1971
        r=install(args)
1972
    elif command == "mkdist":
1973
        r=mkdist(args)
1974
    elif command == "mkmirror":
1975
        r=mkmirror(args)
1976
    elif command == "mkportable":
1977
        r=mkportable(args)
1978
    elif command == "prepare-portable":
1979
        r=prepare_portable(args)
1980
    elif command == "help":
1981
        r=help(args)
1982
    else:
1983
        r=shorthelp(args)
1984
    return r
1985

    
1986
def main():
1987
    global DEBUG
1988
    global VERSION
1989
    global VERBOSE
1990
    global GVSPKG_ROOT
1991
    global SEARCH_VERSIONS
1992

    
1993
    cmd = Command(sys.argv)
1994
    try:
1995
        opts, args = getopt.getopt(cmd.getArgs("main"), "dhvr:", ["debug", "verbose", "version=", "package-root=","help","search_versions="])
1996
    except getopt.GetoptError, err:
1997
        # print help information and exit:
1998
        print str(err) # will print something like "option -a not recognized"
1999
        shorthelp(None)
2000
        sys.exit(2)
2001

    
2002
    for opt, arg in opts:
2003
        if opt in ("-h", "--help"):
2004
            shorthelp(args)
2005
            sys.exit()
2006
        elif opt in ("-d", "--debug"):
2007
            DEBUG = True
2008
        elif opt in ("-v", "--verbose"):
2009
            VERBOSE = True
2010
        elif opt in ("--version"):
2011
            VERSION = arg
2012
        elif opt in ("--search_versions"):
2013
            SEARCH_VERSIONS.append(arg)
2014
        elif opt in ("-r", "--package-root"):
2015
            GVSPKG_ROOT = arg
2016
        else:
2017
            assert False, "unhandled option"
2018
    #
2019
    debug("DEBUG=%s" % DEBUG)
2020
    debug("VERSION=%s" % VERSION)
2021
    debug("GVSPKG_ROOT=%s" % GVSPKG_ROOT)
2022
    if GVSPKG_ROOT == None:
2023
      shorthelp(None)
2024
    else:
2025
      r=executeCommand(*args)
2026
      sys.exit(r)
2027

    
2028
main()
2029

    
2030

    
2031

    
2032