initial commit
This commit is contained in:
parent
a12428b3c3
commit
d9cfdd7717
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/configuration/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
31
Package.swift
Normal file
31
Package.swift
Normal file
@ -0,0 +1,31 @@
|
||||
// swift-tools-version: 6.1
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "YAMLMerger",
|
||||
platforms: [
|
||||
.macOS(.v14),
|
||||
.iOS(.v17)
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
name: "YAMLMerger",
|
||||
targets: ["YAMLMerger"]
|
||||
),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: [
|
||||
.target(
|
||||
name: "YAMLMerger",
|
||||
dependencies: []
|
||||
),
|
||||
.testTarget(
|
||||
name: "YAMLMergerTests",
|
||||
dependencies: ["YAMLMerger"],
|
||||
resources: [
|
||||
.copy("Schema")
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
231
README.md
231
README.md
@ -1,2 +1,231 @@
|
||||
# YamlMerger
|
||||
# YAMLMerger
|
||||
|
||||
A Swift package for merging multiple YAML files from subdirectories into a single combined file.
|
||||
|
||||
## Features
|
||||
|
||||
- Recursively scans subdirectories for YAML files (.yaml or .yml extensions)
|
||||
- Sorts subdirectories and files alphabetically
|
||||
- Merges content in a predictable order
|
||||
- Outputs a single combined YAML file
|
||||
|
||||
## Directory Structure for OpenAPI Schemas
|
||||
|
||||
When using YAMLMerger for OpenAPI specifications, organize your YAML files into the following subdirectories:
|
||||
|
||||
```
|
||||
Schema/
|
||||
├── 01_Info/ # OpenAPI info section (version, title, description, etc.)
|
||||
├── 02_Servers/ # API server URLs and environment configurations
|
||||
├── 03_Tags/ # Tag definitions for organizing endpoints
|
||||
├── 04_Paths/ # API endpoint definitions
|
||||
├── 05_Webhooks/ # Webhook/callback definitions (OpenAPI 3.1+)
|
||||
├── 06_Components/ # Reusable components (schemas, responses, parameters, etc.)
|
||||
├── 07_Security/ # Top-level security requirements
|
||||
└── 08_ExternalDocs/ # External documentation references
|
||||
```
|
||||
|
||||
Place your distinct YAML files into the corresponding folders:
|
||||
|
||||
#### 01_Info/
|
||||
Add files containing OpenAPI metadata and general information.
|
||||
|
||||
Example (`__info.yaml`):
|
||||
```yaml
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
title: My API
|
||||
version: 1.0.0
|
||||
description: A comprehensive REST API for managing resources
|
||||
contact:
|
||||
name: API Support
|
||||
email: support@example.com
|
||||
license:
|
||||
name: Apache 2.0
|
||||
url: https://www.apache.org/licenses/LICENSE-2.0.html
|
||||
```
|
||||
|
||||
#### 02_Servers/
|
||||
Add server configuration files (production, staging, development URLs).
|
||||
|
||||
Example (`__servers.yaml`):
|
||||
```yaml
|
||||
servers:
|
||||
- url: https://api.example.com/v1
|
||||
description: Production server
|
||||
- url: https://staging-api.example.com/v1
|
||||
description: Staging server
|
||||
- url: http://localhost:8000/v1
|
||||
description: Development server
|
||||
```
|
||||
|
||||
#### 03_Tags/
|
||||
Add tag definitions to organize and group your API endpoints.
|
||||
|
||||
Example (`__tags.yaml`):
|
||||
```yaml
|
||||
tags:
|
||||
- name: users
|
||||
description: User management operations
|
||||
- name: products
|
||||
description: Product catalog operations
|
||||
- name: orders
|
||||
description: Order processing and management
|
||||
```
|
||||
|
||||
#### 04_Paths/
|
||||
Add individual endpoint definition files (one per endpoint or grouped logically).
|
||||
|
||||
Example (`users.yaml`):
|
||||
```yaml
|
||||
/users:
|
||||
get:
|
||||
tags:
|
||||
- users
|
||||
summary: List all users
|
||||
responses:
|
||||
'200':
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/User'
|
||||
post:
|
||||
tags:
|
||||
- users
|
||||
summary: Create a new user
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/UserInput'
|
||||
responses:
|
||||
'201':
|
||||
description: User created successfully
|
||||
```
|
||||
|
||||
#### 05_Webhooks/
|
||||
Add webhook definitions for callbacks your API sends (OpenAPI 3.1+).
|
||||
|
||||
Example (`order-events.yaml`):
|
||||
```yaml
|
||||
orderStatusChanged:
|
||||
post:
|
||||
summary: Order status change notification
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
orderId:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
timestamp:
|
||||
type: string
|
||||
format: date-time
|
||||
responses:
|
||||
'200':
|
||||
description: Webhook received successfully
|
||||
```
|
||||
|
||||
#### 06_Components/
|
||||
Add reusable schema definitions, response objects, parameters, security schemes, etc.
|
||||
|
||||
Example (`User.yaml`):
|
||||
```yaml
|
||||
User:
|
||||
type: object
|
||||
required:
|
||||
- id
|
||||
- email
|
||||
- name
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
email:
|
||||
type: string
|
||||
format: email
|
||||
name:
|
||||
type: string
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
```
|
||||
|
||||
#### 07_Security/
|
||||
Add top-level security requirements that apply across the API.
|
||||
|
||||
Example (`__securitySchemes.yaml`):
|
||||
```yaml
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
apiKey:
|
||||
type: apiKey
|
||||
in: header
|
||||
name: X-API-Key
|
||||
security:
|
||||
- bearerAuth: []
|
||||
```
|
||||
|
||||
#### 08_ExternalDocs/
|
||||
Add links to external documentation.
|
||||
|
||||
Example (`__externalDocs.yaml`):
|
||||
```yaml
|
||||
externalDocs:
|
||||
description: Find more information in our documentation
|
||||
url: https://docs.example.com/api
|
||||
```
|
||||
|
||||
The numeric prefixes ensure subdirectories are processed in the correct order during merging.
|
||||
|
||||
### How the Merger Works
|
||||
|
||||
Each folder contains a `__*.yaml` file (e.g., `__paths.yaml`, `__components.yaml`) that serves as a section header. Due to the `__` prefix, these files are sorted and merged first within each folder, followed by all other YAML files in alphabetical order. This ensures:
|
||||
|
||||
1. Folders are processed in numerical order (01 → 02 → 03 → ...)
|
||||
2. Within each folder, the section header (`__*.yaml`) is merged first
|
||||
3. All additional YAML files in the folder are then merged in alphabetical order
|
||||
4. The result is a single, properly structured OpenAPI specification file
|
||||
|
||||
## Usage
|
||||
|
||||
```swift
|
||||
import YAMLMerger
|
||||
|
||||
let merger = YAMLMerger(
|
||||
rootDirectory: URL(fileURLWithPath: "/path/to/yaml/files"),
|
||||
outputFileName: "CombinedSpec.yaml"
|
||||
)
|
||||
merger.merge()
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- Swift 6.1+
|
||||
- macOS 14.0+ / iOS 17.0+
|
||||
|
||||
## Installation
|
||||
|
||||
### Swift Package Manager
|
||||
|
||||
Add this package as a dependency in your `Package.swift`:
|
||||
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/yourusername/YAMLMerger", from: "1.0.0")
|
||||
]
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Add your license here.
|
||||
|
||||
65
Sources/YAMLMerger/YAMLMerger.swift
Normal file
65
Sources/YAMLMerger/YAMLMerger.swift
Normal file
@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
public struct YAMLMerger {
|
||||
public let rootDirectory: URL
|
||||
public let outputFileName: String
|
||||
|
||||
public init(rootDirectory: URL, outputFileName: String) {
|
||||
self.rootDirectory = rootDirectory
|
||||
self.outputFileName = outputFileName
|
||||
}
|
||||
|
||||
private func sortedYAMLFiles(in folder: URL) -> [URL] {
|
||||
let fileManager = FileManager.default
|
||||
guard let contents = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil) else {
|
||||
return []
|
||||
}
|
||||
return contents
|
||||
.filter { $0.pathExtension == "yaml" || $0.pathExtension == "yml" }
|
||||
.sorted { $0.lastPathComponent.lowercased() < $1.lastPathComponent.lowercased() }
|
||||
}
|
||||
|
||||
private func sortedSubfolders(in folder: URL) -> [URL] {
|
||||
let fileManager = FileManager.default
|
||||
guard let contents = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey]) else {
|
||||
return []
|
||||
}
|
||||
return contents
|
||||
.filter {
|
||||
var isDirectory: ObjCBool = false
|
||||
return fileManager.fileExists(atPath: $0.path, isDirectory: &isDirectory) && isDirectory.boolValue
|
||||
}
|
||||
.sorted { $0.lastPathComponent.lowercased() < $1.lastPathComponent.lowercased() }
|
||||
}
|
||||
|
||||
private func cleanedContent(_ text: String) -> String {
|
||||
let regex = try! NSRegularExpression(pattern: "(\\n\\s*){2,}", options: [])
|
||||
let range = NSRange(location: 0, length: text.utf16.count)
|
||||
return regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "\n\n")
|
||||
}
|
||||
|
||||
public func merge() {
|
||||
let outputFile = rootDirectory.appendingPathComponent(outputFileName)
|
||||
var output = ""
|
||||
|
||||
let folderURLs = sortedSubfolders(in: rootDirectory)
|
||||
|
||||
for folderURL in folderURLs {
|
||||
let yamlFiles = sortedYAMLFiles(in: folderURL)
|
||||
|
||||
var isFirstFile = true
|
||||
for fileURL in yamlFiles {
|
||||
guard let content = try? String(contentsOf: fileURL, encoding: .utf8) else { continue }
|
||||
if !isFirstFile {
|
||||
output += "\n" // only between files
|
||||
}
|
||||
output += content
|
||||
isFirstFile = false
|
||||
}
|
||||
}
|
||||
|
||||
try? output.write(to: outputFile, atomically: true, encoding: .utf8)
|
||||
print("✅ Combined YAML written to \(outputFile.path)")
|
||||
}
|
||||
}
|
||||
|
||||
0
Tests/YAMLMergerTests/Schema/.gitkeep
Normal file
0
Tests/YAMLMergerTests/Schema/.gitkeep
Normal file
0
Tests/YAMLMergerTests/Schema/01_Info/.gitkeep
Normal file
0
Tests/YAMLMergerTests/Schema/01_Info/.gitkeep
Normal file
5
Tests/YAMLMergerTests/Schema/01_Info/__info.yaml
Normal file
5
Tests/YAMLMergerTests/Schema/01_Info/__info.yaml
Normal file
@ -0,0 +1,5 @@
|
||||
openapi: 3.0.0
|
||||
info:
|
||||
|
||||
|
||||
|
||||
4
Tests/YAMLMergerTests/Schema/02_Servers/__servers.yaml
Normal file
4
Tests/YAMLMergerTests/Schema/02_Servers/__servers.yaml
Normal file
@ -0,0 +1,4 @@
|
||||
|
||||
servers:
|
||||
|
||||
|
||||
4
Tests/YAMLMergerTests/Schema/03_Tags/__tags.yaml
Normal file
4
Tests/YAMLMergerTests/Schema/03_Tags/__tags.yaml
Normal file
@ -0,0 +1,4 @@
|
||||
|
||||
tags:
|
||||
|
||||
|
||||
0
Tests/YAMLMergerTests/Schema/04_Paths/.gitkeep
Normal file
0
Tests/YAMLMergerTests/Schema/04_Paths/.gitkeep
Normal file
7
Tests/YAMLMergerTests/Schema/04_Paths/__paths.yaml
Normal file
7
Tests/YAMLMergerTests/Schema/04_Paths/__paths.yaml
Normal file
@ -0,0 +1,7 @@
|
||||
|
||||
paths:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
4
Tests/YAMLMergerTests/Schema/05_Webhooks/__webhooks.yaml
Normal file
4
Tests/YAMLMergerTests/Schema/05_Webhooks/__webhooks.yaml
Normal file
@ -0,0 +1,4 @@
|
||||
|
||||
webhooks:
|
||||
|
||||
|
||||
0
Tests/YAMLMergerTests/Schema/06_Components/.gitkeep
Normal file
0
Tests/YAMLMergerTests/Schema/06_Components/.gitkeep
Normal file
@ -0,0 +1,6 @@
|
||||
|
||||
schemas:
|
||||
|
||||
|
||||
|
||||
|
||||
@ -0,0 +1,6 @@
|
||||
|
||||
securitySchemes:
|
||||
|
||||
|
||||
|
||||
|
||||
@ -0,0 +1,4 @@
|
||||
|
||||
externalDocs:
|
||||
|
||||
|
||||
28
Tests/YAMLMergerTests/YAMLMergerTests.swift
Normal file
28
Tests/YAMLMergerTests/YAMLMergerTests.swift
Normal file
@ -0,0 +1,28 @@
|
||||
@testable import YAMLMerger
|
||||
import XCTest
|
||||
|
||||
final class YamlMergerTests: XCTestCase {
|
||||
func testMergeSchemaYAML() throws {
|
||||
|
||||
print("📂 CWD:", FileManager.default.currentDirectoryPath)
|
||||
|
||||
// Access the resource from the test bundle
|
||||
let bundle = Bundle.module
|
||||
guard let schemaFolder = bundle.url(forResource: "Schema", withExtension: nil) else {
|
||||
XCTFail("Failed to locate Schema folder in resources")
|
||||
return
|
||||
}
|
||||
|
||||
// Merge the files
|
||||
let merger = YAMLMerger(
|
||||
rootDirectory: schemaFolder,
|
||||
outputFileName: "CombinedSpec.yaml"
|
||||
)
|
||||
merger.merge()
|
||||
|
||||
// Optional: assert output file exists
|
||||
let outputURL = schemaFolder.appendingPathComponent("CombinedSpec.yaml")
|
||||
print("📂 CWD:", outputURL)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: outputURL.path))
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user