func handleImports()

in Sources/MockoloFramework/Operations/ImportsHandler.swift [19:70]


func handleImports(pathToImportsMap: ImportMap,
                   customImports: [String]?,
                   excludeImports: [String]?,
                   testableImports: [String]?,
                   relevantPaths: [String]) -> String {
    var topLevelImports: [Import] = []
    var conditionalBlocks: [ConditionalImportBlock] = []

    // 1. Collect imports from all relevant files
    for (path, parsedImports) in pathToImportsMap {
        guard relevantPaths.contains(path) else { continue }

        for `import` in parsedImports {
            switch `import` {
            case .simple(let simple):
                topLevelImports.append(simple)
            case .conditional(let conditional):
                conditionalBlocks.append(conditional)
            }
        }
    }

    // 2. Sort conditional blocks by offset (file appearance order)
    conditionalBlocks.sort(by: { $0.offset < $1.offset })

    // 3. Add custom imports
    if let customImports {
        topLevelImports.append(contentsOf: customImports.map {
            Import(moduleName: $0)
        })
    }

    var contents: [ImportContent] {
        topLevelImports.map { .simple($0) } + conditionalBlocks.map { .conditional($0) }
    }

    // 4. Add testable imports if the import does not exist
    if let testableImports {
        let usedNames = Set(visitModuleName(contents))
        for name in testableImports {
            if !usedNames.contains(name) {
                topLevelImports.append(Import(moduleName: name).asTestable)
            }
        }
    }

    return renderImportContents(
        contents,
        excludeImports: excludeImports,
        testableImports: testableImports
    )
}