summaryrefslogtreecommitdiffstats
path: root/scripts/license-yaml2csv.py
blob: dcd6f442f14ada939806ea764819734373dc0c2a (plain)
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
66
67
68
#!/usr/bin/env python3
#
# Copyright (C) 2018 by Michael Olbrich <m.olbrich@pengutronix.de>
#
# For further information about the PTXdist project and license conditions
# see the README file.
#

import argparse
import sys
import yaml

def parse_separator(arg):
    if len(arg) != 1:
        raise argparse.ArgumentTypeError('field separator must be a single character')
    else:
        return arg

def parse_input(arg):
    if arg == '-':
        return sys.stdin
    try:
        return open(arg)
    except:
        raise argparse.ArgumentTypeError('cannot access input file "{}"'.format(arg))

def parse_fields(arg):
    tmp = arg.split(',')
    fields = []
    for field in tmp:
        field = field.strip()
        if field:
            fields.append(field)
    if not fields:
        raise argparse.ArgumentTypeError('at least on field must be specified')
    return fields

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--separator', type=parse_separator, default=',',
    help='field separator [,]')
parser.add_argument('-f', '--fields', type=parse_fields,
    default=['name', 'version', 'section', 'licenses', 'license-flags'],
    help='field list [name,version,section,licenses,license-flags]')
parser.add_argument('input', nargs='?', type=parse_input,
    default=sys.stdin, help='license yaml file [stdin]')

args = parser.parse_args()

for (_, record) in yaml.load(args.input.read(), Loader=yaml.loader.BaseLoader).items():
    line = ""
    for field in args.fields:
        if line:
            line += args.separator
        value = record.get(field, None)
        if not value:
            value = ''
        if field == 'license-flags':
            value = " ".join(value)
        elif not isinstance(value, str):
            value = str(value)
        quote = args.separator in value or '"' in value
        if quote:
            line += '"'
        line += value.replace('"', '""')
        if quote:
            line += '"'
    line += "\n"
    sys.stdout.write(line)