1#########################################################################
2#                                                                       #
3#                                                                       #
4#   copyright 2002 Paul Henry Tremblay                                  #
5#                                                                       #
6#   This program is distributed in the hope that it will be useful,     #
7#   but WITHOUT ANY WARRANTY; without even the implied warranty of      #
8#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    #
9#   General Public License for more details.                            #
10#                                                                       #
11#                                                                       #
12#########################################################################
13import os
14
15from calibre.ebooks.rtf2xml import copy
16from calibre.utils.cleantext import clean_ascii_chars
17from calibre.ptempfile import better_mktemp
18
19
20class FixLineEndings:
21    """Fix line endings"""
22
23    def __init__(self,
24            bug_handler,
25            in_file=None,
26            copy=None,
27            run_level=1,
28            replace_illegals=1,
29            ):
30        self.__file = in_file
31        self.__bug_handler = bug_handler
32        self.__copy = copy
33        self.__run_level = run_level
34        self.__write_to = better_mktemp()
35        self.__replace_illegals = replace_illegals
36
37    def fix_endings(self):
38        # read
39        with open(self.__file, 'rb') as read_obj:
40            input_file = read_obj.read()
41        # calibre go from win and mac to unix
42        input_file = input_file.replace(b'\r\n', b'\n')
43        input_file = input_file.replace(b'\r', b'\n')
44        # remove ASCII invalid chars : 0 to 8 and 11-14 to 24-26-27
45        if self.__replace_illegals:
46            input_file = clean_ascii_chars(input_file)
47        # write
48        with open(self.__write_to, 'wb') as write_obj:
49            write_obj.write(input_file)
50        # copy
51        copy_obj = copy.Copy(bug_handler=self.__bug_handler)
52        if self.__copy:
53            copy_obj.copy_file(self.__write_to, "line_endings.data")
54        copy_obj.rename(self.__write_to, self.__file)
55        os.remove(self.__write_to)
56