summaryrefslogtreecommitdiffstats
path: root/cli_helpers/tabular_output/delimited_output_adapter.py
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 02:59:59 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 02:59:59 +0000
commitc9ef4ed560a5de28fce031882257b6741565284e (patch)
tree07afa40629447df997726efd4de84d5987ff5e50 /cli_helpers/tabular_output/delimited_output_adapter.py
parentInitial commit. (diff)
downloadcli-helpers-c9ef4ed560a5de28fce031882257b6741565284e.tar.xz
cli-helpers-c9ef4ed560a5de28fce031882257b6741565284e.zip
Adding upstream version 2.3.1.upstream/2.3.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'cli_helpers/tabular_output/delimited_output_adapter.py')
-rw-r--r--cli_helpers/tabular_output/delimited_output_adapter.py56
1 files changed, 56 insertions, 0 deletions
diff --git a/cli_helpers/tabular_output/delimited_output_adapter.py b/cli_helpers/tabular_output/delimited_output_adapter.py
new file mode 100644
index 0000000..b812456
--- /dev/null
+++ b/cli_helpers/tabular_output/delimited_output_adapter.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+"""A delimited data output adapter (e.g. CSV, TSV)."""
+
+from __future__ import unicode_literals
+import contextlib
+
+from cli_helpers.compat import csv, StringIO
+from cli_helpers.utils import filter_dict_by_key
+from .preprocessors import bytes_to_string, override_missing_value
+
+supported_formats = ("csv", "csv-tab")
+preprocessors = (override_missing_value, bytes_to_string)
+
+
+class linewriter(object):
+ def __init__(self):
+ self.reset()
+
+ def reset(self):
+ self.line = None
+
+ def write(self, d):
+ self.line = d
+
+
+def adapter(data, headers, table_format="csv", **kwargs):
+ """Wrap the formatting inside a function for TabularOutputFormatter."""
+ keys = (
+ "dialect",
+ "delimiter",
+ "doublequote",
+ "escapechar",
+ "quotechar",
+ "quoting",
+ "skipinitialspace",
+ "strict",
+ )
+ if table_format == "csv":
+ delimiter = ","
+ elif table_format == "csv-tab":
+ delimiter = "\t"
+ else:
+ raise ValueError("Invalid table_format specified.")
+
+ ckwargs = {"delimiter": delimiter, "lineterminator": ""}
+ ckwargs.update(filter_dict_by_key(kwargs, keys))
+
+ l = linewriter()
+ writer = csv.writer(l, **ckwargs)
+ writer.writerow(headers)
+ yield l.line
+
+ for row in data:
+ l.reset()
+ writer.writerow(row)
+ yield l.line