diff --git a/.gitignore b/.gitignore index 330d167..4f20167 100644 --- a/.gitignore +++ b/.gitignore @@ -88,3 +88,4 @@ fastlane/test_output # https://github.com/johnno1962/injectionforxcode iOSInjectionProject/ +.DS_Store diff --git a/README.md b/README.md index aef0445..a7efd49 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ # Credits.rtf Command line tool to generate "Credits.rtf" (for About page) from xcodeproj + + + +## Usage + +```shell +OVERVIEW: A Swift command-line tool to generate Credits.rtf file + +USAGE: credits --output [--title-font-size ] [--font-size ] [--exclude ...] [--no-open ] + +ARGUMENTS: + Input file. Supports one of: + - .xcodeproj/.pbxproj file + - Project direcotry (contains .xcodeproj file) + - plain text file with Github repository URLs (one + per line) + +OPTIONS: + -o, --output The output file name. + -t, --title-font-size + Font size for the title. (default: 16) + -f, --font-size + Font size for the content. (default: 12) + -x, --exclude Ignored repositories by name, repeat for multiple. + -O, --no-open Don't automatically open the output file after + generation. (default: false) + -h, --help Show help information. +``` + diff --git a/credits.rtf.xcodeproj/project.pbxproj b/credits.rtf.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2be025b --- /dev/null +++ b/credits.rtf.xcodeproj/project.pbxproj @@ -0,0 +1,337 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + F711FB642B4FF61600C0E272 /* credits.swift in Sources */ = {isa = PBXBuildFile; fileRef = F711FB632B4FF61600C0E272 /* credits.swift */; }; + F7CCF04B2B55255C00A195D3 /* ArgumentParser in Frameworks */ = {isa = PBXBuildFile; productRef = F7CCF04A2B55255C00A195D3 /* ArgumentParser */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + F711FB5E2B4FF61600C0E272 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + F711FB602B4FF61600C0E272 /* credits */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = credits; sourceTree = BUILT_PRODUCTS_DIR; }; + F711FB632B4FF61600C0E272 /* credits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = credits.swift; sourceTree = ""; }; + F738F85B2B552EC200CA3590 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; + F738F85C2B552EC200CA3590 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + F711FB5D2B4FF61600C0E272 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F7CCF04B2B55255C00A195D3 /* ArgumentParser in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + F711FB572B4FF61600C0E272 = { + isa = PBXGroup; + children = ( + F738F85B2B552EC200CA3590 /* LICENSE */, + F738F85C2B552EC200CA3590 /* README.md */, + F711FB622B4FF61600C0E272 /* credits.rtf */, + F711FB612B4FF61600C0E272 /* Products */, + F7CCF0482B5524E300A195D3 /* Frameworks */, + ); + sourceTree = ""; + }; + F711FB612B4FF61600C0E272 /* Products */ = { + isa = PBXGroup; + children = ( + F711FB602B4FF61600C0E272 /* credits */, + ); + name = Products; + sourceTree = ""; + }; + F711FB622B4FF61600C0E272 /* credits.rtf */ = { + isa = PBXGroup; + children = ( + F711FB632B4FF61600C0E272 /* credits.swift */, + ); + path = credits.rtf; + sourceTree = ""; + }; + F7CCF0482B5524E300A195D3 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + F711FB5F2B4FF61600C0E272 /* credits */ = { + isa = PBXNativeTarget; + buildConfigurationList = F711FB672B4FF61600C0E272 /* Build configuration list for PBXNativeTarget "credits" */; + buildPhases = ( + F711FB5C2B4FF61600C0E272 /* Sources */, + F711FB5D2B4FF61600C0E272 /* Frameworks */, + F711FB5E2B4FF61600C0E272 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = credits; + packageProductDependencies = ( + F7CCF04A2B55255C00A195D3 /* ArgumentParser */, + ); + productName = credits.rtf; + productReference = F711FB602B4FF61600C0E272 /* credits */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + F711FB582B4FF61600C0E272 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1520; + LastUpgradeCheck = 1520; + TargetAttributes = { + F711FB5F2B4FF61600C0E272 = { + CreatedOnToolsVersion = 15.2; + }; + }; + }; + buildConfigurationList = F711FB5B2B4FF61600C0E272 /* Build configuration list for PBXProject "credits.rtf" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = F711FB572B4FF61600C0E272; + packageReferences = ( + F7CCF0492B55255C00A195D3 /* XCRemoteSwiftPackageReference "swift-argument-parser" */, + ); + productRefGroup = F711FB612B4FF61600C0E272 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + F711FB5F2B4FF61600C0E272 /* credits */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + F711FB5C2B4FF61600C0E272 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F711FB642B4FF61600C0E272 /* credits.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + F711FB652B4FF61600C0E272 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.2; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + F711FB662B4FF61600C0E272 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.2; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + F711FB682B4FF61600C0E272 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = K7AJ426GA6; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_BUNDLE_IDENTIFIER = credits.jiaanf.tech; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + F711FB692B4FF61600C0E272 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = K7AJ426GA6; + ENABLE_HARDENED_RUNTIME = YES; + PRODUCT_BUNDLE_IDENTIFIER = credits.jiaanf.tech; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + F711FB5B2B4FF61600C0E272 /* Build configuration list for PBXProject "credits.rtf" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F711FB652B4FF61600C0E272 /* Debug */, + F711FB662B4FF61600C0E272 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F711FB672B4FF61600C0E272 /* Build configuration list for PBXNativeTarget "credits" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F711FB682B4FF61600C0E272 /* Debug */, + F711FB692B4FF61600C0E272 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + F7CCF0492B55255C00A195D3 /* XCRemoteSwiftPackageReference "swift-argument-parser" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/apple/swift-argument-parser.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.3.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + F7CCF04A2B55255C00A195D3 /* ArgumentParser */ = { + isa = XCSwiftPackageProductDependency; + package = F7CCF0492B55255C00A195D3 /* XCRemoteSwiftPackageReference "swift-argument-parser" */; + productName = ArgumentParser; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = F711FB582B4FF61600C0E272 /* Project object */; +} diff --git a/credits.rtf.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/credits.rtf.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/credits.rtf.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..b1ff0a0 --- /dev/null +++ b/credits.rtf.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "swift-argument-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-argument-parser.git", + "state" : { + "revision" : "c8ed701b513cf5177118a175d85fbbbcd707ab41", + "version" : "1.3.0" + } + } + ], + "version" : 2 +} diff --git a/credits.rtf.xcodeproj/xcshareddata/xcschemes/credits.rtf.xcscheme b/credits.rtf.xcodeproj/xcshareddata/xcschemes/credits.rtf.xcscheme new file mode 100644 index 0000000..a619167 --- /dev/null +++ b/credits.rtf.xcodeproj/xcshareddata/xcschemes/credits.rtf.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/credits.rtf/credits.swift b/credits.rtf/credits.swift new file mode 100644 index 0000000..f802671 --- /dev/null +++ b/credits.rtf/credits.swift @@ -0,0 +1,250 @@ +// +// main.swift +// credits.rtf +// +// Created by Jiaan Fang on 2024/1/15. +// + +import AppKit +import ArgumentParser +import Foundation + +@main +struct Credits: ParsableCommand { + static var configuration = CommandConfiguration( + abstract: "A Swift command-line tool to generate Credits.rtf file" + ) + + @Argument( + help: """ + Input file. Supports one of: + - .xcodeproj/.pbxproj file + - Project direcotry (contains .xcodeproj file) + - plain text file with Github repository URLs (one per line) + """) + var input: String + + @Option(name: .shortAndLong, help: "The output file name.") + var output: String + + @Option( + name: [.customLong("title-font-size"), .customShort("t")], + help: "Font size for the title.") + var titleFontSize: Int = 16 + + @Option( + name: [.customLong("font-size"), .customShort("f")], + help: "Font size for the content.") + var fontSize: Int = 12 + + @Option( + name: [.customLong("exclude"), .customShort("x")], + help: "Ignored repositories by name, repeat for multiple.") + var excludes: [String] = [] + + + @Option( + name: [.customLong("no-open"), .customShort("O")], + help: "Don't automatically open the output file after generation." + ) + var automaticallyOpenDisabled: Bool = false + + + func run() throws { + let attributedString: NSMutableAttributedString = .init() + let extractedURLs = extractRepositoryURL(fromProjectFile: self.input) + print("Extracted \(extractedURLs.count) URLs") + + for repo in extractedURLs + { + if let repoURL = URL(string: repo), + let licenseFile = fetchLicenseContent(for: repoURL) + { + attributedString.append( + NSAttributedString( + string: repoURL.lastPathComponent + "\n", + attributes: [.font: NSFont.boldSystemFont(ofSize: CGFloat(self.titleFontSize))])) + attributedString.append( + NSAttributedString( + string: licenseFile + "\n\n", + attributes: [.font: NSFont.systemFont(ofSize: CGFloat(self.fontSize))])) + } + + } + let range = NSRange(location: 0, length: attributedString.length) + + if let rtfData = attributedString.rtf( + from: range, documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) + { + // 这里可以使用 rtfData,例如写入文件或进行其他操作 + do { + let url = URL(filePath: self.output) + try rtfData.write(to: url) + if !automaticallyOpenDisabled { + NSWorkspace.shared.open(url) + } + } catch { + print("Error wrting rtf file: \(error)") + } + } else { + print("Error converting to rtf.") + } + } + + + func extractRepositoryURL(fromProjectFile filePath: String) -> [String] { + + if isDir(path: filePath) { + if filePath.hasSuffix(".xcodeproj") { + // 如果是 .xcodeproj 文件,获取 project.pbxproj 文件的路径 + let projectFilePath = filePath + "/project.pbxproj" + return extractRepositoryURL(fromProjectFile: projectFilePath) + } else { + // 如果是项目文件夹,获取 .xcodeproj 文件的路径 + let enumerator = FileManager.default.enumerator( + atPath: filePath) + while let element = enumerator?.nextObject() as? String { + if !element.starts(with: ".") && element.hasSuffix(".xcodeproj") { + let projectFilePath = filePath + "/" + element + "/project.pbxproj" + return extractRepositoryURL(fromProjectFile: projectFilePath) + } + } + } + } + + if !filePath.hasSuffix(".pbxproj") { + print("ERROR: Invalid file type") + return extractRepositoryURL(fromPlainTextFile: filePath) + } + print(filePath) + var foundURLs = [String]() + + do { + let content = try String(contentsOfFile: filePath, encoding: .utf8) + + if let rangeStart = content.range( + of: "/* Begin XCRemoteSwiftPackageReference section */"), + let rangeEnd = content.range( + of: "/* End XCRemoteSwiftPackageReference section */", + range: rangeStart.upperBound.. [String] { + var foundURLs = [String]() + do { + let content = try String(contentsOfFile: filePath, encoding: .utf8) + let lines = content.components(separatedBy: .newlines) + for line in lines { + if line.contains("https://github.com") { + foundURLs.append(line) + } + } + } catch { + print("Error reading file: \(error)") + } + return foundURLs + } + + func isDir(path: String) -> Bool { + let fileManager = FileManager.default + var isDir: ObjCBool = false + if fileManager.fileExists(atPath: path, isDirectory: &isDir) { + if isDir.boolValue { + // 路径指向一个文件夹 + return true + } else { + // 路径指向一个文件 + return false + } + } else { + return false + } + } + + func fetchLicenseContent(for repositoryURL: URL) -> String? { + // 假设 GitHub URL 的格式是 https://github.com/[user]/[repo] + let repoName = repositoryURL.lastPathComponent + if excludes.contains(repoName) { + print("\(repoName):\tExcluded") + return nil + } + print("Fetching license for \(repoName)") + let pathComponents = repositoryURL.pathComponents + guard pathComponents.count >= 3 else { + print("\(repoName):\tERROR: Invalid GitHub URL") + return nil + } + + let user = pathComponents[1] + let repo = pathComponents[2].replacingOccurrences(of: ".git", with: "") + let branches = ["main", "master"] + let suffixes = ["", "txt", "md"] + + let licenseURLs = branches.flatMap { branch in + suffixes.map { suffix in + let urlString = "https://raw.githubusercontent.com/\(user)/\(repo)/\(branch)/LICENSE\(suffix.isEmpty ? "" : ".\(suffix)")" + return URL(string: urlString) + } + } + let semaphore = DispatchSemaphore(value: 0) + var licenseContent: String? + + for url in licenseURLs where url != nil { + print("\(repoName):\ttrying \(url!.relativeString)") + + URLSession.shared.dataTask(with: url!) { data, response, error in + defer { semaphore.signal() } // 在任务完成时发送信号 + + if let error = error { + print("\(repoName):\tERROR: \(error)") + return + } + + if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, + let data = data + { + licenseContent = String(data: data, encoding: .utf8) + } + }.resume() + + semaphore.wait() + + if licenseContent != nil { + break + } + } + if licenseContent == nil || (licenseContent?.count ?? 0) == 0 { + print("\(repoName):\tERROR: License fetch failed") + } else { + print("\(repoName):\tLicense fetched, length \(licenseContent?.count ?? 0)") + } + + return licenseContent + } + + + +}