Skip to content
Snippets Groups Projects
Select Git revision
  • e256b53a6fed140a0166b9b4ea31690bf731c92c
  • main default
  • 1.4.4
  • 1.4.3
  • 1.4.2
  • 1.4.1
  • 1.4.0
  • 1.3.0
  • 1.2.0
  • 1.1.0
  • 1.0.0
11 results

main.swift

Blame
  • main.swift 1.55 KiB
    //
    //  main.swift
    //  SwiftMetaModelGenerator
    //
    //  Created by Tobias on 23.06.21.
    //
    
    import Foundation
    import ArgumentParser
    import SwiftSyntax
    import Stencil
    import PathKit
    
    struct SwiftMetaModelGenerator: ParsableCommand
    {
        @Option(name: .shortAndLong, help: "Input file or folder")
        var input: String
    
        @Option(name: .shortAndLong, help: "Output file")
        var output: String
        
        mutating func run() throws {
            let inputPath = Path(input)
            let classes: [ClassDeclaration]
            if inputPath.isDirectory {
                classes = try inputPath.iterateChildren().flatMap( { try processFile(file: $0) })
            } else {
                classes = try processFile(file: inputPath)
            }
            
            let context = [
              "classes": classes
            ]
    
            let environment = Environment(loader: FileSystemLoader(paths: ["/Users/tobias/Documents/Programmieren/Projects/SwiftMetaModelGenerator/SwiftMetaModelGenerator/templates/"]))
            let rendered = try environment.renderTemplate(name: "meta_model.stencil", context: context)
            
            try Path(output).write(rendered)
        }
        
        func processFile(file: Path) throws -> [ClassDeclaration] {
            if !(file.extension?.lowercased().hasSuffix("swift") ?? false) {
                return []
            }
            
            let content: String = try file.read()
            
            let collector = DeclarationCollector()
            let tree = try SyntaxParser.parse(source: content)
            collector.walk(tree)
            
            return collector.classes
        }
    }
    
    SwiftMetaModelGenerator.main()