deal with stderr in man
[xo.git] / jput
blob4cb62013c979a184d6c071fa7074ffdd35f94212
1 #!/usr/bin/python
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.
10 import sys
11 import os
12 import optparse
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",
23 default=None)
24 parser.add_option("-d", "--description", action="store",
25 dest="description", metavar="DESC",
26 help="Set the description of the journal entry to DESC",
27 default=None)
28 parser.add_option("-m", "--mimetype", action="store",
29 dest="mimetype", metavar="MIMETYPE",
30 help="Set the file's MIME-type to MIMETYPE",
31 default=None)
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",
34 metavar="TAG")
35 return parser
37 if __name__ == "__main__":
39 parser = build_option_parser()
40 options, args = parser.parse_args()
41 if len(args) < 1:
42 parser.print_help()
43 exit(0)
45 fname = args[0]
46 absname = os.path.abspath(fname)
47 if not os.path.exists(absname):
48 print 'Error: File does not exist.'
49 parser.print_help()
50 exit(0)
52 if not options.mimetype:
53 print 'Error: No MIME-type given.'
54 parser.print_help()
55 exit(0)
57 try:
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.
65 if options.title:
66 entry.metadata['title'] = options.title
67 else:
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
75 # and save them.
76 if options.tag_list:
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)
83 entry.destroy()
85 except Exception, e:
86 print 'Error: %s' % (e)