File: tools.py

package info (click to toggle)
distro-info-data 0.68
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 104 kB
  • sloc: python: 297; makefile: 23
file content (65 lines) | stat: -rw-r--r-- 2,246 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Copyright (C) 2012, Benjamin Drung <bdrung@debian.org>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

"""Common parsing and utility functions"""

import argparse
import csv
import datetime
from pathlib import Path


def convert_date(string):
    """Convert a date string in ISO 8601 into a datetime object."""
    if not string:
        date = None
    else:
        parts = [int(x) for x in string.split("-")]
        if len(parts) == 3:
            (year, month, day) = parts
            date = datetime.date(year, month, day)
        else:
            raise ValueError("Date not in ISO 8601 format.")
    return date


def get_csv_dict_reader(filename: str) -> csv.DictReader:
    """Read the given CSV file and return a `csv.DictReader`.

    Comments (lines starting with #) will be removed.
    """
    with open(filename, encoding="ascii") as csv_file:
        content = csv_file.readlines()
    # Remove comments
    for counter, line in enumerate(content):
        if line.startswith("#"):
            content[counter] = "\n"
    return csv.DictReader(content)


def main(validation_function):
    """Main function with command line parameter parsing."""
    parser = argparse.ArgumentParser(usage="%(prog)s [-h] csv-file")

    parser.add_argument(
        "csv_file", metavar="csv-file", type=Path, help="CSV file to validate"
    )

    args = parser.parse_args()
    if not args.csv_file.exists():
        parser.error(f"{args.csv_file} does not exist.")

    distro = args.csv_file.stem

    return int(not validation_function(str(args.csv_file), distro))