File: ManifestLoader%2BValidation.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 (344 lines) | stat: -rw-r--r-- 14,252 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 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 Basics
import Foundation
import PackageModel

public struct ManifestValidator {
    static var supportedLocalBinaryDependencyExtensions: [String] {
        ["zip"] + BinaryModule.Kind.allCases.filter{ $0 != .unknown }.map { $0.fileExtension }
    }
    static var supportedRemoteBinaryDependencyExtensions: [String] {
        ["zip", "artifactbundleindex"]
    }

    private let manifest: Manifest
    private let sourceControlValidator: ManifestSourceControlValidator
    private let fileSystem: FileSystem

    public init(manifest: Manifest, sourceControlValidator: ManifestSourceControlValidator, fileSystem: FileSystem) {
        self.manifest = manifest
        self.sourceControlValidator = sourceControlValidator
        self.fileSystem = fileSystem
    }

    /// Validate the provided manifest.
    public func validate() -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()

        diagnostics += self.validateTargets()
        diagnostics += self.validateProducts()
        diagnostics += self.validateDependencies()

        // Checks reserved for tools version 5.2 features
        if self.manifest.toolsVersion >= .v5_2 {
            diagnostics += self.validateTargetDependencyReferences()
            diagnostics += self.validateBinaryTargets()
        }

        return diagnostics
    }

    private func validateTargets() -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()

        let duplicateTargetNames = self.manifest.targets.map({ $0.name }).spm_findDuplicates()
        for name in duplicateTargetNames {
            diagnostics.append(.duplicateTargetName(targetName: name))
        }

        return diagnostics
    }

    private func validateProducts()  -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()
        
        for product in self.manifest.products {
            // Check that the product contains targets.
            guard !product.targets.isEmpty else {
                diagnostics.append(.emptyProductTargets(productName: product.name))
                continue
            }

            // Check that the product references existing targets.
            for target in product.targets {
                if !self.manifest.targetMap.keys.contains(target) {
                    diagnostics.append(.productTargetNotFound(productName: product.name, targetName: target, validTargets: self.manifest.targetMap.keys.sorted()))
                }
            }

            // Check that products that reference only binary targets don't define an explicit library type.
            if product.targets.allSatisfy({ self.manifest.targetMap[$0]?.type == .binary }) {
                switch product.type {
                case .library(.automatic), .executable:
                    break
                default:
                    diagnostics.append(.invalidBinaryProductType(productName: product.name))
                }
            }
        }

        return diagnostics
    }

    private func validateDependencies() -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()

        // validate dependency requirements
        for dependency in self.manifest.dependencies {
            switch dependency {
            case .sourceControl(let sourceControl):
                diagnostics += validateSourceControlDependency(sourceControl)
            default:
                break
            }
        }

        return diagnostics
    }

    private func validateBinaryTargets() -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()

        // Check that binary targets point to the right file type.
        for target in self.manifest.targets where target.type == .binary {
            if target.isLocal {
                guard let path = target.path else {
                    diagnostics.append(.invalidBinaryLocation(targetName: target.name))
                    continue
                }

                guard let path = path.spm_chuzzle(), !path.isEmpty else {
                    diagnostics.append(.invalidLocalBinaryPath(path: path, targetName: target.name))
                    continue
                }

                guard let relativePath = try? RelativePath(validating: path) else {
                    diagnostics.append(.invalidLocalBinaryPath(path: path, targetName: target.name))
                    continue
                }

                let validExtensions = Self.supportedLocalBinaryDependencyExtensions
                guard let fileExtension = relativePath.extension, validExtensions.contains(fileExtension) else {
                    diagnostics.append(.unsupportedBinaryLocationExtension(
                        targetName: target.name,
                        validExtensions: validExtensions
                    ))
                    continue
                }
            } else if target.isRemote {
                guard let url = target.url else {
                    diagnostics.append(.invalidBinaryLocation(targetName: target.name))
                    continue
                }

                guard let url = url.spm_chuzzle(), !url.isEmpty else {
                    diagnostics.append(.invalidBinaryURL(url: url, targetName: target.name))
                    continue
                }

                guard let url = URL(string: url) else {
                    diagnostics.append(.invalidBinaryURL(url: url, targetName: target.name))
                    continue
                }

                let validSchemes = ["https"]
                guard url.scheme.map({ validSchemes.contains($0) }) ?? false else {
                    diagnostics.append(.invalidBinaryURLScheme(
                        targetName: target.name,
                        validSchemes: validSchemes
                    ))
                    continue
                }

                guard Self.supportedRemoteBinaryDependencyExtensions.contains(url.pathExtension) else {
                    diagnostics.append(.unsupportedBinaryLocationExtension(
                        targetName: target.name,
                        validExtensions: Self.supportedRemoteBinaryDependencyExtensions
                    ))
                    continue
                }

            } else {
                diagnostics.append(.invalidBinaryLocation(targetName: target.name))
                continue
            }
        }

        return diagnostics
    }

    /// Validates that product target dependencies reference an existing package.
    private func validateTargetDependencyReferences() -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()

        for target in self.manifest.targets {
            for targetDependency in target.dependencies {
                switch targetDependency {
                case .target:
                    // If this is a target dependency, we don't need to check anything.
                    break
                case .product(_, let packageName, _, _):
                    if self.manifest.packageDependency(referencedBy: targetDependency) == nil {
                        diagnostics.append(.unknownTargetPackageDependency(
                            packageName: packageName,
                            targetName: target.name,
                            validPackages: self.manifest.dependencies
                        ))
                    }
                case .byName(let name, _):
                    // Don't diagnose root manifests so we can emit a better diagnostic during package loading.
                    if !self.manifest.packageKind.isRoot &&
                        !self.manifest.targetMap.keys.contains(name) &&
                        self.manifest.packageDependency(referencedBy: targetDependency) == nil
                    {
                        diagnostics.append(.unknownTargetDependency(
                            dependency: name,
                            targetName: target.name,
                            validDependencies: self.manifest.dependencies
                        ))
                    }
                }
            }
        }

        return diagnostics
    }

    func validateSourceControlDependency(_ dependency: PackageDependency.SourceControl) -> [Basics.Diagnostic] {
        var diagnostics = [Basics.Diagnostic]()
        // if a location is on file system, validate it is in fact a git repo
        // there is a case to be made to throw early (here) if the path does not exists
        // but many of our tests assume they can pass a non existent path
        if case .local(let localPath) = dependency.location, self.fileSystem.exists(localPath) {
            do {
                if try !self.sourceControlValidator.isValidDirectory(localPath) {
                    // Provides better feedback when mistakenly using url: for a dependency that
                    // is a local package. Still allows for using url with a local package that has
                    // also been initialized by git
                    diagnostics.append(.invalidSourceControlDirectory(localPath))
                }
            } catch {
                diagnostics.append(.invalidSourceControlDirectory(localPath, underlyingError: error))
            }
        }
        return diagnostics
    }
}

public protocol ManifestSourceControlValidator {
    func isValidDirectory(_ path: AbsolutePath) throws -> Bool
}

extension Basics.Diagnostic {
    static func duplicateTargetName(targetName: String) -> Self {
        .error("duplicate target named '\(targetName)'")
    }

    static func emptyProductTargets(productName: String) -> Self {
        .error("product '\(productName)' doesn't reference any targets")
    }

    static func productTargetNotFound(productName: String, targetName: String, validTargets: [String]) -> Self {
        .error("target '\(targetName)' referenced in product '\(productName)' could not be found; valid targets are: '\(validTargets.joined(separator: "', '"))'")
    }

    static func invalidBinaryProductType(productName: String) -> Self {
        .error("invalid type for binary product '\(productName)'; products referencing only binary targets must be executable or automatic library products")
    }

    static func unknownTargetDependency(dependency: String, targetName: String, validDependencies: [PackageDependency]) -> Self {

        .error("unknown dependency '\(dependency)' in target '\(targetName)'; valid dependencies are: \(validDependencies.map{ "\($0.descriptionForValidation)" }.joined(separator: ", "))")
    }

    static func unknownTargetPackageDependency(packageName: String?, targetName: String, validPackages: [PackageDependency]) -> Self {
        let messagePrefix: String
        if let packageName {
            messagePrefix = "unknown package '\(packageName)'"
        } else {
            messagePrefix = "undeclared package"
        }
        return .error("\(messagePrefix) in dependencies of target '\(targetName)'; valid packages are: \(validPackages.map{ "\($0.descriptionForValidation)" }.joined(separator: ", "))")
    }

    static func invalidBinaryLocation(targetName: String) -> Self {
        .error("invalid location for binary target '\(targetName)'")
    }

    static func invalidBinaryURL(url: String, targetName: String) -> Self {
        .error("invalid URL '\(url)' for binary target '\(targetName)'")
    }

    static func invalidLocalBinaryPath(path: String, targetName: String) -> Self {
        .error("invalid local path '\(path)' for binary target '\(targetName)', path expected to be relative to package root.")
    }

    static func invalidBinaryURLScheme(targetName: String, validSchemes: [String]) -> Self {
        .error("invalid URL scheme for binary target '\(targetName)'; valid schemes are: '\(validSchemes.joined(separator: "', '"))'")
    }

    static func unsupportedBinaryLocationExtension(targetName: String, validExtensions: [String]) -> Self {
        .error("unsupported extension for binary target '\(targetName)'; valid extensions are: '\(validExtensions.joined(separator: "', '"))'")
    }

    static func invalidLanguageTag(_ languageTag: String) -> Self {
        .error("""
            invalid language tag '\(languageTag)'; the pattern for language tags is groups of latin characters and \
            digits separated by hyphens
            """)
    }

    static func errorSuffix(_ error: Error?) -> String {
        if let error {
            return ": \(error.interpolationDescription)"
        } else {
            return ""
        }
    }

    static func invalidSourceControlDirectory(_ path: AbsolutePath, underlyingError: Error? = nil) -> Self {
        .error("cannot clone from local directory \(path)\nPlease git init or use \"path:\" for \(path)\(errorSuffix(underlyingError))")
    }
}

extension TargetDescription {
    fileprivate var isRemote: Bool { url != nil }
    fileprivate var isLocal: Bool { path != nil }
}

extension PackageDependency {
    fileprivate var descriptionForValidation: String {
        var description = "'\(self.nameForModuleDependencyResolutionOnly)'"

        if let locationsString = {
            switch self {
            case .fileSystem(let settings):
                return "at '\(settings.path.pathString)'"
            case .sourceControl(let settings):
                switch settings.location {
                case .local(let path):
                    return "at '\(path.pathString)'"
                case .remote(let url):
                    return "from '\(url.absoluteString)'"
                }
            case .registry:
                return .none
            }
        }() {
            description += " (\(locationsString))"
        }

        return description
    }
}