-
Notifications
You must be signed in to change notification settings - Fork 53
/
SwiftDocCPreview.swift
182 lines (152 loc) · 7.5 KB
/
SwiftDocCPreview.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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
#if os(Windows)
import WinSDK
#endif
import Foundation
import PackagePlugin
/// Creates and previews a Swift-DocC documentation archive from a Swift Package.
@main struct SwiftDocCPreview: CommandPlugin {
func performCommand(context: PluginContext, arguments: [String]) throws {
// We'll be creating commands that invoke `docc`, so start by locating it.
let doccExecutableURL = try context.doccExecutable
var argumentExtractor = ArgumentExtractor(arguments)
let specifiedTargets = try argumentExtractor.extractSpecifiedTargets(in: context.package)
let possibleTargets: [SwiftSourceModuleTarget]
if specifiedTargets.isEmpty {
possibleTargets = context.package.topLevelDocumentableTargets
} else {
possibleTargets = specifiedTargets
}
let verbose = argumentExtractor.extractFlag(named: "verbose") > 0
// Parse the given command-line arguments
let parsedArguments = ParsedArguments(argumentExtractor.remainingArguments)
// If the `--help` or `-h` flag was passed, print the plugin's help information
// and exit.
guard !parsedArguments.help else {
let helpInfo = try HelpInformation.forAction(.preview, doccExecutableURL: doccExecutableURL)
print(helpInfo)
return
}
// Confirm that at least one compatible target was provided.
guard let target = possibleTargets.first else {
Diagnostics.error("""
None of the provided targets produce Swift-DocC documentation.
Swift-DocC can produce documentation for Swift library and executable targets.
"""
)
return
}
// Swift-DocC is only able to preview a single target at a time.
guard possibleTargets.count == 1 else {
Diagnostics.error("""
Multiple targets found that can produce Swift-DocC documentation.
Swift-DocC is only able to preview a single target at a time. If your
package contains more than one documentable target, you must specify which
target should be previewed with the --target option.
Compatible targets: \(context.package.compatibleTargets).
"""
)
return
}
#if swift(>=5.7)
let snippetExtractTool = try context.tool(named: "snippet-extract")
let snippetExtractor = SnippetExtractor(
snippetTool: URL(fileURLWithPath: snippetExtractTool.path.string, isDirectory: false),
workingDirectory: URL(fileURLWithPath: context.pluginWorkDirectory.string, isDirectory: true)
)
#else
let snippetExtractor: SnippetExtractor? = nil
#endif
let symbolGraphs = try packageManager.doccSymbolGraphs(
for: target,
context: context,
verbose: verbose,
snippetExtractor: snippetExtractor,
customSymbolGraphOptions: parsedArguments.symbolGraphArguments
)
if try FileManager.default.contentsOfDirectory(atPath: symbolGraphs.targetSymbolGraphsDirectory.path).isEmpty {
// This target did not produce any symbol graphs. Let's check if it has a
// DocC catalog.
guard target.doccCatalogPath != nil else {
let message = """
'\(target.name)' does not contain any documentable symbols or a \
DocC catalog and will not produce documentation
"""
Diagnostics.error(message)
return
}
}
// Use the parsed arguments gathered earlier to generate the necessary
// arguments to pass to `docc`. ParsedArguments will merge the flags provided
// by the user with default fallback values for required flags that were not
// provided.
let doccArguments = parsedArguments.doccArguments(
action: .preview,
targetKind: target.kind == .executable ? .executable : .library,
doccCatalogPath: target.doccCatalogPath,
targetName: target.name,
symbolGraphDirectoryPath: symbolGraphs.unifiedSymbolGraphsDirectory.path,
outputPath: target.doccArchiveOutputPath(in: context)
)
if verbose {
let arguments = doccArguments.joined(separator: " ")
print("docc invocation: '\(doccExecutableURL.path) \(arguments)'")
}
// Configure the `docc preview` process with the generated arguments
let previewProcess = Process()
previewProcess.executableURL = doccExecutableURL
previewProcess.arguments = doccArguments
func stopPreviewProcess() {
#if os(macOS) && os(iOS) && os(tvOS) && os(watchOS)
previewProcess.interrupt()
#elseif os(Windows)
_ = TerminateProcess(previewProcess.processHandle, 0)
#else
// On non-Darwin systems, `docc` doesn't properly exit with just an interrupt signal
// so send a SIGKILL instead.
kill(previewProcess.processIdentifier, SIGKILL)
#endif
}
// Monitor for a termination signal and pass any along to the child `docc` preview
// process.
//
// Since Foundation's process does *not* create new processes with the same group ID
// as the parent process, we don't expect this to happen automatically.
signal(SIGTERM, SIG_IGN)
let terminateSignalSource = DispatchSource.makeSignalSource(signal: SIGTERM)
terminateSignalSource.setEventHandler {
terminateSignalSource.cancel()
stopPreviewProcess()
}
terminateSignalSource.resume()
// Monitor for an interrupt signal and pass any along to the child `docc` preview
// process
signal(SIGINT, SIG_IGN)
let interruptSignalSource = DispatchSource.makeSignalSource(signal: SIGINT)
interruptSignalSource.setEventHandler {
interruptSignalSource.cancel()
stopPreviewProcess()
}
interruptSignalSource.resume()
// Run the docc preview process and wait until it exits.
try previewProcess.run()
previewProcess.waitUntilExit()
// Check whether the `docc preview` invocation was successful.
guard previewProcess.terminationReason == .exit && previewProcess.terminationStatus == 0 else {
Diagnostics.error("""
'docc preview' invocation failed with a nonzero exit code: '\(previewProcess.terminationStatus)'.
Note: The Swift-DocC Preview plugin requires passing the '--disable-sandbox' flag
to the Swift Package Manager because it requires local network access to
run a local web server. See 'swift package plugin preview-documentation --help' for details.
"""
)
return
}
}
}