3 # Simple script to import a file to the datastore
4 # Reinier Heeres, <reinier@heeres.eu>, 2007-12-20
6 # Modified by Phil Bordelon <phil@lsu.edu> 2007-12-20, 2007-12-21
7 # to support adding metadata. Note that the MIME-type is required,
8 # as otherwise the datastore will not accept the file.
14 from sugar
.datastore
import datastore
16 def build_option_parser():
18 usage
= "Usage: %prog <file> -m MIMETYPE [-t TITLE] [-d DESC] [-T tag1 [-T tag2 ...]]"
19 parser
= optparse
.OptionParser(usage
=usage
)
21 parser
.add_option("-t", "--title", action
="store", dest
="title",
22 help="Set the title of the journal entry to TITLE", metavar
="TITLE",
24 parser
.add_option("-d", "--description", action
="store",
25 dest
="description", metavar
="DESC",
26 help="Set the description of the journal entry to DESC",
28 parser
.add_option("-m", "--mimetype", action
="store",
29 dest
="mimetype", metavar
="MIMETYPE",
30 help="Set the file's MIME-type to MIMETYPE",
32 parser
.add_option("-T", "--tag", action
="append", dest
="tag_list",
33 help="Add tag TAG to the journal entry's tags; this option can be repeated",
37 if __name__
== "__main__":
39 parser
= build_option_parser()
40 options
, args
= parser
.parse_args()
46 absname
= os
.path
.abspath(fname
)
47 if not os
.path
.exists(absname
):
48 print 'Error: File does not exist.'
52 if not options
.mimetype
:
53 print 'Error: No MIME-type given.'
58 entry
= datastore
.create()
59 entry
.set_file_path(absname
)
61 # Set the mimetype to the provided one.
62 entry
.metadata
['mime_type'] = options
.mimetype
64 # If no title is given, use the filename.
66 entry
.metadata
['title'] = options
.title
68 entry
.metadata
['title'] = fname
70 # Use the description given, otherwise leave it blank.
71 if options
.description
:
72 entry
.metadata
['description'] = options
.description
74 # Lastly, if any tags are given, combine them into a single string
77 tag_string
= " ".join(options
.tag_list
)
78 entry
.metadata
['tags'] = tag_string
80 datastore
.write(entry
)
81 print 'Created as %s' % (entry
.object_id
)
86 print 'Error: %s' % (e
)