Debian Codegraph @

clevercsv/console/commands/standardize.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 from __future__ import annotations
4
5 import io
6 import os
7 import shutil
8 import sys
9 import tempfile
10
11 from typing import TYPE_CHECKING
12 from typing import Optional
13
14 from wilderness import Command
15
16 from clevercsv._types import StrPath
17 from clevercsv.dialect import SimpleDialect
18 from clevercsv.encoding import get_encoding
19 from clevercsv.read import reader
20 from clevercsv.utils import sha1sum
21 from clevercsv.wrappers import detect_dialect
22 from clevercsv.write import writer
23
24 if TYPE_CHECKING:
25 from clevercsv._types import SupportsWrite
26
27 from ._docs import FLAG_DESCRIPTIONS
28 from ._utils import parse_int
29
30
31 class StandardizeCommand(Command):
32 _description = (
33 "The standardize command can be used to convert a non-standard "
34 "CSVfile to the standard RFC-4180 format [1]. When using the "
35 "--in-place option, the return code of CleverCSV can be used to check "
36 "whether a file was altered or not. The return code"
37 "will be 2 when the file was altered and 0 otherwise.\n\n"
38 "[1]: https://tools.ietf.org/html/rfc4180"
39 )
40
41 def __init__(self) -> None:
42 super().__init__(
43 name="standardize",
44 title="Convert a CSV file to one that conforms to RFC-4180",
45 description=self._description,
46 extra_sections={"CleverCSV": "Part of the CleverCSV suite"},
47 )
48
49 def register(self) -> None:
50 self.add_argument(
51 "path", help="Path to one or more CSV file(s)", nargs="+"
52 )
53 self.add_argument(
54 "-e",
55 "--encoding",
56 action="append",
57 help="Set the encoding of the file(s)",
58 description=(
59 "The file encoding of the given CSV file is automatically "
60 "detected using chardet. While chardet is incredibly "
61 "accurate, it is not perfect. In the rare cases that it makes "
62 "a mistake in detecting the file encoding, you can override "
63 "the encoding by providing it through this flag. For this "
64 "command, the provided encoding will also be used for the "
65 "output file(s). When only one encoding is given, it will be "
66 "used for all files given on the command line. When multiple "
67 "encodings are given, the number must correspond to the "
68 "number of files provided as input."
69 ),
70 default=[],
71 )
72 self.add_argument(
73 "-E",
74 "--target-encoding",
75 help="Set the encoding of the output file(s)",
76 description=(
77 "If ommited, the output file encoding while be the same "
78 "as that of the original file."
79 ),
80 type=str,
81 )
82 self.add_argument(
83 "-i",
84 "--in-place",
85 help="Standardize and overwrite the input file(s)",
86 action="store_true",
87 )
88 self.add_argument(
89 "-n",
90 "--num-chars",
91 help="Number of characters to use for detection",
92 description=FLAG_DESCRIPTIONS["num-chars"],
93 type=int,
94 )
95 self.add_argument(
96 "-o",
97 "--output",
98 action="append",
99 help="Output file(s) to write to. If omitted, print to stdout.",
100 description=(
101 "The output files to write the standardized input files to. "
102 "The order of the input files and the order of the output "
103 "files should match if this option is used with more than one "
104 "input file."
105 ),
106 default=[],
107 )
108 self.add_argument(
109 "-t",
110 "--transpose",
111 action="store_true",
112 help="Transpose the columns of the input file(s) before writing",
113 )
114
115 def handle(self) -> int:
116 """Handle the standardize command
117
118 The return value of this method is the exit code of the command, with 0
119 meaning success.
120
121 """
122 verbose = self.args.verbose
123 paths = self.args.path
124 outputs = self.args.output
125 encodings = self.args.encoding
126 num_chars = parse_int(self.args.num_chars, "num-chars")
127 in_place = self.args.in_place
128 target_encoding = self.args.target_encoding
129
130 if in_place and outputs:
131 print(
132 "Incompatible options '-i/--in-place' and '-o/--output'. "
133 "Can't edit file in-place and write to an output file.",
134 file=sys.stderr,
135 )
136 return 1
137
138 if len(outputs) == 0:
139 outputs = [None for _ in range(len(paths))]
140
141 if not in_place and len(outputs) != len(paths):
142 print(
143 "Number of output files should match the number of input files.",
144 file=sys.stderr,
145 )
146 return 1
147
148 if len(encodings) == 0:
149 encodings = [None for _ in range(len(paths))]
150 if len(encodings) == 1:
151 encodings = [encodings[0] for _ in range(len(paths))]
152 elif len(encodings) != len(paths):
153 print(
154 "Number of encodings should be 1 or the same as the "
155 "number of input paths.",
156 file=sys.stderr,
157 )
158 return 1
159
160 global_retval = 0
161 for path, output, encoding in zip(paths, outputs, encodings):
162 retval = self.handle_path(
163 path,
164 output,
165 encoding=encoding,
166 verbose=verbose,
167 num_chars=num_chars,
168 target_encoding=target_encoding,
169 )
170 if retval > 0 and global_retval == 0:
171 global_retval = retval
172 if retval == 1:
173 return retval
174 return global_retval
175
176 def handle_path(
177 self,
178 path: StrPath,
179 output: Optional[StrPath],
180 encoding: Optional[str] = None,
181 num_chars: Optional[int] = None,
182 verbose: bool = False,
183 target_encoding: Optional[str] = None,
184 ) -> int:
185 encoding = encoding or get_encoding(path)
186 target_encoding = target_encoding or encoding
187 dialect = detect_dialect(
188 path, num_chars=num_chars, encoding=encoding, verbose=verbose
189 )
190 if dialect is None:
191 print("Error: dialect detection failed.", file=sys.stderr)
192 return 1
193
194 if self.args.in_place:
195 return self._in_place(path, dialect, encoding, target_encoding)
196 elif output is None:
197 return self._to_stdout(path, dialect, encoding)
198 return self._to_file(path, output, dialect, encoding, target_encoding)
199
200 def _write_transposed(
201 self,
202 path: StrPath,
203 stream: SupportsWrite[str],
204 dialect: SimpleDialect,
205 encoding: Optional[str],
206 ) -> None:
207 with open(path, "r", newline="", encoding=encoding) as fp:
208 read = reader(fp, dialect=dialect)
209 rows = list(read)
210 rows = list(map(list, zip(*rows)))
211 write = writer(stream, dialect="excel")
212 for row in rows:
213 write.writerow(row)
214
215 def _write_direct(
216 self,
217 path: StrPath,
218 stream: SupportsWrite[str],
219 dialect: SimpleDialect,
220 encoding: Optional[str],
221 ) -> None:
222 with open(path, "r", newline="", encoding=encoding) as fp:
223 read = reader(fp, dialect=dialect)
224 write = writer(stream, dialect="excel")
225 for row in read:
226 write.writerow(row)
227
228 def _write_to_stream(
229 self,
230 path: StrPath,
231 stream: SupportsWrite[str],
232 dialect: SimpleDialect,
233 encoding: Optional[str],
234 ) -> None:
235 if self.args.transpose:
236 self._write_transposed(path, stream, dialect, encoding)
237 else:
238 self._write_direct(path, stream, dialect, encoding)
239
240 def _in_place(
241 self,
242 path: StrPath,
243 dialect: SimpleDialect,
244 encoding: Optional[str],
245 target_encoding: Optional[str],
246 ) -> int:
247 """In-place mode overwrites the input file, if necessary
248
249 The return value of this method is to be used as the status code of
250 the command. A return value of 0 means no edits were made as the file
251 was already in the correct format, and a value of 2 means the file was
252 modified.
253
254 """
255 tmpfd, tmpfname = tempfile.mkstemp(prefix="clevercsv_", suffix=".csv")
256 tmpid = os.fdopen(tmpfd, "w", newline="", encoding=target_encoding)
257 self._write_to_stream(path, tmpid, dialect, encoding)
258 tmpid.close()
259
260 previous_sha1 = sha1sum(path)
261 new_sha1 = sha1sum(tmpfname)
262 if previous_sha1 == new_sha1:
263 os.unlink(tmpfname)
264 return 0
265
266 shutil.move(tmpfname, path)
267 return 2
268
269 def _to_stdout(
270 self, path: StrPath, dialect: SimpleDialect, encoding: Optional[str]
271 ) -> int:
272 stream = io.StringIO(newline="")
273 self._write_to_stream(path, stream, dialect, encoding)
274 print(stream.getvalue(), end="")
275 stream.close()
276 return 0
277
278 def _to_file(
279 self,
280 path: StrPath,
281 output: StrPath,
282 dialect: SimpleDialect,
283 encoding: Optional[str],
284 target_encoding: Optional[str],
285 ) -> int:
286 with open(output, "w", newline="", encoding=target_encoding) as fp:
287 self._write_to_stream(path, fp, dialect, encoding)
288 return 0