- try:
- (options, args) = getopt(sys.argv[1:], "lp")
- except:
- usage()
- print "\nUnrecognized option"
- sys.exit(1)
-
- opened_files = False
- # Open files
- if len(args) == 0:
- source = sys.stdin
- output = sys.stdout
- elif len(args) == 2:
- source = open(args[0], 'rb')
- output = open(args[1], 'wb')
- opened_files = True
- else:
- usage()
- print "\nEither zero or two arguments must be given."
- sys.exit(1)
-
- conversions = False
-
- for (opt, param) in options:
- if opt == "-l":
- from prefs2prefs_lfuns import conversions
- elif opt == "-p":
- from prefs2prefs_prefs import conversions
-
- if not conversions:
- usage()
- print "\nNeither -l nor -p given."
- sys.exit(1)
- elif len(options) > 1:
- usage()
- print "\nOnly one of -l or -p should be given."
- sys.exit(1)
-
- current_format = len(conversions)
- lines = read(source)
- format = get_format(lines)
-
- while format < current_format:
- for c in conversions[format]:
- for i in range(len(lines)):
- (update, newline) = c(lines[i])
- if update:
- lines[i] = newline
-
- update_format(lines)
-
- # sanity check
- old_format = format
- format = get_format(lines)
- if int(old_format) + 1 != int(format):
- sys.stderr.write("Failed to convert to new format!\n")
- sys.exit(1)
-
- write(output, lines)
-
- # Close files
- if opened_files:
- source.close()
- output.close()
-
- return 0
+ try:
+ (options, args) = getopt(sys.argv[1:], "lp")
+ except:
+ usage()
+ abort("Unrecognized option")
+
+ opened_files = False
+ # Open files
+ if len(args) == 0:
+ source = sys.stdin
+ output = sys.stdout
+ elif len(args) == 2:
+ source = io.open(args[0], 'r', encoding='utf_8', errors='surrogateescape')
+ output = io.open(args[1], 'w', encoding='utf_8', newline='\n')
+ opened_files = True
+ else:
+ usage()
+ abort("Either zero or two arguments must be given.")
+
+ conversions = False
+
+ for (opt, param) in options:
+ if opt == "-l":
+ from prefs2prefs_lfuns import conversions
+ elif opt == "-p":
+ from prefs2prefs_prefs import conversions
+
+ if not conversions:
+ usage()
+ abort("Neither -l nor -p given.")
+ elif len(options) > 1:
+ usage()
+ abort("Only one of -l or -p should be given.")
+
+ current_format = len(conversions)
+ lines = read(source)
+ format = get_format(lines)
+
+ while format < current_format:
+ target_format, convert = conversions[format]
+ old_format = format
+
+ # make sure the conversion list is sequential
+ if int(old_format) + 1 != target_format:
+ abort("Something is wrong with the conversion chain.")
+
+ for c in convert:
+ for i in range(len(lines)):
+ (update, newline) = c(lines[i])
+ if update:
+ lines[i] = newline
+
+ update_format(lines)
+ format = get_format(lines)
+
+ # sanity check
+ if int(old_format) + 1 != int(format):
+ abort("Failed to convert to new format!")
+
+ write(output, lines)
+
+ # Close files
+ if opened_files:
+ source.close()
+ output.close()
+
+ return 0