Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions Sources/Package Manager/Package.Manifest.Clause.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
public import SPM_Standard

extension Package.Manifest {
/// A located `.package(...)` clause within manifest source: the exact text
/// it spans and the UTF-8 byte range it occupies.
///
/// Located by paren-matching over the **raw** manifest bytes, not by
/// re-serialising an evaluated manifest. The reversal a redirection owes is
/// *byte-identical* — the declared clause must be restored verbatim — so it
/// has to be captured verbatim, and only the original bytes are verbatim.
/// String-literal contents are skipped during the scan, so a parenthesis
/// inside a quoted URL or path cannot close the clause early.
///
/// The range is expressed in bytes rather than `String.Index` because every
/// delimiter this engine keys on — `.package(`, `(`, `)`, `"`, `\` — is
/// ASCII, so byte boundaries at those points never fall inside a multi-byte
/// UTF-8 scalar and slicing on them is exact. Working over `String.Index`
/// would pull in Foundation's `range(of:)`, which the layer forbids.
public struct Clause: Swift.Sendable, Swift.Equatable {
/// The exact source text of the clause, from `.package(` to its
/// matching `)`, inclusive.
public let text: Swift.String

/// The half-open UTF-8 byte range the clause occupies in its source.
public let range: Swift.Range<Swift.Int>
}
}

extension Package.Manifest.Clause {
/// Every `.package(...)` clause in `source`, in source order.
public static func all(in source: Swift.String) -> [Self] {
let bytes = [Swift.UInt8](source.utf8)
let marker = [Swift.UInt8](".package(".utf8)

var clauses: [Self] = []
var index = 0
while let start = firstIndex(of: marker, in: bytes, from: index) {
let openParen = start + marker.count
guard let close = closingParen(in: bytes, after: openParen) else {
// Unbalanced from here on; nothing further is a well-formed
// clause, so stop rather than ressynchronising on a guess.
break
}
let range = start..<(close + 1)
clauses.append(
.init(
text: Swift.String(decoding: bytes[range], as: Swift.UTF8.self),
range: range
)
)
index = close + 1
}
return clauses
}

/// The url-form clause whose declared URL has package identity `identity`,
/// or `nil` when the source declares no such dependency by URL.
///
/// Matched on derived identity, not on a literal URL comparison, so a
/// declaration that omits a trailing `.git` or differs in case still
/// matches — identity is exactly what SwiftPM keys a dependency on.
public static func url(
identity: Swift.String,
in source: Swift.String
) -> Self? {
all(in: source).first { clause in
guard let url = clause.declaredURL else { return false }
return Self.identity(ofURL: url) == identity
}
}

/// The declared URL of a url-form clause (`.package(url: "…", …)`), or
/// `nil` when the clause is not url-form.
public var declaredURL: Swift.String? {
Self.declaredURL(in: text)
}

/// The declared path of a path-form clause (`.package(path: "…")`), or
/// `nil` when the clause is not path-form.
public var declaredPath: Swift.String? {
Self.declaredPath(in: text)
}

/// The declared URL of a standalone url-form clause text.
///
/// The standalone form lets a persisted clause be re-parsed without
/// re-locating it in a manifest — a restore knows the exact clause text it
/// stored and needs the identity it carries, not a position.
public static func declaredURL(in text: Swift.String) -> Swift.String? {
quoted(after: "url:", in: text)
}

/// The declared path of a standalone path-form clause text.
public static func declaredPath(in text: Swift.String) -> Swift.String? {
quoted(after: "path:", in: text)
}

/// `source` with this clause's byte span replaced by `replacement`.
///
/// The clause carries a byte range into the exact `source` it was located
/// in; applying it to any other text is a programmer error the caller
/// prevents by re-locating against the text it edits.
public func replacing(
with replacement: Swift.String,
in source: Swift.String
) -> Swift.String {
let bytes = [Swift.UInt8](source.utf8)
var result = [Swift.UInt8]()
result.reserveCapacity(bytes.count)
result.append(contentsOf: bytes[bytes.startIndex..<range.lowerBound])
result.append(contentsOf: replacement.utf8)
result.append(contentsOf: bytes[range.upperBound..<bytes.endIndex])
return Swift.String(decoding: result, as: Swift.UTF8.self)
}

/// SwiftPM's package identity for a source-control URL: the last path
/// component, with a trailing slash and a trailing `.git` removed, folded
/// to lower case. This mirrors how SwiftPM derives identity from a git URL.
public static func identity(ofURL url: Swift.String) -> Swift.String {
var value = url[...]
while value.last == "/" { value = value.dropLast() }
if value.hasSuffix(".git") { value = value.dropLast(4) }
let component = value.split(separator: "/").last.map(Swift.String.init) ?? Swift.String(value)
return component.lowercased()
}
}

extension Package.Manifest.Clause {
/// The first quoted string literal that follows `label` in the clause text,
/// or `nil` when the label or a following literal is absent.
///
/// Escaped quotes are not interpreted: a URL or filesystem path carrying a
/// literal `"` is pathological here, and treating the first inner quote as
/// the terminator fails loudly rather than smuggling a wrong value through.
private static func quoted(after label: Swift.String, in text: Swift.String) -> Swift.String? {
let bytes = [Swift.UInt8](text.utf8)
let needle = [Swift.UInt8](label.utf8)
let located = firstIndex(of: needle, in: bytes, from: 0)
guard let labelStart = located else { return nil }

let quote = Swift.UInt8(ascii: "\"" as Swift.Unicode.Scalar)
var index = labelStart + needle.count
while index < bytes.count, bytes[index] != quote { index += 1 }
guard index < bytes.count else { return nil }
let open = index + 1
var close = open
while close < bytes.count, bytes[close] != quote { close += 1 }
guard close < bytes.count else { return nil }
return Swift.String(decoding: bytes[open..<close], as: Swift.UTF8.self)
}

/// The index of the `)` that closes the `.package(` whose `(` sits at
/// `start - 1`. Depth-counts parentheses and skips string-literal contents
/// so a paren inside a quoted URL or path cannot close the clause early.
/// `nil` when the parentheses never balance.
private static func closingParen(in bytes: [Swift.UInt8], after start: Swift.Int) -> Swift.Int? {
let quote = Swift.UInt8(ascii: "\"" as Swift.Unicode.Scalar)
let backslash = Swift.UInt8(ascii: "\\" as Swift.Unicode.Scalar)
let open = Swift.UInt8(ascii: "(" as Swift.Unicode.Scalar)
let close = Swift.UInt8(ascii: ")" as Swift.Unicode.Scalar)

var depth = 1
var index = start
var insideString = false
var escaped = false
while index < bytes.count {
let byte = bytes[index]
if insideString {
if escaped {
escaped = false
} else if byte == backslash {
escaped = true
} else if byte == quote {
insideString = false
}
} else {
switch byte {
case quote: insideString = true

case open: depth += 1

case close:
depth -= 1
if depth == 0 { return index }

default: break
}
}
index += 1
}
return nil
}

/// The index in `haystack` at or after `from` where `needle` first occurs,
/// or `nil`. A plain forward scan; manifests are small and this runs a
/// handful of times per operation.
private static func firstIndex(
of needle: [Swift.UInt8],
in haystack: [Swift.UInt8],
from: Swift.Int
) -> Swift.Int? {
guard !needle.isEmpty, haystack.count >= needle.count else { return nil }
var start = from
let last = haystack.count - needle.count
while start <= last {
var offset = 0
while offset < needle.count, haystack[start + offset] == needle[offset] {
offset += 1
}
if offset == needle.count { return start }
start += 1
}
return nil
}
}
16 changes: 16 additions & 0 deletions Sources/Package Manager/Package.Manifest.Redirection.Error.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
public import SPM_Standard

extension Package.Manifest.Redirection {
/// Why a redirection or its restore refused to rewrite the manifest.
public enum Error: Swift.Error, Swift.Sendable, Swift.Equatable {
/// No url-form `.package(url:)` clause in the source declares a
/// dependency with this SwiftPM package identity; there is nothing
/// to redirect.
case dependencyNotDeclaredByURL(identity: Swift.String)

/// The composed `.package(path:)` clause a prior redirect wrote is
/// not present in the source — it may have been hand-edited or
/// already restored. Refusing to guess beats a wrong rewrite.
case composedClauseAbsent(planned: Swift.String)
}
}
31 changes: 31 additions & 0 deletions Sources/Package Manager/Package.Manifest.Redirection.Rewrite.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
public import SPM_Standard

extension Package.Manifest.Redirection {
/// The result of one ``Package/Manifest/Redirection/redirect(_:dependency:to:)``:
/// the rewritten manifest source plus the exact clause texts a
/// byte-for-byte restore needs.
///
/// `declared` and `planned` are the reversal record. A caller that
/// persists them (in whatever ledger it owns) can restore the manifest
/// verbatim later with ``Package/Manifest/Redirection/restore(_:planned:declared:)``.
public struct Rewrite: Swift.Sendable, Swift.Equatable {
/// The manifest source with the url-form clause replaced by `planned`.
public let source: Swift.String

/// The url-form clause that was replaced, captured verbatim.
public let declared: Swift.String

/// The path-form clause that replaced it.
public let planned: Swift.String

public init(
source: Swift.String,
declared: Swift.String,
planned: Swift.String
) {
self.source = source
self.declared = declared
self.planned = planned
}
}
}
81 changes: 81 additions & 0 deletions Sources/Package Manager/Package.Manifest.Redirection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
public import SPM_Standard

extension Package.Manifest {
/// Redirecting a URL-declared dependency to a **local mutable source**
/// at an existing checkout, and undoing it byte-for-byte.
///
/// The mechanism is generated `.package(path:)` composition: the manifest's
/// url-form clause is rewritten in place to a path-form clause, and the
/// declared clause is captured **verbatim** so ``restore(_:planned:declared:)``
/// can return it byte-for-byte. A composed manifest therefore carries a
/// machine-local absolute path. That is a virtue, not a bug, as long as it
/// stays local — off-machine it fails *loudly* at resolution rather than
/// silently substituting a wrong source — but it means a composed manifest
/// must never be committed; callers own surfacing that warning.
///
/// This is a pure source-to-source transformation. Deciding *which* local
/// checkout a dependency redirects to — org layout, checkout discovery,
/// ledgering the reversal — stays with the caller.
public enum Redirection {}
}

extension Package.Manifest.Redirection {
/// Rewrites the url-form clause declaring `url` in `source` to a
/// `.package(path:)` clause pointing at `path`.
///
/// The clause is located by SwiftPM package identity derived from `url`
/// (see ``Package/Manifest/Clause/identity(ofURL:)``), so a declaration
/// that omits a trailing `.git` or differs in case still matches.
///
/// - Parameters:
/// - source: The consumer manifest source to rewrite.
/// - url: The dependency's declared source-control URL.
/// - path: The local checkout the dependency redirects to. Written into
/// the manifest exactly as given; pass an absolute path so a leaked
/// composed manifest fails loudly off-machine.
/// - Returns: The rewritten source together with the declared clause
/// captured verbatim and the planned clause that replaced it.
/// - Throws: ``Error/dependencyNotDeclaredByURL(identity:)`` when no
/// url-form clause in `source` declares the dependency.
public static func redirect(
_ source: Swift.String,
dependency url: Swift.String,
to path: Swift.String
) throws(Error) -> Rewrite {
let identity = Package.Manifest.Clause.identity(ofURL: url)
guard let clause = Package.Manifest.Clause.url(identity: identity, in: source) else {
throw .dependencyNotDeclaredByURL(identity: identity)
}
let planned = ".package(path: \"\(path)\")"
return Rewrite(
source: clause.replacing(with: planned, in: source),
declared: clause.text,
planned: planned
)
}

/// Restores `source` to its declared url-form clause **byte-for-byte**:
/// locates the clause whose text equals `planned` and replaces it with
/// `declared` verbatim.
///
/// - Parameters:
/// - source: The composed manifest source to restore.
/// - planned: The exact path-form clause a prior
/// ``redirect(_:dependency:to:)`` wrote.
/// - declared: The exact url-form clause it captured.
/// - Returns: The restored manifest source.
/// - Throws: ``Error/composedClauseAbsent(planned:)`` when `source` no
/// longer contains `planned` — it may have been hand-edited or already
/// restored, and guessing would be worse than refusing.
public static func restore(
_ source: Swift.String,
planned: Swift.String,
declared: Swift.String
) throws(Error) -> Swift.String {
let located = Package.Manifest.Clause.all(in: source).first { $0.text == planned }
guard let clause = located else {
throw .composedClauseAbsent(planned: planned)
}
return clause.replacing(with: declared, in: source)
}
}
Loading
Loading