+
+def writeOutput(cal, outfile=''):
+ '''Takes a list of lines and outputs to the specified file'''
+
+ if not cal:
+ sys.stderr.write('Refusing to write out an empty file')
+ sys.exit(0)
+
+ if not outfile:
+ out = sys.stdout
+ else:
+ try:
+ out = open(outfile, 'w')
+ except (IOError, OSError), e:
+ sys.stderr.write('%s\n'%e)
+ sys.exit(1)
+
+ cal.serialize(out)
+
+ if not out == sys.stdout:
+ out.close()
+
+if __name__ == '__main__':
+ # Only load options parsing if this script was called directly, skip it
+ # if it's being called as a module.
+ from optparse import OptionParser
+
+ parser = OptionParser('usage: %prog [options] url')
+ parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
+ default=False, help='Take a calendar from standard input')
+ parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
+ default=False, help='Be verbose when rules are being applied')
+ parser.add_option('-o', '--output', dest='outfile', default='',
+ help='Specify output file (defaults to standard output)')
+ parser.add_option('-m','--encoding', dest='encoding', default='',
+ help='Specify a different character encoding'
+ '(ignored if the remote server also specifies one)')
+ parser.add_option('-t','--timezone', dest='timezone', default='Australia/Perth',
+ help='Specify a timezone to use if the remote calendar doesn\'t set it properly')
+
+ (options, args) = parser.parse_args()
+
+ # Ensure the rules process using the desired timezone
+ ruleConfig = {}
+ ruleConfig["defaultTZ"] = options.timezone
+
+ # If the user passed us a 'stdin' argument, we'll go with that,
+ # otherwise we'll try for a url opener
+ if not args and not options.stdin:
+ parser.print_usage()
+ sys.exit(0)
+ elif not options.stdin:
+ url = args[0]
+ else:
+ url = ''
+
+ (content, encoding) = getContent(url, options.stdin)
+ encoding = encoding or options.encoding or 'utf-8'
+
+ cal = vobject.readOne(unicode(content, encoding))
+ cal = applyRules(cal, generateRules(ruleConfig), options.verbose)
+
+ writeOutput(cal, options.outfile)