Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_csv.py

raw
1 # Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[email protected]>
2 # Copyright (c) 2018, Dag Wieers (@dagwieers) <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import csv
12 import typing as t
13 from io import StringIO
14
15 from ansible.module_utils.common.text.converters import to_native
16
17 if t.TYPE_CHECKING:
18 from collections.abc import Sequence
19
20 class DialectParamsOrNone(t.TypedDict):
21 delimiter: t.NotRequired[str | None]
22 doublequote: t.NotRequired[bool | None]
23 escapechar: t.NotRequired[str | None]
24 lineterminator: t.NotRequired[str | None]
25 quotechar: t.NotRequired[str | None]
26 quoting: t.NotRequired[int | None]
27 skipinitialspace: t.NotRequired[bool | None]
28 strict: t.NotRequired[bool | None]
29
30
31 class CustomDialectFailureError(Exception):
32 pass
33
34
35 class DialectNotAvailableError(Exception):
36 pass
37
38
39 CSVError = csv.Error
40
41
42 def initialize_dialect(dialect: str, **kwargs: t.Unpack[DialectParamsOrNone]) -> str:
43 # Add Unix dialect from Python 3
44 class unix_dialect(csv.Dialect):
45 """Describe the usual properties of Unix-generated CSV files."""
46
47 delimiter = ","
48 quotechar = '"'
49 doublequote = True
50 skipinitialspace = False
51 lineterminator = "\n"
52 quoting = csv.QUOTE_ALL
53
54 csv.register_dialect("unix", unix_dialect)
55
56 if dialect not in csv.list_dialects():
57 raise DialectNotAvailableError(f"Dialect '{dialect}' is not supported by your version of python.")
58
59 # Create a dictionary from only set options
60 dialect_params = {k: v for k, v in kwargs.items() if v is not None}
61 if dialect_params:
62 try:
63 csv.register_dialect("custom", dialect, **dialect_params) # type: ignore
64 except TypeError as e:
65 raise CustomDialectFailureError(f"Unable to create custom dialect: {e}") from e
66 dialect = "custom"
67
68 return dialect
69
70
71 def read_csv(data: str, dialect: str, fieldnames: Sequence[str] | None = None) -> csv.DictReader:
72 BOM = "\ufeff"
73 data = to_native(data, errors="surrogate_or_strict")
74 if data.startswith(BOM):
75 data = data[len(BOM) :]
76
77 fake_fh = StringIO(data)
78
79 reader = csv.DictReader(fake_fh, fieldnames=fieldnames, dialect=dialect)
80
81 return reader