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
|
#!/usr/bin/env python
"""Copyright Canonical Limited 2005
Author: Daniel Silverstone <daniel.silverstone@canonical.com>
Celso Providelo <celso.providelo@canonical.com>
Simple tool to upload arbitrary files into Librarian
"""
from canonical.lp import initZopeless
from canonical.launchpad.scripts import execute_zcml_for_scripts
from zope.component import getUtility
from canonical.librarian.interfaces import ILibrarianClient
from canonical.launchpad.helpers import filenameToContentType
from optparse import OptionParser
import os
def addfile(filepath, client):
"""Add a file to librarian."""
# verify filepath
if not filepath:
print 'Filepath is required'
return
# open given file
try:
fd = open(filepath)
except IOError:
print 'Could not open:', filepath
return
# XXX: cprov 20050613
# os.fstat(fd) presents an strange behavior
flen = os.stat(filepath).st_size
filename = os.path.basename(filepath)
ftype = filenameToContentType(filename)
alias = client.addFile(filename, flen, fd, contentType=ftype)
print 'Added as', alias
# commit previous transactions
tm.commit()
if __name__ == '__main__':
# Parse the commandline...
parser = OptionParser()
parser.add_option("-f","--file", dest="filepath",
help="filename to import",
metavar="FILE",
default=None)
(options,args) = parser.parse_args()
filepath = options.filepath
# setup a transaction manager to LPDB
tm = initZopeless()
# load the zcml configuration
execute_zcml_for_scripts()
# get an librarian client instance
client = getUtility(ILibrarianClient)
addfile(filepath, client)
|