Skip to content

Commit 0126f9e

Browse files
committed
Created Scripts/PackageTargetsParser.swift
1 parent 532759b commit 0126f9e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Scripts/PackageTargetsParser.swift

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
//
2+
// PackageTargetsParser.swift
3+
// GitHubRestAPISwiftOpenAPI
4+
//
5+
// Created by zwc on 2025/5/11.
6+
//
7+
8+
import Foundation
9+
10+
struct ErrorMessage: LocalizedError {
11+
var message: String
12+
var errorDescription: String? { message }
13+
init(message: String, line: Int = #line) {
14+
self.message = "\(line): \(message)"
15+
}
16+
}
17+
18+
/// A struct that parses a JSON file containing a "tags" array, extracting the "name" field from each element.
19+
struct PackageTargetsParser {
20+
21+
/// Parses the provided JSON file and extracts the "name" values from the "tags" array.
22+
///
23+
/// - Parameter path: The path to the JSON file to be parsed.
24+
/// - Returns: An array of strings representing the "name" values found in the "tags" array.
25+
/// - Throws: An error if the file cannot be read or the JSON structure is invalid.
26+
///
27+
/// Example:
28+
///
29+
/// Given a JSON file:
30+
/// ```json
31+
/// {
32+
/// "tags": [
33+
/// { "name": "user" },
34+
/// { "name": "admin" },
35+
/// { "name": "billing" }
36+
/// ]
37+
/// }
38+
/// ```
39+
/// The function will return:
40+
/// ```swift
41+
/// ["user", "admin", "billing"]
42+
/// ```
43+
func parse(from path: String) throws -> [String] {
44+
let data = try Data(contentsOf: URL(fileURLWithPath: path))
45+
let json = try JSONSerialization.jsonObject(with: data, options: [])
46+
if let dict = json as? [String: Any], let tags = dict["tags"] as? [[String: Any]] {
47+
return tags.compactMap { $0["name"] as? String }
48+
} else {
49+
throw ErrorMessage(message: "Properties not found.")
50+
}
51+
}
52+
}
53+
54+
if let argPath = CommandLine.arguments[1]
55+
.split(whereSeparator: \.isNewline)
56+
.first {
57+
let path = String(argPath)
58+
let names = try PackageTargetsParser().parse(from: path)
59+
print(names.joined(separator: "\n"))
60+
} else {
61+
throw ErrorMessage(message: "PackageTargetsParser.parse(from:) failure")
62+
}
63+
64+

0 commit comments

Comments
 (0)