brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.9 KiB · 6e1aca9 Raw
104 lines · python
1#!/usr/bin/env python2#3# ===- csv2json.py - Static Analyzer test helper ---*- python -*-===#4#5# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.6# See https://llvm.org/LICENSE.txt for license information.7# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception8#9# ===------------------------------------------------------------------------===#10 11r"""12Clang Static Analyzer test helper13=================================14 15This script converts a CSV file to a JSON file with a specific structure.16 17The JSON file contains a single dictionary.  The keys of this dictionary18are taken from the first column of the CSV. The values are dictionaries19themselves, mapping the CSV header names (except the first column) to20the corresponding row values.21 22 23Usage:24  csv2json.py <source-file>25 26Example:27  // RUN: %csv2json.py %t | FileCheck %s28"""29 30import csv31import sys32import json33 34 35def csv_to_json_dict(csv_filepath):36    """37    Args:38        csv_filepath: The path to the input CSV file.39 40    Raises:41        FileNotFoundError: If the CSV file does not exist.42        csv.Error: If there is an error parsing the CSV file.43        Exception: For any other unexpected errors.44    """45    try:46        with open(csv_filepath, "r", encoding="utf-8") as csvfile:47            reader = csv.reader(csvfile, skipinitialspace=True)48 49            # Read the header row (column names)50            try:51                header = next(reader)52            except StopIteration:  # Handle empty CSV file53                json.dumps({}, indent=2)  # write an empty dict54                return55 56            # handle a csv file that contains no rows, not even a header row.57            if not header:58                json.dumps({}, indent=2)59                return60 61            header_length = len(header)62            other_column_names = header[1:]63 64            data_dict = {}65 66            for row in reader:67                if len(row) != header_length:68                    raise csv.Error("Inconsistent CSV file")69                    exit(1)70 71                key = row[0]72                value_map = {}73 74                for i, col_name in enumerate(other_column_names):75                    # +1 to skip the first column76                    value_map[col_name] = row[i + 1].strip()77 78                data_dict[key] = value_map79 80        return json.dumps(data_dict, indent=2)81 82    except FileNotFoundError:83        raise FileNotFoundError(f"Error: CSV file not found at {csv_filepath}")84    except csv.Error as e:85        raise csv.Error(f"Error parsing CSV file: {e}")86    except Exception as e:87        raise Exception(f"An unexpected error occurred: {e}")88 89 90def main():91    """Example usage with error handling."""92    csv_file = sys.argv[1]93 94    try:95        print(csv_to_json_dict(csv_file))96    except (FileNotFoundError, csv.Error, Exception) as e:97        print(str(e))98    except:99        print("An error occured")100 101 102if __name__ == "__main__":103    main()104