|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import csv |
| 5 | +import os |
| 6 | +import sys |
| 7 | +from dataclasses import dataclass, asdict, fields |
| 8 | +from typing import List |
| 9 | +from gherkin.parser import Parser |
| 10 | +from gherkin.token_scanner import TokenScanner |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class Rule: |
| 14 | + """A class representing a rule extracted from a Gherkin feature file.""" |
| 15 | + identifier: str |
| 16 | + description: str |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def field_names(cls) -> List[str]: |
| 20 | + return [f.name for f in fields(cls)] |
| 21 | + |
| 22 | +def extract_rules_from_feature(file_path): |
| 23 | + """Parse a Gherkin feature file and extract the rules.""" |
| 24 | + try: |
| 25 | + with open(file_path, 'r', encoding='utf-8') as file: |
| 26 | + content = file.read() |
| 27 | + |
| 28 | + parser = Parser() |
| 29 | + feature_document = parser.parse(TokenScanner(content)) |
| 30 | + rules = [] |
| 31 | + |
| 32 | + if 'feature' in feature_document: |
| 33 | + feature = feature_document['feature'] |
| 34 | + |
| 35 | + if 'children' in feature: |
| 36 | + for child in feature['children']: |
| 37 | + if 'rule' in child: |
| 38 | + rule = child['rule'] |
| 39 | + rule_id = rule.get('name', '').strip() |
| 40 | + description = rule.get('description', '').strip() |
| 41 | + rules.append(Rule( |
| 42 | + identifier=rule_id, |
| 43 | + description=description |
| 44 | + )) |
| 45 | + |
| 46 | + return rules |
| 47 | + except Exception as e: |
| 48 | + print(f"Error parsing {file_path}: {e}", file=sys.stderr) |
| 49 | + return [] |
| 50 | + |
| 51 | +def main(): |
| 52 | + parser = argparse.ArgumentParser(description='Extract rules from Gherkin feature files and save to CSV') |
| 53 | + parser.add_argument('feature_files', nargs='+', help='Paths to feature files') |
| 54 | + parser.add_argument('--output', '-o', default='rules.csv', help='Output CSV file path') |
| 55 | + |
| 56 | + args = parser.parse_args() |
| 57 | + all_rules = [] |
| 58 | + |
| 59 | + for feature_path in args.feature_files: |
| 60 | + if os.path.isfile(feature_path): |
| 61 | + print(f"Processing {feature_path}") |
| 62 | + rules = extract_rules_from_feature(feature_path) |
| 63 | + all_rules.extend(rules) |
| 64 | + else: |
| 65 | + print(f"File not found: {feature_path}", file=sys.stderr) |
| 66 | + |
| 67 | + with open(args.output, 'w', newline='', encoding='utf-8') as csvfile: |
| 68 | + writer = csv.DictWriter(csvfile, fieldnames=Rule.field_names()) |
| 69 | + writer.writeheader() |
| 70 | + writer.writerows([asdict(rule) for rule in all_rules]) |
| 71 | + |
| 72 | + print(f"Extracted {len(all_rules)} rules to {args.output}") |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + main() |
0 commit comments