| 1 |
|
| 2 |
|
| 3 |
import sys |
| 4 |
|
| 5 |
from typing import List |
| 6 |
from typing import Optional |
| 7 |
from typing import Sequence |
| 8 |
|
| 9 |
from wilderness import Command |
| 10 |
|
| 11 |
from clevercsv._optional import import_optional_dependency |
| 12 |
from clevercsv.exceptions import NoDetectionResult |
| 13 |
from clevercsv.wrappers import read_table |
| 14 |
|
| 15 |
from ._docs import FLAG_DESCRIPTIONS |
| 16 |
from ._utils import parse_int |
| 17 |
|
| 18 |
|
| 19 |
class ViewCommand(Command): |
| 20 |
_description = ( |
| 21 |
"The view command is useful to quickly inspect a messy CSV file on " |
| 22 |
"the command line." |
| 23 |
) |
| 24 |
|
| 25 |
def __init__(self) -> None: |
| 26 |
super().__init__( |
| 27 |
name="view", |
| 28 |
title="View the CSV file on the command line using TabView", |
| 29 |
description=self._description, |
| 30 |
extra_sections={"CleverCSV": "Part of the CleverCSV suite"}, |
| 31 |
) |
| 32 |
|
| 33 |
def register(self) -> None: |
| 34 |
self.add_argument("path", help="Path to the CSV file") |
| 35 |
self.add_argument( |
| 36 |
"-e", |
| 37 |
"--encoding", |
| 38 |
help="Set the encoding of the file", |
| 39 |
description=FLAG_DESCRIPTIONS["encoding"], |
| 40 |
) |
| 41 |
self.add_argument( |
| 42 |
"-n", |
| 43 |
"--num-chars", |
| 44 |
help="Number of characters to use for detection", |
| 45 |
type=int, |
| 46 |
description=FLAG_DESCRIPTIONS["num-chars"], |
| 47 |
) |
| 48 |
self.add_argument( |
| 49 |
"-t", |
| 50 |
"--transpose", |
| 51 |
action="store_true", |
| 52 |
help="Transpose the columns of the input file before viewing", |
| 53 |
) |
| 54 |
|
| 55 |
def _tabview(self, rows: List[List[str]]) -> None: |
| 56 |
if sys.platform == "win32": |
| 57 |
print( |
| 58 |
"Error: unfortunately Tabview is not available on Windows, so " |
| 59 |
"the clevercsv view command is not available", |
| 60 |
file=sys.stderr, |
| 61 |
) |
| 62 |
return |
| 63 |
|
| •64 |
import_optional_dependency("tabview", raise_on_missing=False) |
| 65 |
from tabview import view |
| 66 |
|
| 67 |
view(rows) |
| 68 |
|
| 69 |
def handle(self) -> int: |
| 70 |
verbose = self.args.verbose |
| 71 |
num_chars = parse_int(self.args.num_chars, "num-chars") |
| 72 |
try: |
| 73 |
rows = read_table( |
| 74 |
self.args.path, |
| 75 |
encoding=self.args.encoding, |
| 76 |
num_chars=num_chars, |
| 77 |
verbose=verbose, |
| 78 |
) |
| 79 |
except NoDetectionResult: |
| 80 |
print("Error: dialect detection failed.", file=sys.stderr) |
| 81 |
return 1 |
| 82 |
|
| 83 |
if self.args.transpose: |
| 84 |
max_row_length = max(map(len, rows)) |
| 85 |
fixed_rows: List[Sequence[Optional[str]]] = [] |
| 86 |
for row in rows: |
| 87 |
if len(row) == max_row_length: |
| 88 |
fixed_rows.append(row) |
| 89 |
else: |
| 90 |
fixed_rows.append( |
| 91 |
row + [None] * (max_row_length - len(row)) |
| 92 |
) |
| 93 |
rows = list(map(list, zip(*fixed_rows))) |
| 94 |
self._tabview(rows) |
| 95 |
return 0 |