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
80 changes: 80 additions & 0 deletions Snippets/EnvironmentValues/ReadingFileLocation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Read where a file is being written with `@FilePath`, `@FileURL`, `@EnclosingPath`, and `@EnclosingURL`.

// snippet.hide
import Calligraphy
import Foundation

// snippet.show
// snippet.path
struct GeneratedNotice: StringComponent {

@FilePath
private var path

@EnclosingPath
private var folder

var body: some StringComponent {
"// \(path ?? "unknown") is generated. Do not edit."
"// Sibling files live in \(folder ?? "unknown")/"
}

}

let sources = Folder("Sources") {
Folder("Models") {
File("User.swift") {
GeneratedNotice()
"struct User {}"
}
}
}
// Sources/Models/User.swift begins with:
// // Sources/Models/User.swift is generated. Do not edit.
// // Sibling files live in Sources/Models/
// snippet.end

// snippet.url
struct AbsoluteNotice: StringComponent {

@FileURL
private var url

var body: some StringComponent {
if let url {
"// Written to \(url.path(percentEncoded: false))"
} else {
"// Not written to disk"
}
}

}
// snippet.end

// snippet.enclosing
struct Manifest: Directory {

let name: String

@EnclosingPath
private var location

var body: some DirectoryContent {
File("MANIFEST.txt") {
"Contents of \(location ?? "")"
"- README.md"
}
File("README.md", text: "# \(name)")
}

}
// Manifest(name: "Docs") written at the top level produces Docs/MANIFEST.txt containing:
// Contents of Docs
// - README.md
// snippet.end

// snippet.hide
let destination = FileManager.default.temporaryDirectory
try await sources.write(to: destination, shouldOverwrite: true)
try await Manifest(name: "Docs").write(to: destination, shouldOverwrite: true)
print("Wrote to \(destination.path(percentEncoded: false))")
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,26 @@ The property wrapper works the same way in a ``DataComponent``, and in types tha

The property wrapper is populated by reflection on the enclosing type, so it only works as a stored property of a component. When you need an environment value somewhere else, such as a free `@StringBuilder` function or the ``Swift/String/init(builder:)`` initializer, move that piece of content into a small component type and read the value there, the same way you would introduce a `View` in SwiftUI.

## Reading the File Name
## Reading the File Location

``File``, ``TextFile``, and ``DataFile`` set the name of the file, including its extension, before rendering their contents. Read it with the ``FileName`` property wrapper from any string or data component inside a file, and adapt the output to where it is being written:

@Snippet(path: "Calligraphy/Snippets/EnvironmentValues/ReadingFileName", slice: "header")

The value is `nil` outside of any file, and on a file type itself, which already knows its own name.

To learn where a file sits in the tree, read ``FilePath``, which includes the names of every enclosing folder, or ``EnclosingPath``, which stops at the directory containing the file. Both are relative to the directory the content is written to:

@Snippet(path: "Calligraphy/Snippets/EnvironmentValues/ReadingFileLocation", slice: "path")

Pass ``PathResolution/absolute`` to either wrapper, or use ``FileURL`` and ``EnclosingURL``, to learn where the file lands on disk. Absolute locations are only known while content is being written with ``DirectoryContent/write(to:shouldOverwrite:)``, so they are `nil` when content is serialized without a destination:

@Snippet(path: "Calligraphy/Snippets/EnvironmentValues/ReadingFileLocation", slice: "url")

Inside the body of a ``Directory``, ``EnclosingPath`` and ``EnclosingURL`` describe that directory, so content can also adapt to the folder it is placed in:

@Snippet(path: "Calligraphy/Snippets/EnvironmentValues/ReadingFileLocation", slice: "enclosing")

## Writing Values

Use the ``StringComponent/environment(_:_:)-(_,Value)`` modifier to set an environment value on a component and its descendants. Ancestor components are unaffected. ``DataComponent`` and ``DirectoryContent`` have the same modifiers, so you can set a value once on a folder and have it reach every file inside:
Expand Down
5 changes: 5 additions & 0 deletions Sources/Calligraphy/Calligraphy.docc/Calligraphy.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,10 @@ Calligraphy's type-safe API and builder patterns make it ideal for code generati
- ``EnvironmentKey``
- ``Entry()``
- ``FileName``
- ``FilePath``
- ``FileURL``
- ``EnclosingPath``
- ``EnclosingURL``
- ``PathResolution``
- ``DynamicProperty``

4 changes: 3 additions & 1 deletion Sources/Calligraphy/DirectoryComposition/Directory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,13 @@ extension Directory {
in environment: EnvironmentValues
) -> [SerializedDirectoryContent] {
environment.inject(into: self)
var childEnvironment = environment
childEnvironment.enclosingDirectoryComponents.append(name)
return [
.directory(
name,
permissions: permissions,
content: body._serialize(in: environment)
content: body._serialize(in: childEnvironment)
)
]
}
Expand Down
26 changes: 16 additions & 10 deletions Sources/Calligraphy/DirectoryComposition/DirectoryContent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ extension DirectoryContent {
/// - shouldOverwrite: Whether or not existing content with the same name or structure should be overwritten with new content.
/// - Returns: A list of every file URL that was created during the process.
/// - Important: Sibling names are validated case-insensitively before anything is written. A tree containing both `README.md` and `readme.md` is rejected on every platform, because case-insensitive file systems such as APFS would treat them as the same file.
/// - Note: The destination is made available to the content while it renders, so ``FilePath``, ``FileURL``, ``EnclosingPath``, and ``EnclosingURL`` can resolve absolute locations.
@discardableResult
public func write(
to directoryURL: URL,
Expand All @@ -80,7 +81,9 @@ extension DirectoryContent {
isDirectory.boolValue else {
throw DiskOperationError("Provided URL does not point to a directory")
}
let contents = _serialize(in: EnvironmentValues())
var environment = EnvironmentValues()
environment.destinationDirectoryURL = directoryURL.standardizedFileURL
let contents = _serialize(in: environment)
try contents.validate(in: directoryURL)
return try await DiskOperation.start(with: directoryURL) {
try await contents.performWriteOperations(shouldOverwrite: shouldOverwrite)
Expand All @@ -93,6 +96,7 @@ extension DirectoryContent {
/// - shouldOverwrite: Whether or not existing content with the same name or structure should be overwritten with new content.
/// - Returns: A list of every file URL that was created during the process.
/// - Important: Sibling names are validated case-insensitively before anything is written. A tree containing both `README.md` and `readme.md` is rejected on every platform, because case-insensitive file systems such as APFS would treat them as the same file.
/// - Note: The destination is made available to the content while it renders, so ``FilePath``, ``FileURL``, ``EnclosingPath``, and ``EnclosingURL`` can resolve absolute locations.
@discardableResult
public nonisolated(nonsending) func write(
to directoryURL: URL,
Expand All @@ -106,7 +110,9 @@ extension DirectoryContent {
isDirectory.boolValue else {
throw DiskOperationError("Provided URL does not point to a directory")
}
let contents = _serialize(in: EnvironmentValues())
var environment = EnvironmentValues()
environment.destinationDirectoryURL = directoryURL.standardizedFileURL
let contents = _serialize(in: environment)
try contents.validate(in: directoryURL)
return try await DiskOperation.start(with: directoryURL) {
try await contents.performWriteOperations(shouldOverwrite: shouldOverwrite)
Expand Down Expand Up @@ -231,12 +237,12 @@ extension [SerializedDirectoryContent] {
let name = content.name

guard !name.isEmpty else {
throw DiskOperationError("Invalid directory content - empty name found in parent '\(parent.path())'")
throw DiskOperationError("Invalid directory content - empty name found in parent '\(parent.path(percentEncoded: false))'")
}

let illegalCharacters = CharacterSet(charactersIn: "/\\:?*\"<>|")
guard name.rangeOfCharacter(from: illegalCharacters) == nil else {
throw DiskOperationError("Invalid directory content - file or directory name '\(name)' contains illegal characters in parent '\(parent.path())'")
throw DiskOperationError("Invalid directory content - file or directory name '\(name)' contains illegal characters in parent '\(parent.path(percentEncoded: false))'")
}

#if os(Windows)
Expand All @@ -253,30 +259,30 @@ extension [SerializedDirectoryContent] {
guard !reservedNames.contains(stem.uppercased()) else {
throw DiskOperationError(
"""
Invalid directory content - file or directory name '\(name)' is a reserved name in parent '\(parent.path())'
Invalid directory content - file or directory name '\(name)' is a reserved name in parent '\(parent.path(percentEncoded: false))'
"""
)
}
guard !name.hasSuffix("."),
!name.hasSuffix(" ") else {
throw DiskOperationError(
"""
Invalid directory content - file or directory name '\(name)' ends with a period or space in parent '\(parent.path())'
Invalid directory content - file or directory name '\(name)' ends with a period or space in parent '\(parent.path(percentEncoded: false))'
"""
)
}
guard name.unicodeScalars.allSatisfy({ $0.value >= 32 }) else {
throw DiskOperationError(
"""
Invalid directory content - file or directory name '\(name)' contains control characters in parent '\(parent.path())'
Invalid directory content - file or directory name '\(name)' contains control characters in parent '\(parent.path(percentEncoded: false))'
"""
)
}
#endif

let caseFoldedName = name.lowercased()
guard !uniqueNames.contains(caseFoldedName) else {
throw DiskOperationError("Invalid directory content - duplicate file or directory name '\(name)' found in parent '\(parent.path())'. Names are compared case-insensitively because some file systems, such as APFS, do not distinguish between names that differ only by case.")
throw DiskOperationError("Invalid directory content - duplicate file or directory name '\(name)' found in parent '\(parent.path(percentEncoded: false))'. Names are compared case-insensitively because some file systems, such as APFS, do not distinguish between names that differ only by case.")
}
uniqueNames.insert(caseFoldedName)
try content.validate(in: parent)
Expand Down Expand Up @@ -474,7 +480,7 @@ extension FileManager {
if shouldOverwrite {
try FileManager.default.removeItem(at: url)
} else {
throw DiskOperationError("File or directory already exists at proposed path '\(url.path())'")
throw DiskOperationError("File or directory already exists at proposed path '\(url.path(percentEncoded: false))'")
}
}
}
Expand All @@ -486,7 +492,7 @@ extension FileManager {
#if !os(Windows)
try setAttributes(
[.posixPermissions: permissions.rawValue],
ofItemAtPath: url.path()
ofItemAtPath: url.path(percentEncoded: false)
)
#endif
}
Expand Down
69 changes: 69 additions & 0 deletions Sources/Calligraphy/Environment/EnclosingPath.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Calligraphy
// EnclosingPath.swift
//
// MIT License
//
// Copyright (c) 2026 Varun Santhanam
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
//
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Foundation

/// A property wrapper that reads the path of the directory enclosing the content currently being rendered.
///
/// Inside a file, this is the directory that contains the file. Inside the body of a ``Directory``, it is that directory. The relative path is measured from the directory the content is written to, and is empty at the top level, where the enclosing directory is the destination itself:
///
/// @Snippet(path: "Calligraphy/Snippets/EnvironmentValues/ReadingFileLocation", slice: "enclosing")
///
/// The value is `nil` for ``PathResolution/absolute`` when the content is serialized without a destination. Like ``FileName``, it describes where a directory's body is rendered, not the directory's own properties, which see their parent.
@available(macOS 14.0, macCatalyst 17.0, iOS 17.0, watchOS 10.0, tvOS 17.0, visionOS 1.0, *)
@propertyWrapper
public struct EnclosingPath: DynamicProperty {

// MARK: - Initializers

/// Read the path of the directory enclosing the content currently being rendered.
/// - Parameter resolution: Whether to read a path relative to the destination directory, or an absolute path on disk.
public init(
_ resolution: PathResolution = .relative
) {
self.resolution = resolution
}

// MARK: - Property Wrapper

/// The path of the enclosing directory, or `nil` when it cannot be determined.
public var wrappedValue: String? {
location.path(
to: enclosing,
resolution: resolution
)
}

// MARK: - Private

private let resolution: PathResolution

@Environment(\.enclosingDirectoryComponents)
private var enclosing

@FileLocationEnvironment
private var location

}
58 changes: 58 additions & 0 deletions Sources/Calligraphy/Environment/EnclosingURL.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Calligraphy
// EnclosingURL.swift
//
// MIT License
//
// Copyright (c) 2026 Varun Santhanam
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
//
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import Foundation

/// A property wrapper that reads the URL of the directory enclosing the content currently being rendered.
///
/// Inside a file, this is the directory that contains the file. Inside the body of a ``Directory``, it is that directory. The URL is absolute, so it is only available while content is being written with ``DirectoryContent/write(to:shouldOverwrite:)``, and is `nil` otherwise. Use ``EnclosingPath`` when a relative location is enough.
@available(macOS 14.0, macCatalyst 17.0, iOS 17.0, watchOS 10.0, tvOS 17.0, visionOS 1.0, *)
@propertyWrapper
public struct EnclosingURL: DynamicProperty {

// MARK: - Initializers

/// Read the URL of the directory enclosing the content currently being rendered.
public init() {}

// MARK: - Property Wrapper

/// The absolute file URL of the enclosing directory, or `nil` when it cannot be determined.
public var wrappedValue: URL? {
location.url(
to: enclosing,
isDirectory: true
)
}

// MARK: - Private

@Environment(\.enclosingDirectoryComponents)
private var enclosing

@FileLocationEnvironment
private var location

}
13 changes: 13 additions & 0 deletions Sources/Calligraphy/Environment/EnvironmentValues.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,16 @@ public struct EnvironmentValues: Sendable {
private var storage = [ObjectIdentifier: any Sendable]()

}

extension EnvironmentValues {

@Entry
var fileName: String?

@Entry
var enclosingDirectoryComponents: [String] = []

@Entry
var destinationDirectoryURL: URL?

}
Loading
Loading