Skip to content

Commit

Permalink
csv-to-md: read stdin if no file is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
leroyguillaume committed Feb 7, 2022
1 parent 5b32b59 commit 68759d3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ csv-to-md -s ";" -a r tests/table.csv
# | Fedora | | Red Hat |

csv-to-md -s ";" -a r tests/table.csv | xclip -selection clipboard # Copy markdown table in clipboard

psql -h 127.0.0.1 -U postgres postgres -c "select * from test" --csv | csv-to-md # Generate markdown table from PostgreSQL query
```

### Library
Expand Down
31 changes: 22 additions & 9 deletions markdown_table_generator/markdown_table_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from enum import Enum
from math import ceil, floor
from typing import List, Optional
import sys


class Alignment(Enum):
Expand Down Expand Up @@ -52,7 +53,11 @@ def csv_to_md() -> None:
arg_parser = ArgumentParser(
description="Generate markdown table from CSV",
)
arg_parser.add_argument("file", nargs="+")
arg_parser.add_argument(
"file",
help="CSV file to convert to markdown (if empty, stdin is used)",
nargs="*",
)
arg_parser.add_argument(
"-a", "--alignment",
help="table alignment (l|c|r for left, center or right;default: 'l')",
Expand All @@ -68,14 +73,16 @@ def csv_to_md() -> None:
)
args = arg_parser.parse_args()
alignment = __alignment_from_string(args.alignment)
for i, filepath in enumerate(args.file):
with open(filepath, "r", encoding="utf-8") as file:
csv = file.readlines()
table = table_from_csv(csv, args.separator, alignment)
markdown = generate_markdown(table)
print(markdown)
if i < len(args.file) - 1:
print()
if len(args.file) == 0:
csv = sys.stdin.readlines()
__print_markdown_from_csv(csv, args.separator, alignment)
else:
for i, filepath in enumerate(args.file):
with open(filepath, "r", encoding="utf-8") as file:
csv = file.readlines()
__print_markdown_from_csv(csv, args.separator, alignment)
if i < len(args.file) - 1:
print()


def generate_markdown(table: Table) -> str:
Expand Down Expand Up @@ -204,6 +211,12 @@ def __generate_dash_row(header_row: List[Optional[Cell]], columns_size: List[int
return string


def __print_markdown_from_csv(csv: str, separator: str, alignment: Alignment) -> None:
table = table_from_csv(csv, separator, alignment)
markdown = generate_markdown(table)
print(markdown)


def __generate_string_with(character: str, size: int) -> str:
string = ""
for _ in range(0, size):
Expand Down

0 comments on commit 68759d3

Please sign in to comment.