Skip to content

Commit b24e0c2

Browse files
committed
Migrate code to use Swift Regex
1 parent 09f1b22 commit b24e0c2

File tree

6 files changed

+37
-39
lines changed

6 files changed

+37
-39
lines changed

Sources/Build/BuildOperation.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import class TSCBasic.DiagnosticsEngine
2323
import protocol TSCBasic.OutputByteStream
2424
import class TSCBasic.Process
2525
import enum TSCBasic.ProcessEnv
26-
import struct TSCBasic.RegEx
2726

2827
import enum TSCUtility.Diagnostics
2928
import class TSCUtility.MultiLineNinjaProgressAnimation
@@ -690,7 +689,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS
690689
guard let _ = self._buildPlan?.targets.first(where: { $0.target.name == target }) else { return nil }
691690

692691
// Check for cases involving modules that cannot be found.
693-
if let importedModule = try? RegEx(pattern: "no such module '(.+)'").matchGroups(in: message).first?.first {
692+
if let importedModule = message.firstMatch(of: #/no such module '(?<module>.+)'/#)?.module {
694693
// A target is importing a module that can't be found. We take a look at the build plan and see if can offer any advice.
695694

696695
// Look for a target with the same module name as the one that's being imported.

Sources/Build/BuildOperationBuildSystemDelegateHandler.swift

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import struct TSCBasic.Format
2323
import class TSCBasic.LocalFileOutputByteStream
2424
import protocol TSCBasic.OutputByteStream
2525
import enum TSCBasic.ProcessEnv
26-
import struct TSCBasic.RegEx
2726
import class TSCBasic.ThreadSafeOutputByteStream
2827

2928
import class TSCUtility.IndexStore
@@ -933,11 +932,13 @@ final class BuildOperationBuildSystemDelegateHandler: LLBuildBuildSystemDelegate
933932
// next we want to try and scoop out any errors from the output (if reasonable size, otherwise this
934933
// will be very slow), so they can later be passed to the advice provider in case of failure.
935934
if output.utf8.count < 1024 * 10 {
936-
let regex = try! RegEx(pattern: #".*(error:[^\n]*)\n.*"#, options: .dotMatchesLineSeparators)
937-
for match in regex.matchGroups(in: output) {
938-
self.errorMessagesByTarget[parser.targetName] = (
939-
self.errorMessagesByTarget[parser.targetName] ?? []
940-
) + [match[0]]
935+
let regex = #/.*(?<error>error:[^\n]*)\n.*/#.dotMatchesNewlines()
936+
for match in output.matches(of: regex) {
937+
self
938+
.errorMessagesByTarget[parser.targetName] = (
939+
self
940+
.errorMessagesByTarget[parser.targetName] ?? []
941+
) + [String(match.error)]
941942
}
942943
}
943944
}

Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -252,23 +252,11 @@ struct GitHubPackageMetadataProvider: PackageMetadataProvider, Closable {
252252

253253
// FIXME: use URL instead of string
254254
internal static func apiURL(_ url: String) -> URL? {
255-
do {
256-
let regex = try NSRegularExpression(pattern: #"([^/@]+)[:/]([^:/]+)/([^/.]+)(\.git)?$"#, options: .caseInsensitive)
257-
if let match = regex.firstMatch(in: url, options: [], range: NSRange(location: 0, length: url.count)) {
258-
if let hostRange = Range(match.range(at: 1), in: url),
259-
let ownerRange = Range(match.range(at: 2), in: url),
260-
let repoRange = Range(match.range(at: 3), in: url) {
261-
let host = String(url[hostRange])
262-
let owner = String(url[ownerRange])
263-
let repo = String(url[repoRange])
264-
265-
return URL(string: "https://\(Self.apiHostPrefix)\(host)/repos/\(owner)/\(repo)")
266-
}
267-
}
268-
return nil
269-
} catch {
255+
let regex = #/(?<host>[^/@]+)[:/](?<owner>[^:/]+)/(?<repo>[^/.]+)(\.git)?$/#.ignoresCase()
256+
guard let match = url.firstMatch(of: regex) else {
270257
return nil
271258
}
259+
return URL(string: "https://\(Self.apiHostPrefix)\(match.host)/repos/\(match.owner)/\(match.repo)")
272260
}
273261

274262
private func makeRequestOptions(validResponseCodes: [Int]) -> LegacyHTTPClientRequest.Options {

Sources/PackageLoading/ToolsVersionParser.swift

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import Foundation
1515
import PackageModel
1616

1717
import struct TSCBasic.ByteString
18-
import struct TSCBasic.RegEx
1918

2019
import struct TSCUtility.Version
2120

@@ -621,19 +620,32 @@ extension ManifestLoader {
621620
do { contents = try fileSystem.getDirectoryContents(packagePath) } catch {
622621
throw ToolsVersionParser.Error.inaccessiblePackage(path: packagePath, reason: String(describing: error))
623622
}
624-
let regex = try! RegEx(pattern: #"^Package@swift-(\d+)(?:\.(\d+))?(?:\.(\d+))?.swift$"#)
625-
623+
let regex = #/^Package@swift-(?<major>\d+)(?<minor>:\.(\d+))?(?<patch>:\.(\d+))?.swift$/#
626624
// Collect all version-specific manifests at the given package path.
627625
let versionSpecificManifests = Dictionary(contents.compactMap{ file -> (ToolsVersion, String)? in
628-
let parsedVersion = regex.matchGroups(in: file)
629-
guard parsedVersion.count == 1, parsedVersion[0].count == 3 else {
626+
let parsedVersionMatches = file.matches(of: regex)
627+
guard parsedVersionMatches.count == 1,
628+
let parsedVersion = parsedVersionMatches.first else {
630629
return nil
631630
}
632-
633-
let major = Int(parsedVersion[0][0])!
634-
let minor = parsedVersion[0][1].isEmpty ? 0 : Int(parsedVersion[0][1])!
635-
let patch = parsedVersion[0][2].isEmpty ? 0 : Int(parsedVersion[0][2])!
636-
631+
// Most of case the transform will success since we are capturing digit.
632+
// But if the value exceed the representation of Int(Int64), it will fail to transform.
633+
// In such case, we'd like to fallback to zero instead of crash.
634+
//
635+
// We can also use RegexBuild and use transform in Capture to get Int type directly.
636+
let major = Int(parsedVersion.major) ?? 0
637+
let minor: Int
638+
if let minorString = parsedVersion.minor {
639+
minor = Int(minorString) ?? 0
640+
} else {
641+
minor = 0
642+
}
643+
let patch: Int
644+
if let patchString = parsedVersion.patch {
645+
patch = Int(patchString) ?? 0
646+
} else {
647+
patch = 0
648+
}
637649
return (ToolsVersion(version: Version(major, minor, patch)), file)
638650
}, uniquingKeysWith: { $1 })
639651

Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -433,9 +433,9 @@ enum PackageArchiveSigner {
433433
}
434434
manifests.append(Manifest.filename)
435435

436-
let regex = try RegEx(pattern: #"^Package@swift-(\d+)(?:\.(\d+))?(?:\.(\d+))?.swift$"#)
436+
let regex = #/^Package@swift-(\d+)(?:\.(\d+))?(?:\.(\d+))?.swift$/#
437437
let versionSpecificManifests: [String] = packageContents.filter { file in
438-
let matchGroups = regex.matchGroups(in: file)
438+
let matchGroups = file.matches(of: regex)
439439
return !matchGroups.isEmpty
440440
}
441441
manifests.append(contentsOf: versionSpecificManifests)

Sources/Workspace/PackageContainer/SourceControlPackageContainer.swift

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ import PackageLoading
1919
import PackageModel
2020
import SourceControl
2121

22-
import struct TSCBasic.RegEx
23-
2422
import enum TSCUtility.Git
2523
import struct TSCUtility.Version
2624

@@ -287,8 +285,8 @@ internal final class SourceControlPackageContainer: PackageContainer, CustomStri
287285
)
288286
} else {
289287
// Revision does not exist, so we customize the error.
290-
let sha1RegEx = try! RegEx(pattern: #"\A[:xdigit:]{40}\Z"#)
291-
let isBranchRev = sha1RegEx.matchGroups(in: revision).compactMap { $0 }.isEmpty
288+
let sha1RegEx = #/\A[:xdigit:]{40}\Z/#
289+
let isBranchRev = revision.matches(of: sha1RegEx).isEmpty
292290
let errorMessage = "could not find " + (isBranchRev ? "a branch named ‘\(revision)" : "the commit \(revision)")
293291
let mainBranchExists = (try? repository.resolveRevision(identifier: "main")) != nil
294292
let suggestion = (revision == "master" && mainBranchExists) ? "did you mean ‘main’?" : nil

0 commit comments

Comments
 (0)