File: InitAction.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (188 lines) | stat: -rw-r--r-- 7,622 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2024 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import Foundation
import SwiftDocC

/// An action that generates a documentation catalog from a template seed.
public struct InitAction: Action {
    
    enum Error: DescribedError {
        case catalogAlreadyExists
        var errorDescription: String {
            switch self {
                case .catalogAlreadyExists: return "A documentation catalog with the same name already exists in the output directory."
            }
        }
    }
    
    private var fileManager: FileManagerProtocol
    private let catalogOutputURL: URL
    private let catalogTemplateKind: CatalogTemplateKind
    private let documentationTitle: String
    
    /// Creates a new Init action from the given parameters.
    ///
    /// - Parameters:
    ///     - catalogOutputDirectory: The URL to the directory where the catalog will be stored.
    ///     - documentationTitle: The title of the used for the top-level root file.
    ///     - catalogTemplate: The template used to initialize the catalog.
    ///     - fileManager: A file persistence manager.
    init(
        catalogOutputDirectory: URL,
        documentationTitle: String,
        catalogTemplate: CatalogTemplateKind,
        fileManager: FileManagerProtocol
    ) throws {
        self.catalogOutputURL = catalogOutputDirectory
        self.documentationTitle = documentationTitle
        self.catalogTemplateKind = catalogTemplate
        self.fileManager = fileManager
    }
    
    /// Creates a new Init action from the given parameters.
    ///
    /// - Parameters:
    ///     - catalogOutputDirectory: The URL to the directory where the catalog will be stored.
    ///     - documentationTitle: The title of the used for the top-level root file.
    ///     - catalogTemplate: The template used to initialize the catalog.
    public init(
        catalogOutputDirectory: URL,
        documentationTitle: String,
        catalogTemplate: CatalogTemplateKind
    ) throws {
        // Note: This public initializer recalls the internal initializer
        // and exists separately because the FileManagerProtocol type
        // we use to enable mocking in tests is internal to this framework.
        try self.init(
            catalogOutputDirectory: catalogOutputDirectory.appendingPathComponent("\(documentationTitle).docc"),
            documentationTitle: documentationTitle,
            catalogTemplate: catalogTemplate,
            fileManager: FileManager.default
        )
    }
    
    /// Generates a documentation catalog from a catalog template.
    ///
    /// - Parameter logHandle: The file handle that the convert and preview actions will print debug messages to.
    public mutating func perform(logHandle: SwiftDocC.LogHandle) throws -> ActionResult {
        
        let diagnosticEngine: DiagnosticEngine = DiagnosticEngine(treatWarningsAsErrors: false)
        diagnosticEngine.filterLevel = .warning
        diagnosticEngine.add(DiagnosticConsoleWriter(formattingOptions: []))
        var logHandle = logHandle
        var directoryURLsList = [URL]()
        var resourceDocumentationLink: String {
            switch catalogTemplateKind {
            case .articleOnly:
                return "https://www.swift.org/documentation/docc/"
            case .tutorial:
                return "https://www.swift.org/documentation/docc/tutorial-syntax"
            }
        }
        
        defer {
            diagnosticEngine.flush()
        }
        
        do {
            // Create the directory where the catalog will be initialized.
            try fileManager.createDirectory(
                at: catalogOutputURL,
                withIntermediateDirectories: false,
                attributes: nil
            )
        } catch CocoaError.fileWriteFileExists {
            diagnosticEngine.emit(
                Problem(
                    diagnostic: Diagnostic(
                        severity: .error,
                        identifier: "org.swift.DocumentationCatalogAlreadyExists",
                        summary: Error.catalogAlreadyExists.errorDescription
                    )
                )
            )
            return ActionResult(
                didEncounterError: !diagnosticEngine.problems.isEmpty,
                outputs: []
            )
        }
        
        do {
            // Create a catalog template using the options passed through the CLI.
            let catalogTemplate = try CatalogTemplate(catalogTemplateKind, title: documentationTitle)
            // Store the catalog on disk.
            for (relativePath, content) in catalogTemplate.files {
                // Generate the directories for file storage
                // by adding the article path to the output URL and
                // excluding the file name.
                let fileURL = catalogOutputURL.appendingPathComponent(relativePath)
                try fileManager.createDirectory(
                    at: fileURL.deletingLastPathComponent(),
                    withIntermediateDirectories: true,
                    attributes: nil
                )
                // Generate the article file at the specified URL path.
                try fileManager.createFile(at: fileURL, contents: Data(content.utf8))
                directoryURLsList.append(fileURL.relative(to: catalogOutputURL)!)
            }
            // Write additional directiories defined in the catalog.
            // Ex. `Resources`
            for relativePath in catalogTemplate.additionalDirectories {
                let directoryURL = catalogOutputURL.appendingPathComponent(relativePath)
                try fileManager.createDirectory(
                    at: directoryURL,
                    withIntermediateDirectories: true,
                    attributes: nil
                )
                directoryURLsList.append(directoryURL.relative(to: catalogOutputURL)!)
            }
            print(
                """
                A new documentation catalog has been generated at \(catalogOutputURL.path) with the following structure:
                
                \(directoryURLsList.map {
                    """
                    - \($0)
                    """
                }.joined(separator: "\n"))
                
                To preview it, run the command:
                    docc preview \(catalogOutputURL.path)
                
                For additional resources on how to get started with DocC, please refer to \(resourceDocumentationLink).
                """,
                to: &logHandle
            )
        } catch {
            // If an error occurs, delete the generated output.
            if fileManager.fileExists(atPath: catalogOutputURL.path) {
                try fileManager.removeItem(at: catalogOutputURL)
            }
            diagnosticEngine.emit(
                Problem(
                    diagnostic: Diagnostic(
                        severity: .error,
                        identifier: "org.swift.InitActionUnexpectedError",
                        summary: error.localizedDescription
                    )
                )
            )
        }
        
        return ActionResult(
            didEncounterError: !diagnosticEngine.problems.isEmpty,
            outputs: [catalogOutputURL]
        )
    }
    
}