Source

csound-package-manager / cspm.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#!/usr/bin/env python

import ConfigParser
import argparse
import os
import sys
import sqlite3
import tarfile
import urllib
from xml.sax import make_parser 
from xml.sax.handler import ContentHandler 
from operator import itemgetter 

SCRIPT_PATH = os.path.dirname(os.path.realpath(sys.argv[0]))
#SERVER = "file://" + SCRIPT_PATH + os.sep + "testRepo" # temporary local test repo
SERVER = "http://cspm-server.appspot.com/repo" # temporary local test repo

HOME_FOLDER = os.getenv('HOME')
SETTINGS_FOLDER = HOME_FOLDER + os.sep + ".cspm"
CACHE_FOLDER = SETTINGS_FOLDER + os.sep + "cache"
PKG_FOLDER = SETTINGS_FOLDER + os.sep + "packages"
DB_FILE = SETTINGS_FOLDER + os.sep + "cspm.db"
DB_VERSION = 1
VERSION = "1.0 Alpha"

# DB FUNCTIONS ####################################

def db_connect():
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    return conn


def db_init():
    if(os.path.isfile(DB_FILE)):
        return
    message("initializing cspm.db database\n")
    conn = db_connect()
    # do table creates here    
    conn.execute('''CREATE TABLE version
             (version integer)''')
    conn.execute('''CREATE TABLE servers
             (id integer primary key, name text, url text)''')
    conn.execute('''CREATE TABLE packages
             (name text NOT NULL, 
             version text NOT NULL, 
             author text NOT NULL, 
             email text NOT NULL, 
             description text NOT NULL, 
             files text NOT NULL,
             dependencies text, 
             serverId integer,
             installed integer)''')
    with conn:
        conn.execute('INSERT into version values (?)', (DB_VERSION,))
        conn.execute('INSERT into servers (name, url) values (?,?)', 
                     ('Main CSPM Server',SERVER))
    
    conn.close()

        
# PROGRAM FUNCTIONS ####################################


def error(msg):
    print "cspm: error: ", msg
    
def message(msg):
    print "cspm: ", msg

def dummyFunc(args):
    message("Command not implemented: Args %s"%args)
    return True


def init_CSPM():
    if(os.path.isdir(SETTINGS_FOLDER)):
        return
    message("Initializing .cspm folder: " + SETTINGS_FOLDER)
    os.mkdir(SETTINGS_FOLDER)
    db_init()

# INIT COMMAND ####################################

def initCspmFile(args):
    
    pkgName = args.name
    version = args.version
    author = args.author
    email = args.email
         
    f = open('package.cspm', 'w')
    
    c = ConfigParser.RawConfigParser()
    section = 'package'
    c.add_section(section)
    c.set(section, 'Name', pkgName)
    c.set(section, 'Version', version)
    c.set(section, 'Author', author)
    c.set(section, 'Email', email)
    c.set(section, 'Description', "description of " + pkgName)
    c.set(section, 'Website')
    c.set(section, 'License')
    c.set(section, 'Copyright')
    c.set(section, 'Files')
    c.set(section, 'Dependencies')
    c.write(f)
    
    f.flush()
    f.close()
    
    print "Created package.cspm file"

# BUILD COMMAND ################################

def buildPackage(args):
    
    c = ConfigParser.RawConfigParser()
    c.readfp(args.cspmfile)
#    found = c.readfp(args.cspmfile)
#    if(len(found) == 0):
#        error("unable to read .cspm file: " + args.cspmfile.name)
#        sys.exit(1)
    filename = args.cspmfile.name
    basename = os.path.basename(filename)
    pkgName = c.get('package', 'name') + "-" + c.get('package', 'version')
    print "Building Package", pkgName, "using", filename, "..."
    fileStr = c.get('package', 'files')
    files = fileStr.split()
    fileError = False
    
    cspmdir = os.path.dirname(os.path.realpath(filename))
    
    for i in files:
        if(not os.path.isfile(cspmdir + os.sep + i)):
            error("unable to locate file " + i)
            fileError = True
    if(fileError):
        error("could not build package")
        sys.exit(1)
    t = tarfile.open(pkgName + '.tar.bz2', 'w:bz2')
    t.add(args.cspmfile.name, pkgName + os.sep + basename)
    for i in files:
        t.add(cspmdir + os.sep + i, pkgName + os.sep + i)
    
    t.close()
    print "Created package", pkgName + '.tar.bz2'
     
# XML COMMAND ################################
       
def cspm_to_xml(args):
    if(not args.cspmfile.name.endswith('.cspm')):
        error("xml requires a .cspm file")
        sys.exit(1)
    c = ConfigParser.ConfigParser()
    c.readfp(args.cspmfile)
    values = c.items('package')
    print "<package>"
    for i,j in values:
        print "  <%s>%s</%s>"%(i,j,i)
    print "</package>"
    

# INFO COMMAND ####################################

def findPackage(pkgName):
    conn = db_connect()

    c = conn.execute("select * from packages where name = ?", (pkgName,))
    packages = c.fetchall()
    
    return sorted(packages, key=itemgetter(1), reverse=True)

def packageInfo(args):
    
    pkgname = args.package
    pkginfo = findPackage(pkgname)
    pkg = None
    
    if(len(pkginfo) == 0):
        error("No package information for package: %s"%pkgname)
        sys.exit(1)
    
    
    if(args.version != None):
        for p in pkginfo:
            if(p['version'] == args.version):
                pkg = p
                break
        if(pkg == None):
            error("No package information for package %s with version %s"%(pkgname,args.version))
            print "Available Versions:"
            for p in pkginfo:
                print "  ", p['version']
            sys.exit(1)
    else:
        pkg = pkginfo[0]            
    

    print "Package:", pkg['name'] 
    print "Version:", pkg['version']
    print "Author:", pkg['author']
    print "Email:", pkg['email']
    print "Description: %s\n"%pkg['description'] 

    print "Available Versions:"
    for p in pkginfo:
        print "  ", p['version']

# INSTALLED COMMAND ################################

def find_installed_packages(args):
    conn = db_connect()
    
    c = conn.execute("select * from packages where installed = 1")
    packages = c.fetchall()
    
    print "The following packages are currently installed:"
    for p in packages:
        print "  %s %s"%(p[0], p[1])
    
    conn.close()
    
def list_packages(args):
    conn = db_connect()
    
    c = conn.execute("select * from packages")
    packages = c.fetchall()
    
    print "The following packages are available:"
    for p in packages:
        installed = ''
        if (p['installed'] == 1):
            installed = '(*)'
        print "  %s %s %s"%(p['name'], p['version'], installed)
    
    conn.close()

# UPDATE COMMAND ################################

class RepoHandler(ContentHandler):
    def __init__(self, serverId):
        self.packages = []
        self.currentPackage = None
        self.currentTag = None
        self.currentValue = ""
        self.serverId = serverId
        
    def startElement(self, name, attrs):
        if(name == "package"):
            self.currentPackage = {}
        elif(self.currentPackage != None):
            self.currentTag = name
        
    def endElement(self, name):
        if(name == "package"):
            cp = self.currentPackage
            pkg = (cp['name'], cp['version'], 
                   cp['author'], cp['email'],
                   cp['description'], cp['files'],
                   cp['dependencies'], self.serverId )
            
            self.packages.append(pkg)
            self.currentPackage = None
        elif(self.currentTag != None):
            self.currentPackage[self.currentTag] = self.currentValue
            self.currentTag = None
            self.currentValue = None
    
    def characters(self, content):
        if(self.currentPackage != None):
            self.currentValue = content

def update_from_repositories(args):
    conn = db_connect()
    servers = conn.execute('select * from servers')
    servers = [tuple(s) for s in servers]
    
    for s in servers:
        message('downloading repository %s(%s)'%(s[1],s[2]))
        parser = make_parser()
        r = RepoHandler(s[0])
        parser.setContentHandler(r)
        try:
            parser.parse(urllib.urlopen(s[2] + '/cspmrepo.xml'))
        except IOError,e:
            error("skipping server '" + s[1] + "'\n  " + str(e))
            
            continue 
        
        with conn:
            conn.execute("delete from packages")
            conn.executemany('insert into packages values (?,?,?,?,?,?,?,?,0)', r.packages)
        
    
# INSTALL COMMAND ################################

def install_package(args):
    
    if(not os.path.isdir(CACHE_FOLDER)):
        os.mkdir(CACHE_FOLDER)
    if(not os.path.isdir(PKG_FOLDER)):
        os.mkdir(PKG_FOLDER)
    
    conn = db_connect()
    
    servers = {}
    vals = [tuple(i) for i in conn.execute('select * from servers')]
    for i in vals:
        servers[i[0]] = i[1:]
    
    vals = [i.rsplit('-',1) for i in args.package]
    errors = False
    pkgs = []
    
    for i in vals:
        pkg = None
        if(len(i) == 1):
            c = conn.execute('select * from packages where name = ? order by version', (i[0],))
            pkg = c.fetchone()
        else:
            c = conn.execute('select * from packages where name = ? and version = ?', (i[0],i[1]))
            pkg = c.fetchone()
        
        if(pkg == None):
            error('unable to find package: ' + str(i))
            errors = True
        else:
            if(pkg['installed'] == 1):
                print "skipping", pkg['name'] + '-' + pkg['version']," (Already installed)"
            pkgs.append(pkg)
            
    if(errors):
        sys.exit(1)
    
    outdir = PKG_FOLDER
    
    if(args.local):
        outdir = os.path.realpath('.')
    print "Downloading packages..."
    
    for i in pkgs:
        pkgname = i['name'] + '-' + i['version']
        server = servers[i['serverId']]
        url = server[1] + '/packages/' + pkgname + '.tar.bz2'
        filename = CACHE_FOLDER + os.sep + pkgname + '.tar.bz2'
        
        if(os.path.isfile(filename)):
            print "skipping downloading", pkgname, ": file already downloaded"
        else:    
            print "Downloading package:", pkgname
            print "    ", url
            try:
                urllib.urlretrieve(url, filename)
            except:
                error('unable to retrieve '+ url)
                os.remove(filename)
                sys.exit(1)

        #handle untarring of bz2 file
        print "extracting ", os.path.basename(filename)
        t = tarfile.open(filename, 'r:bz2')
        t.extractall(outdir)

# SERVER FUNCTIONS #################################

def get_server_list():
    conn = db_connect()
    counter = 1
    ids = []
    serverStr = ""
    for s in conn.execute('select * from servers'):
        serverStr += "%d) %s - %s\n"%(counter, s['name'], s['url'])
        counter += 1
        ids.append(s['id'])
    return (serverStr, ids)
    
def server_add(args):
    conn = db_connect()
    with conn:
        conn.execute('insert into servers (name, url) values (?,?)', (args.name, args.url))
    print "Added server: %s - %s"%(args.name, args.url)

def server_remove(args):
    servers = get_server_list()
    
    print(servers[0])
    serverId = -1
    while(serverId < 0):
        val = -1
        try:
            val = input("Choose a server to remove (choose 0 to cancel): ")
            val = int(val)
        except:
            print("Error - input was not a number")
            serverId = -1
            continue
        if(val == 0):
            sys.exit(0)
        if(val < 0 or val > len(servers[1])):
            print("Error - number was outside of acceptable range")
            serverId = -1
            continue
        serverId = servers[1][val - 1]
    
    conn = db_connect()
    with conn:
        conn.execute("delete from servers where id = ?", (serverId,))

def server_list(args):
    servers = get_server_list()
    print servers[0]


# MAIN FUNCTION ####################################
    
def main():
    
    init_CSPM()
    
    parser = argparse.ArgumentParser(prog='cspm', 
                                     description='Csound Package Manager - version 0.2')

    subparsers = parser.add_subparsers(title='Commands')
    
    cmd = subparsers.add_parser('server', help='Add, remove, and list servers.')
    server = cmd.add_subparsers(title='server sub-commands')
    scmd = server.add_parser('add', help='Add server to the list of server.')
    scmd.add_argument('name', help='Display name of server.')
    scmd.add_argument('url', help='URL of server. (can be local by using file://)')
    scmd.set_defaults(func=server_add)
    
    scmd = server.add_parser('remove', help='Remove server from the list of servers.')
    scmd.set_defaults(func=server_remove)
    
    scmd = server.add_parser('list', help='Display list of servers.')
    scmd.set_defaults(func=server_list)
    
    cmd = subparsers.add_parser('install', help='Installs a list of packages.')
    cmd.add_argument('--local', action='store_true', help='Install packages into local directory')
    cmd.add_argument('package', nargs='+')
    cmd.set_defaults(func=install_package)
    
    cmd = subparsers.add_parser('update', help='Update list of known packages.')
    cmd.set_defaults(func=update_from_repositories)

    cmd = subparsers.add_parser('list', help='List packages matching a search string.')
    cmd.add_argument('search-string', nargs='?')
    cmd.set_defaults(func=list_packages)

    cmd = subparsers.add_parser('installed', help='List installed packages.')
    cmd.set_defaults(func=find_installed_packages)

    cmd = subparsers.add_parser('info', help='Display detailed information about a particular package.')
    cmd.add_argument('package', help='name of package to find')
    cmd.add_argument('version', nargs='?', help='Optional version for package, otherwise finds latest version')
    cmd.set_defaults(func=packageInfo)
    
    cmd = subparsers.add_parser('init', help='Create a default .cspm file in the current directory.')
    cmd.add_argument('name')
    cmd.add_argument('author')
    cmd.add_argument('version', nargs='?', default='1.0')
    cmd.add_argument('email', nargs='?', default='email@address.com')
    cmd.set_defaults(func=initCspmFile)
    
    cmd = subparsers.add_parser('build', help='Build a package using the passed in .cspm file.')
    cmd.add_argument('cspmfile', help='.cspm file to use for building', type=argparse.FileType('r'))
    cmd.set_defaults(func=buildPackage)
    
    cmd = subparsers.add_parser('xml', 
                                help='Generate XML from .cspm file, suitable for cspmrepo.xml.')
    cmd.add_argument('cspmfile', help='.cspm file to use for building', type=argparse.FileType('r'))
    cmd.set_defaults(func=cspm_to_xml)

    args = parser.parse_args()
    args.func(args)

    
if __name__ == '__main__':
    main()