File: SwiftRunCommand.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 (323 lines) | stat: -rw-r--r-- 13,027 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2015-2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import ArgumentParser
import Basics
import CoreCommands
import Foundation
import PackageGraph
import PackageModel

import enum TSCBasic.ProcessEnv
import func TSCBasic.exec

import enum TSCUtility.Diagnostics

/// An enumeration of the errors that can be generated by the run tool.
private enum RunError: Swift.Error {
    /// The package manifest has no executable product.
    case noExecutableFound

    /// Could not find a specific executable in the package manifest.
    case executableNotFound(String)

    /// There are multiple executables and one must be chosen.
    case multipleExecutables([String])
}

extension RunError: CustomStringConvertible {
    var description: String {
        switch self {
        case .noExecutableFound:
            return "no executable product available"
        case .executableNotFound(let executable):
            return "no executable product named '\(executable)'"
        case .multipleExecutables(let executables):
            let joinedExecutables = executables.joined(separator: ", ")
            return "multiple executable products available: \(joinedExecutables)"
        }
    }
}

struct RunCommandOptions: ParsableArguments {
    enum RunMode: EnumerableFlag {
        case repl
        case debugger
        case run

        static func help(for value: RunCommandOptions.RunMode) -> ArgumentHelp? {
            switch value {
            case .repl:
                return "Launch Swift REPL for the package"
            case .debugger:
                return "Launch the executable in a debugger session"
            case .run:
                return "Launch the executable with the provided arguments"
            }
        }
    }

    /// The mode in with the tool command should run.
    @Flag var mode: RunMode = .run

    /// If the executable product should be built before running.
    @Flag(name: .customLong("skip-build"), help: "Skip building the executable product")
    var shouldSkipBuild: Bool = false

    var shouldBuild: Bool { !shouldSkipBuild }

    /// If the test should be built.
    @Flag(name: .customLong("build-tests"), help: "Build both source and test targets")
    var shouldBuildTests: Bool = false

    /// The executable product to run.
    @Argument(help: "The executable to run", completion: .shellCommand("swift package completion-tool list-executables"))
    var executable: String?

    /// The arguments to pass to the executable.
    @Argument(parsing: .captureForPassthrough,
              help: "The arguments to pass to the executable")
    var arguments: [String] = []
}

/// swift-run command namespace
public struct SwiftRunCommand: AsyncSwiftCommand {
    public static var configuration = CommandConfiguration(
        commandName: "run",
        _superCommandName: "swift",
        abstract: "Build and run an executable product",
        discussion: "SEE ALSO: swift build, swift package, swift test",
        version: SwiftVersion.current.completeDisplayString,
        helpNames: [.short, .long, .customLong("help", withSingleDash: true)])

    @OptionGroup()
    public var globalOptions: GlobalOptions

    @OptionGroup()
    var options: RunCommandOptions

    public var toolWorkspaceConfiguration: ToolWorkspaceConfiguration {
        return .init(wantsREPLProduct: options.mode == .repl)
    }

    public func run(_ swiftCommandState: SwiftCommandState) async throws {
        if options.shouldBuildTests && options.shouldSkipBuild {
            swiftCommandState.observabilityScope.emit(
              .mutuallyExclusiveArgumentsError(arguments: ["--build-tests", "--skip-build"])
            )
            throw ExitCode.failure
        }

        switch options.mode {
        case .repl:
            // Load a custom package graph which has a special product for REPL.
            let graphLoader = {
                try swiftCommandState.loadPackageGraph(
                    explicitProduct: self.options.executable
                )
            }

            // Construct the build operation.
            // FIXME: We need to implement the build tool invocation closure here so that build tool plugins work with the REPL. rdar://86112934
            let buildSystem = try swiftCommandState.createBuildSystem(
                explicitBuildSystem: .native,
                cacheBuildManifest: false,
                packageGraphLoader: graphLoader
            )

            // Perform build.
            try buildSystem.build()

            // Execute the REPL.
            let arguments = try buildSystem.buildPlan.createREPLArguments()
            print("Launching Swift REPL with arguments: \(arguments.joined(separator: " "))")
            try self.run(
                fileSystem: swiftCommandState.fileSystem,
                executablePath: swiftCommandState.getTargetToolchain().swiftInterpreterPath,
                originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,
                arguments: arguments
            )

        case .debugger:
            do {
                let buildSystem = try swiftCommandState.createBuildSystem(explicitProduct: options.executable)
                let productName = try findProductName(in: buildSystem.getPackageGraph())
                if options.shouldBuildTests {
                    try buildSystem.build(subset: .allIncludingTests)
                } else if options.shouldBuild {
                    try buildSystem.build(subset: .product(productName))
                }

                let executablePath = try swiftCommandState.productsBuildParameters.buildPath.appending(component: productName)

                // Make sure we are running from the original working directory.
                let cwd: AbsolutePath? = swiftCommandState.fileSystem.currentWorkingDirectory
                if cwd == nil || swiftCommandState.originalWorkingDirectory != cwd {
                    try ProcessEnv.chdir(swiftCommandState.originalWorkingDirectory)
                }

                let pathRelativeToWorkingDirectory = executablePath.relative(to: swiftCommandState.originalWorkingDirectory)
                let lldbPath = try swiftCommandState.getTargetToolchain().getLLDB()
                try exec(path: lldbPath.pathString, args: ["--", pathRelativeToWorkingDirectory.pathString] + options.arguments)
            } catch let error as RunError {
                swiftCommandState.observabilityScope.emit(error)
                throw ExitCode.failure
            }

        case .run:
            // Detect deprecated uses of swift run to interpret scripts.
            if let executable = options.executable, try isValidSwiftFilePath(fileSystem: swiftCommandState.fileSystem, path: executable) {
                swiftCommandState.observabilityScope.emit(.runFileDeprecation)
                // Redirect execution to the toolchain's swift executable.
                let swiftInterpreterPath = try swiftCommandState.getTargetToolchain().swiftInterpreterPath
                // Prepend the script to interpret to the arguments.
                let arguments = [executable] + options.arguments
                try self.run(
                    fileSystem: swiftCommandState.fileSystem,
                    executablePath: swiftInterpreterPath,
                    originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,
                    arguments: arguments
                )
                return
            }

            do {
                let buildSystem = try swiftCommandState.createBuildSystem(explicitProduct: options.executable)
                let productName = try findProductName(in: buildSystem.getPackageGraph())
                if options.shouldBuildTests {
                    try buildSystem.build(subset: .allIncludingTests)
                } else if options.shouldBuild {
                    try buildSystem.build(subset: .product(productName))
                }

                let executablePath = try swiftCommandState.productsBuildParameters.buildPath.appending(component: productName)
                try self.run(
                    fileSystem: swiftCommandState.fileSystem,
                    executablePath: executablePath,
                    originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,
                    arguments: options.arguments
                )
            } catch Diagnostics.fatalError {
                throw ExitCode.failure
            } catch let error as RunError {
                swiftCommandState.observabilityScope.emit(error)
                throw ExitCode.failure
            }
        }
    }

    /// Returns the path to the correct executable based on options.
    private func findProductName(in graph: ModulesGraph) throws -> String {
        if let executable = options.executable {
            // There should be only one product with the given name in the graph
            // and it should be executable or snippet.
            guard let product = graph.product(for: executable, destination: .destination),
                  product.type == .executable || product.type == .snippet
            else {
                throw RunError.executableNotFound(executable)
            }
            return executable
        }

        // If the executable is implicit, search through root products.
        let rootExecutables = graph.rootPackages
            .flatMap { $0.products }
            .filter { $0.type == .executable || $0.type == .snippet }
            .map { $0.name }

        // Error out if the package contains no executables.
        guard rootExecutables.count > 0 else {
            throw RunError.noExecutableFound
        }

        // Only implicitly deduce the executable if it is the only one.
        guard rootExecutables.count == 1 else {
            throw RunError.multipleExecutables(rootExecutables)
        }

        return rootExecutables[0]
    }

    /// Executes the executable at the specified path.
    private func run(
        fileSystem: FileSystem,
        executablePath: AbsolutePath,
        originalWorkingDirectory: AbsolutePath,
        arguments: [String]) throws
    {
        // Make sure we are running from the original working directory.
        let cwd: AbsolutePath? = fileSystem.currentWorkingDirectory
        if cwd == nil || originalWorkingDirectory != cwd {
            try ProcessEnv.chdir(originalWorkingDirectory)
        }

        let pathRelativeToWorkingDirectory = executablePath.relative(to: originalWorkingDirectory)
        try execute(path: executablePath.pathString, args: [pathRelativeToWorkingDirectory.pathString] + arguments)
    }

    /// Determines if a path points to a valid swift file.
    private func isValidSwiftFilePath(fileSystem: FileSystem, path: String) throws -> Bool {
        guard path.hasSuffix(".swift") else { return false }
        //FIXME: Return false when the path is not a valid path string.
        let absolutePath: AbsolutePath
        if path.first == "/" {
            do {
                absolutePath = try AbsolutePath(validating: path)
            } catch {
                return false
            }
        } else {
            guard let cwd = fileSystem.currentWorkingDirectory else {
                return false
            }
            absolutePath = try AbsolutePath(cwd, validating: path)
        }
        return fileSystem.isFile(absolutePath)
    }

    /// A safe wrapper of TSCBasic.exec.
    private func execute(path: String, args: [String]) throws -> Never {
        #if !os(Windows)
        // Dispatch will disable almost all asynchronous signals on its worker threads, and this is called from `async`
        // context. To correctly `exec` a freshly built binary, we will need to:
        // 1. reset the signal masks
        for i in 1..<NSIG {
            signal(i, SIG_DFL)
        }
        var sig_set_all = sigset_t()
        sigfillset(&sig_set_all)
        sigprocmask(SIG_UNBLOCK, &sig_set_all, nil)

        #if os(Android)
        let number_fds = Int32(sysconf(_SC_OPEN_MAX))
        #else
        let number_fds = getdtablesize()
        #endif
        
        // 2. close all file descriptors.
        for i in 3..<number_fds {
            close(i)
        }
        #endif

        try TSCBasic.exec(path: path, args: args)
    }

    public init() {}
}

private extension Basics.Diagnostic {
    static var runFileDeprecation: Self {
        .warning("'swift run file.swift' command to interpret swift files is deprecated; use 'swift file.swift' instead")
    }
}