Compare commits

..

76 Commits

Author SHA1 Message Date
Bartosz Polaczyk 2f10c6a3a0 Merge pull request #185 from polac24/bartosz/20230306-watch-library
Support universal binary framework
2023-03-08 15:21:10 -05:00
Bartosz Polaczyk c7cd649aab Fix formatting 2023-03-08 06:02:24 -05:00
Bartosz Polaczyk 8201f7778b Fix for static frameworks 2023-03-08 05:33:39 -05:00
Bartosz Polaczyk 504393c3e3 Bundle optional private.swiftinterface 2023-03-08 05:29:02 -05:00
Aleksander Grzyb 82334dda04 Merge pull request #181 from polac24/lddplus-automatic
Add LDPLUSPLUS in automatic integration mode
2023-01-09 09:24:34 +01:00
Bartosz Polaczyk 1072979479 Fix formatting 2023-01-08 10:14:38 -08:00
Bartosz Polaczyk d741b3f6df Add unit tests 2023-01-08 09:59:44 -08:00
Bartosz Polaczyk a0f20b4da3 Add LDPLUSPLUS in automatic mode 2023-01-08 09:53:03 -08:00
Aleksander Grzyb f325b74796 Merge pull request #177 from polac24/pch-c-header
Compile locally PCH for c-header
2023-01-06 06:40:12 +01:00
Aleksander Grzyb a50eae615c Merge pull request #178 from polac24/xcode-1420
Switch to Xcode 14.2
2023-01-02 10:46:23 +01:00
Bartosz Polaczyk 3c8f062e95 Remove whitespaces 2022-12-30 10:59:16 -08:00
Bartosz Polaczyk 1cf685e197 Switch to Xcode 14.2 2022-12-30 10:57:49 -08:00
Bartosz Polaczyk d2ba874079 Compile locally PCH for c-header 2022-12-30 10:52:11 -08:00
Bartosz Polaczyk b439674378 Merge pull request #164 from polac24/20220831-optional-public-headers-folder
Make PUBLIC_HEADERS_FOLDER_PATH ENV optional
2022-11-24 05:27:57 +01:00
Bartosz Polaczyk de066f2b1c Merge pull request #175 from polac24/polac24-private-swiftinterface
Add SPI files: private.swiftinterface and abi.json
2022-11-18 15:47:03 +01:00
Bartosz Polaczyk 73d7a13246 Fix linter issue 2022-11-14 20:27:45 -08:00
Bartosz Polaczyk 75fdd27a5f Add unit tests for SPI changes in Xcode14 2022-11-14 20:00:18 -08:00
Bartosz Polaczyk 2fa1f4e927 Update SwiftmoduleFileExtension.swift 2022-11-14 06:34:45 +01:00
Bartosz Polaczyk 0a64893489 Bundle optional private.swiftinterface 2022-11-14 06:28:10 +01:00
Vadim Smal 56850cf2b0 Merge pull request #167 from CognitiveDisson/catalog-info
Add spotify OSS maintainer metadata
2022-09-01 15:56:55 +01:00
Vadim Smal cef92d2f0b Add spotify OSS maintainer metadata 2022-09-01 12:23:49 +01:00
Bartosz Polaczyk b1507b6e60 Fix linting 2022-08-31 13:42:30 +02:00
Bartosz Polaczyk c76c8a7672 Make PUBLIC_HEADERS_FOLDER_PATH optional 2022-08-31 13:22:13 +02:00
Bartosz Polaczyk 816a9c07c3 Merge pull request #149 from polac24/20220606-publish-swifth-md5
Support exposing enums from ObjC via Bridging headers
2022-08-25 09:53:50 +02:00
Vadim Smal 1e741bc859 Merge pull request #159 from polac24/update-docs-readme
Update Docs link in Readme
2022-08-24 11:13:35 +01:00
Vadim Smal 398b9b11e4 Merge pull request #161 from CognitiveDisson/features/add-retry-logic-for-download
Add retry logic for download
2022-08-24 09:26:18 +01:00
Vadim Smal cb76934ca2 Add retry logic for download 2022-08-11 18:06:20 +01:00
Bartosz Polaczyk aa92805e14 Update Docs link in Readme 2022-08-02 20:22:15 +02:00
Vadim Smal d6355074b2 Merge pull request #158 from CognitiveDisson/maxConcurrentRequests
Add upload_batch_size
2022-08-02 13:59:00 +01:00
Vadim Smal 070e671ddb Merge pull request #156 from polac24/20220711-fix-incremental
[CocoaPodsPlugin] Regenerate cached projects when XCRC is finally on
2022-07-31 21:25:52 +01:00
Vadim Smal 4efdbabf3e Check retryDelay and uploadBatchSize reading from rcinfo 2022-07-20 12:54:51 +01:00
Vadim Smal f33819da60 Rename max_concurrent_requests to upload_batch_size 2022-07-19 17:58:47 +01:00
Vadim Smal f16e6b06f3 Add maxConcurrentRequests 2022-07-19 10:22:09 +01:00
Vadim Smal 25ff5a790b Merge pull request #157 from CognitiveDisson/addUploadRetryDelay
Add a delay between network request retries
2022-07-15 18:38:20 +01:00
Vadim Smal f446f6061d Fix config read 2022-07-15 18:01:22 +01:00
Bartosz Polaczyk 4262620c57 Update Sources/XCRemoteCache/Artifacts/ArtifactProcessor.swift
Co-authored-by: PatrikBillgren <PatrikBillgren@users.noreply.github.com>
2022-07-15 16:03:54 +02:00
Vadim Smal b46d1e2ca1 Fixed retryDelay decoding 2022-07-14 18:06:35 +01:00
Vadim Smal 88d0666da9 Fix swiftlint violations 2022-07-14 17:44:31 +01:00
Vadim Smal 08bf5c21bf Update documentation 2022-07-14 17:38:48 +01:00
Vadim Smal be97a6a247 Fix swiftlint violations 2022-07-14 17:37:46 +01:00
Vadim Smal dff71f8070 Add a delay between upload retries 2022-07-14 16:59:40 +01:00
Bartosz Polaczyk 36fc5ae1e4 Bump plugin version 2022-07-11 22:49:13 +02:00
Bartosz Polaczyk 2d7c881b3b Do not skip install cache invalidation in consumer 2022-07-11 22:48:45 +02:00
Bartosz Polaczyk aed4a124cd [CocoaPodsPlugin] Regenerate cached projects when XCRC is finally enabled 2022-07-11 21:10:57 +02:00
Vadim Smal cda5fc1188 Add a delay between upload retries 2022-07-11 17:21:51 +01:00
Bartosz Polaczyk 2a5c6edfce More cleanup 2022-06-20 21:28:17 +02:00
Bartosz Polaczyk 7a1703e70f Pre-review cleanup 2022-06-20 21:24:47 +02:00
Bartosz Polaczyk 15586755d2 Merge pull request #152 from polac24/xcode14-fallback
Xcode 14.0 support
2022-06-20 09:29:41 +02:00
Bartosz Polaczyk e978eb182c Add limitation 2022-06-18 17:51:54 +02:00
Bartosz Polaczyk 7e98cebdd9 Merge remote-tracking branch 'upstream/master' into xcode14-fallback 2022-06-18 17:48:18 +02:00
Bartosz Polaczyk fbc2982aa3 [Xcode 14.0] Disable Swift integration driver 2022-06-18 17:43:33 +02:00
Bartosz Polaczyk cbcc028cad Merge pull request #151 from ainopara/fix/denpendency-writer-white-space
Escape white space in denpendency writer
2022-06-14 15:25:57 +02:00
ainopara 2acf97eca1 Fix lint issue 2022-06-14 13:37:33 +08:00
ainopara 40803cf747 Add unit test 2022-06-13 14:45:15 +08:00
ainopara 97496ed7b8 Escape white space in denpendency writer 2022-06-13 01:35:15 +08:00
Bartosz Polaczyk 45222f8e33 Merge pull request #150 from jarbogast-salesforce/cplusplus-support
Support C++ Linker
2022-06-11 22:26:58 +02:00
Jonathan Arbogast 91b5b5e590 Support C++ Linker 2022-06-11 15:07:30 -04:00
Bartosz Polaczyk 8222478817 Delete previous -Swift.h.md5 2022-06-07 08:53:53 -04:00
Bartosz Polaczyk 7a1b5267bf Merge remote-tracking branch 'upstream/master' into 20220606-publish-swifth-md5 2022-06-07 08:52:44 -04:00
Bartosz Polaczyk 2bd50e1c19 Delete old override for .h 2022-06-07 08:49:17 -04:00
Bartosz Polaczyk f2a7880c24 Merge pull request #148 from polac24/20220606-integrate-postbuild
Place postbuild build phase right after compilation
2022-06-07 07:29:14 -04:00
Bartosz Polaczyk 00cb8cc23d Merge pull request #147 from polac24/20220606-bridging-headers-enum-test
Add E2E test for exposing public enums from ObjC to Swift
2022-06-07 07:28:56 -04:00
Bartosz Polaczyk 6d0fd51c8e Add docs 2022-06-06 18:15:58 -04:00
Bartosz Polaczyk 65a16d0964 Use -Swift.h.md5 placeholder if available 2022-06-06 18:02:47 -04:00
Bartosz Polaczyk a152d9b159 Add support for generating md5 for -Swift.h 2022-06-06 18:01:27 -04:00
Bartosz Polaczyk a3cd6bea07 Add postbuild right after compilation for CocoaPods 2022-06-06 17:53:11 -04:00
Bartosz Polaczyk 86c762b070 Add postbuild right after compilation for integrate 2022-06-06 17:49:44 -04:00
Bartosz Polaczyk bd21156695 Add E2E test for exposing public enums from ObjC to Swift 2022-06-06 17:34:14 -04:00
Bartosz Polaczyk 3a82ad91b2 Merge pull request #144 from devMEremenko/fix-caching-in-env-fingerprint-generator
Fixed caching in `generatedFingerprint` in `EnvironmentFingerprintGenerator`
2022-06-02 23:03:38 +02:00
Maxim Eremenko 5a5bf35c4a Clean up 2022-06-02 22:46:10 +03:00
Maxim Eremenko 1f766ad4a4 Fixed SwiftLint in EnvironmentFingerprintGeneratorTests 2022-06-02 22:34:23 +03:00
Maxim Eremenko 3c3cd84d81 Fixed swiftlint issues 2022-06-02 22:23:42 +03:00
Maxim Eremenko 7728733aef Cached generatedFingerprint in EnvironmentFingerprintGenerator 2022-06-02 21:06:41 +03:00
Bartosz Polaczyk 50580bf9fd Merge pull request #139 from samuelsainz/feature/postbuild-dependencies-reader-perf-improvement
Improved DependenciesReader performance (~10x faster)
2022-05-24 17:40:21 +02:00
Samuel Sainz ceaff318d6 Fixed SwiftLint issues and CR improvements 2022-05-24 11:09:18 -03:00
Samuel Sainz 4cc932a592 Improved Dependencies Reader performance to be 10x faster 2022-05-23 15:31:41 -03:00
100 changed files with 3944 additions and 201 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
macOS:
runs-on: macos-12
env:
XCODE_VERSION: ${{ '13.3.1' }}
XCODE_VERSION: ${{ '14.2' }}
steps:
- name: Select Xcode
run: "sudo xcode-select -s /Applications/Xcode_$XCODE_VERSION.app"
+1 -1
View File
@@ -9,7 +9,7 @@ jobs:
docs:
runs-on: macos-12
env:
XCODE_VERSION: ${{ '13.3.1' }}
XCODE_VERSION: ${{ '14.2' }}
steps:
- uses: actions/checkout@v2
- name: Select Xcode
+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
name: Add macOS binaries to release
runs-on: macos-12
env:
XCODE_VERSION: ${{ '13.3.1' }}
XCODE_VERSION: ${{ '14.2' }}
steps:
- name: Select Xcode
run: "sudo xcode-select -s /Applications/Xcode_$XCODE_VERSION.app"
+1
View File
@@ -64,6 +64,7 @@ excluded:
- fastlane/
- DerivedData/
- e2eTests/XCRemoteCacheSample/Pods
- e2eTests/StandaloneSampleApp
attributes:
always_on_same_line:
+14 -2
View File
@@ -33,9 +33,13 @@ let package = Package(
dependencies: ["XCRemoteCache"]
),
.target(
name: "xclibtool",
name: "xclibtoolSupport",
dependencies: ["XCRemoteCache"]
),
.target(
name: "xclibtool",
dependencies: ["XCRemoteCache", "xclibtoolSupport"]
),
.target(
name: "xcpostbuild",
dependencies: ["XCRemoteCache"]
@@ -51,15 +55,23 @@ let package = Package(
name: "xcld",
dependencies: ["XCRemoteCache"]
),
.target(
name: "xcldplusplus",
dependencies: ["XCRemoteCache"]
),
.target(
// Wrapper target that builds all binaries but does nothing in runtime
name: "Aggregator",
dependencies: ["xcprebuild", "xcswiftc", "xclibtool", "xcpostbuild", "xcprepare", "xcld"]
dependencies: ["xcprebuild", "xcswiftc", "xclibtool", "xcpostbuild", "xcprepare", "xcld", "xcldplusplus"]
),
.testTarget(
name: "XCRemoteCacheTests",
dependencies: ["XCRemoteCache"],
resources: [.copy("TestData")]
),
.testTarget(
name: "xclibtoolSupportTests",
dependencies: ["xclibtoolSupport"]
),
]
)
+42 -2
View File
@@ -8,7 +8,7 @@ _XCRemoteCache is a remote cache tool for Xcode projects. It reuses target artif
[![Build Status](https://github.com/spotify/XCRemoteCache/workflows/CI/badge.svg)](https://github.com/spotify/XCRemoteCache/workflows/CI/badge.svg)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Slack](https://slackin.spotify.com/badge.svg)](https://slackin.spotify.com)
[![Docs](https://spotify.github.io/XCRemoteCache/documentation/xcremotecache/)](https://github.com/spotify/XCRemoteCache/workflows/Docs/badge.svg)
[![Docs](https://github.com/spotify/XCRemoteCache/workflows/Docs/badge.svg)](https://spotify.github.io/XCRemoteCache/documentation/xcremotecache/)
- [How and Why?](#how-and-why)
* [Accurate target input files](#accurate-target-input-files)
@@ -196,7 +196,9 @@ Configure Xcode targets that **should use** XCRemoteCache:
* `SWIFT_EXEC` - location of `xcprepare` (e.g. `xcremotecache/xcswiftc`)
* `LIBTOOL` - location of `xclibtool` (e.g. `xcremotecache/xclibtool`)
* `LD` - location of `xcld` (e.g. `xcremotecache/xcld`)
* `LDPLUSPLUS` - location of `xcldplusplus` (e.g. `xcremotecache/xcldplusplus`)
* `XCRC_PLATFORM_PREFERRED_ARCH` - `$(LINK_FILE_LIST_$(CURRENT_VARIANT)_$(PLATFORM_PREFERRED_ARCH):dir:standardizepath:file:default=arm64)`
* `SWIFT_USE_INTEGRATED_DRIVER` - `NO` (required in Xcode 14.0+)
<details>
<summary>Screenshot</summary>
@@ -265,7 +267,42 @@ $ xcremotecache/xcprepare mark --configuration Debug --platform iphonesimulator
That command creates an empty file on a remote server which informs that for given sha, configuration, platform, Xcode versions etc. all artifacts are available.
_Note that for the `producer` mode, the prebuild build phase and `xccc`, `xcld`, `xclibtool` wrappers become no-op, so it is recommended to not add them for the `producer` mode._
_Note that for the `producer` mode, the prebuild build phase and `xccc`, `xcld`, `xcldplusplus`, `xclibtool` wrappers become no-op, so it is recommended to not add them for the `producer` mode._
##### 7. Generalize `-Swift.h` (Optional only if using static library with a bridging header with public `NS_ENUM` exposed from ObjC)
If a static library target contains a mixed target with a bridging header exposing an enum from ObjC in a public Swift API, your custom script that moves `*-Swift.h` to the shared location, it should also move `*-Swift.h.md5` next to it.
Example:
##### Existing script (Before):
```shell
ditto "${SCRIPT_INPUT_FILE_0}" "${SCRIPT_OUTPUT_FILE_0}"
```
where
* `SCRIPT_INPUT_FILE_0="$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"`
* `SCRIPT_OUTPUT_FILE_0="$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"`
##### Correct script (After):
```shell
ditto "${SCRIPT_INPUT_FILE_0}" "${SCRIPT_OUTPUT_FILE_0}"
[ -f "${SCRIPT_INPUT_FILE_1}" ] && ditto "${SCRIPT_INPUT_FILE_1}" "${SCRIPT_OUTPUT_FILE_1}" || rm "${SCRIPT_OUTPUT_FILE_1}"
```
where
* `SCRIPT_INPUT_FILE_0="$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"`
* `SCRIPT_INPUT_FILE_1="$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME).md5"`
* `SCRIPT_OUTPUT_FILE_0="$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"`
* `SCRIPT_OUTPUT_FILE_1="$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME).md5"`
Note: This step is not required if at least one of these is true:
* you build a framework (not a static library)
* you don't expose `NS_ENUM` type from ObjC to Swift via a bridging header
## A full list of configuration parameters:
@@ -296,6 +333,8 @@ _Note that for the `producer` mode, the prebuild build phase and `xccc`, `xcld`,
| `stats_dir` | Directory where all XCRemoteCache statistics (e.g. counters) are stored | `~/.xccache` | ⬜️ |
| `download_retries` | Number of retries for download requests | `0` | ⬜️ |
| `upload_retries` | Number of retries for upload requests | `3` | ⬜️ |
| `retry_delay` | Delay between retries in seconds | `10` | ⬜️ |
| `upload_batch_size` | Maximum number of simultaneous requests. 0 means no limits | `0` | ⬜️ |
| `request_custom_headers` | Dictionary of extra HTTP headers for all remote server requests | `[]` | ⬜️ |
| `thin_target_mock_filename` | Filename (without an extension) of the compilation input file that is used as a fake compilation for the forced-cached target (aka thin target) | `standin` | ⬜️ |
| `focused_targets` | A list of all targets that are not thinned. If empty, all targets are meant to be non-thin | `[]` | ⬜️ |
@@ -416,6 +455,7 @@ Note: This setup is not recommended and may not be supported in future XCRemoteC
* Swift Package Manager (SPM) dependencies are not supported. _Because SPM does not allow customizing Build Settings, XCRemoteCache cannot specify `clang` and `swiftc` wrappers that control if the local compilation should be skipped (cache hit) or not (cache miss)_
* Filenames with `_vers.c` suffix are reserved and cannot be used as a source file
* All compilation files should be referenced via the git repo root. Referencing `/AbsolutePath/someOther.swift` or `../../someOther.swift` that resolve to the location outside of the git repo root is prohibited.
* The new Swift driver (introduced by default in Xcode 14.0) is not supported and has to be disabled when using XCRemoteCache
## FAQ
+17 -1
View File
@@ -10,7 +10,7 @@ DERIVED_DATA_DIR = File.join('.build').freeze
RELEASES_ROOT_DIR = File.join('releases').freeze
EXECUTABLE_NAME = 'XCRemoteCache'
EXECUTABLE_NAMES = ['xclibtool', 'xcpostbuild', 'xcprebuild', 'xcprepare', 'xcswiftc', 'xcld']
EXECUTABLE_NAMES = ['xclibtool', 'xcpostbuild', 'xcprebuild', 'xcprepare', 'xcswiftc', 'xcld', 'xcldplusplus']
PROJECT_NAME = 'XCRemoteCache'
SWIFTLINT_ENABLED = true
@@ -72,6 +72,22 @@ task :build, [:configuration, :arch, :sdks, :is_archive] do |task, args|
end
end
desc 'Build release artifacts'
task :prepare_release do
system("rm -rf releases && rm -rf tmp")
Rake::Task['build'].invoke("release", "x86_64-apple-macosx")
system("mkdir -p tmp && unzip releases/XCRemoteCache.zip -d tmp/xcremotecache-x86_64")
system("rm -rf releases")
Rake::Task['build'].invoke("release", "arm64-apple-macosx")
system("rake 'build[release, arm64-apple-macosx]'")
system("mkdir -p tmp && unzip releases/XCRemoteCache.zip -d tmp/xcremotecache-arm64")
system("rm -rf releases")
system("mkdir -p releases && zip -jr releases/XCRemoteCache-macOS-x86_64.zip LICENSE README.md tmp/xcremotecache-x86_64")
system("zip -jr releases/XCRemoteCache-macOS-arm64.zip LICENSE README.md tmp/xcremotecache-arm64")
system("mkdir -p tmp/xcremotecache && ls tmp/xcremotecache-x86_64 | xargs -I {} lipo -create -output tmp/xcremotecache/{} tmp/xcremotecache-x86_64/{} tmp/xcremotecache-arm64/{}")
system("zip -jr releases/XCRemoteCache-macOS-arm64-x86_64.zip LICENSE README.md tmp/xcremotecache")
end
desc 'run tests with SPM'
task :test do
# Running tests
@@ -42,6 +42,7 @@ class BuildArtifactCreator: ArtifactSwiftProductsBuilderImpl, ArtifactCreator {
private let modulesFolderPath: String
private let dSYMPath: URL
private let metaWriter: MetaWriter
private let artifactProcessor: ArtifactProcessor
private let fileManager: FileManager
init(
@@ -52,6 +53,7 @@ class BuildArtifactCreator: ArtifactSwiftProductsBuilderImpl, ArtifactCreator {
modulesFolderPath: String,
dSYMPath: URL,
metaWriter: MetaWriter,
artifactProcessor: ArtifactProcessor,
fileManager: FileManager
) {
self.buildDir = buildDir
@@ -62,6 +64,7 @@ class BuildArtifactCreator: ArtifactSwiftProductsBuilderImpl, ArtifactCreator {
self.fileManager = fileManager
self.dSYMPath = dSYMPath
self.metaWriter = metaWriter
self.artifactProcessor = artifactProcessor
super.init(workingDir: tempDir, moduleName: moduleName, fileManager: fileManager)
}
@@ -87,6 +90,7 @@ class BuildArtifactCreator: ArtifactSwiftProductsBuilderImpl, ArtifactCreator {
/// - Parameter tempDir: Temp location to organize file hierarchy in the artifact
/// - returns: URLs to include into the artifact package
fileprivate func prepareSwiftArtifacts(tempDir: URL) throws -> [URL] {
try artifactProcessor.process(localArtifact: tempDir)
var artifacts: [URL] = []
// Add optional directory with generated ObjC headers
@@ -31,7 +31,7 @@ enum ArtifactOrganizerLocationPreparationResult: Equatable {
case preparedForArtifact(artifact: URL)
}
/// Prepares .zip artifact for the local operations
/// Prepares existing .zip artifact for the local operations
protocol ArtifactOrganizer {
/// Prepares the location for the artifact unzipping
/// - Parameter fileKey: artifact fileKey that corresponds to the zip filename on the remote cache server
@@ -48,10 +48,13 @@ protocol ArtifactOrganizer {
class ZipArtifactOrganizer: ArtifactOrganizer {
private let cacheDir: URL
// all processors that should "prepare" the unzipped raw artifact
private let artifactProcessors: [ArtifactProcessor]
private let fileManager: FileManager
init(targetTempDir: URL, fileManager: FileManager) {
init(targetTempDir: URL, artifactProcessors: [ArtifactProcessor], fileManager: FileManager) {
cacheDir = targetTempDir.appendingPathComponent("xccache")
self.artifactProcessors = artifactProcessors
self.fileManager = fileManager
}
@@ -93,6 +96,10 @@ class ZipArtifactOrganizer: ArtifactOrganizer {
// when the command was interrupted (internal crash or `kill -9` signal)
let tempDestination = destinationURL.appendingPathExtension("tmp")
try Zip.unzipFile(artifact, destination: tempDestination, overwrite: true, password: nil)
try artifactProcessors.forEach { processor in
try processor.process(rawArtifact: tempDestination)
}
try fileManager.moveItem(at: tempDestination, to: destinationURL)
return destinationURL
}
@@ -0,0 +1,80 @@
// Copyright (c) 2022 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
/// Performs a pre/postprocessing on an artifact package
/// Could be a place for file reorganization (to support legacy package formats) and/or
/// remapp absolute paths in some package files
protocol ArtifactProcessor {
/// Processes a raw artifact in a directory. Raw artifact is a format of an artifact
/// that is stored in a remote cache server (generic)
/// - Parameter rawArtifact: directory that contains raw artifact content
func process(rawArtifact: URL) throws
/// Processes a local artifact in a directory
/// - Parameter localArtifact: directory that contains local (machine-specific) artifact content
func process(localArtifact: URL) throws
}
/// Processes downloaded artifact by replacing generic paths in generated ObjC headers placed in ./include
class UnzippedArtifactProcessor: ArtifactProcessor {
/// All directories in an artifact that should be processed by path remapping
private static let remappingDirs = ["include"]
private let fileRemapper: FileDependenciesRemapper
private let dirScanner: DirScanner
init(fileRemapper: FileDependenciesRemapper, dirScanner: DirScanner) {
self.fileRemapper = fileRemapper
self.dirScanner = dirScanner
}
private func findProcessingEligableFiles(path: String) throws -> [URL] {
let remappingURL = URL(fileURLWithPath: path)
let allFiles = try dirScanner.recursiveItems(at: remappingURL)
return allFiles.filter({ !$0.isHidden })
}
/// Replaces all generic paths in a raw artifact's `include` dir with
/// absolute paths, specific for a given machine and configuration
/// - Parameter rawArtifact: raw artifact location
func process(rawArtifact url: URL) throws {
for remappingDir in Self.remappingDirs {
let remappingPath = url.appendingPathComponent(remappingDir).path
let allFiles = try findProcessingEligableFiles(path: remappingPath)
try allFiles.forEach(fileRemapper.remap(fromGeneric:))
}
}
func process(localArtifact url: URL) throws {
for remappingDir in Self.remappingDirs {
let remappingPath = url.appendingPathComponent(remappingDir).path
let allFiles = try findProcessingEligableFiles(path: remappingPath)
try allFiles.forEach(fileRemapper.remap(fromLocal:))
}
}
}
fileprivate extension URL {
// Recognize hidden files starting with a dot
var isHidden: Bool {
lastPathComponent.hasPrefix(".")
}
}
@@ -88,7 +88,7 @@ class ArtifactSwiftProductsBuilderImpl: ArtifactSwiftProductsBuilder {
throw ArtifactSwiftProductsBuilderError.populatingNonExistingObjCHeader
}
try fileManager.createDirectory(at: moduleObjCURL, withIntermediateDirectories: true, attributes: nil)
try fileManager.spt_forceLinkItem(at: headerURL, to: headerArtifactURL)
try fileManager.spt_forceCopyItem(at: headerURL, to: headerArtifactURL)
}
func includeModuleDefinitionsToTheArtifact(arch: String, moduleURL: URL) throws {
@@ -0,0 +1,81 @@
// Copyright (c) 2022 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
enum FileDependenciesRemapperError: Error {
/// Thrown when the file to remap is invalid (e.g. doesn't exist or has unexpected format)
case invalidRemappingFile(URL)
}
/// Replaces paths in a file content between generic (placeholder-based)
/// and local formats
protocol FileDependenciesRemapper {
/// Replaces all generic paths (with placeholders) to a local, machine
/// specific absolute paths
/// - Parameter url: location of a file that should be remapped in-place
func remap(fromGeneric url: URL) throws
/// Replaces all local, machine specific absolute paths to
/// generic ones
/// - Parameter url: location of a file that should be remapped in-place
func remap(fromLocal url: URL) throws
}
/// Remaps absolute paths in a text files stored on a disk
/// Note: That class can be used only for text-based files, not binaries
class TextFileDependenciesRemapper: FileDependenciesRemapper {
private static let linesSeparator = "\n"
private let remapper: DependenciesRemapper
private let fileAccessor: FileAccessor
init(remapper: DependenciesRemapper, fileAccessor: FileAccessor) {
self.remapper = remapper
self.fileAccessor = fileAccessor
}
private func readFileLines(_ url: URL) throws -> [String] {
guard let content = try fileAccessor.contents(atPath: url.path) else {
// the file is empty
return []
}
guard let contentString = String(data: content, encoding: .utf8) else {
throw FileDependenciesRemapperError.invalidRemappingFile(url)
}
return contentString.components(separatedBy: .newlines)
}
private func storeFileLines(lines: [String], url: URL) throws {
let contentString = lines.joined(separator: "\n")
let contentData = contentString.data(using: String.Encoding.utf8)
try fileAccessor.write(toPath: url.path, contents: contentData)
}
func remap(fromGeneric url: URL) throws {
let contentLines = try readFileLines(url)
let remappedContent = try remapper.replace(genericPaths: contentLines)
try storeFileLines(lines: remappedContent, url: url)
}
func remap(fromLocal url: URL) throws {
let contentLines = try readFileLines(url)
let remappedContent = try remapper.replace(localPaths: contentLines)
try storeFileLines(lines: remappedContent, url: url)
}
}
@@ -31,6 +31,8 @@ enum SwiftmoduleFileExtension: String {
case swiftdoc
case swiftsourceinfo
case swiftinterface
case privateSwiftinterface = "private.swiftinterface"
case abiJson = "abi.json"
}
extension SwiftmoduleFileExtension {
@@ -40,5 +42,7 @@ extension SwiftmoduleFileExtension {
.swiftdoc: .required,
.swiftsourceinfo: .optional,
.swiftinterface: .optional,
.privateSwiftinterface: .optional,
.abiJson: .optional,
]
}
@@ -20,7 +20,7 @@
import Foundation
/// Represents a mode that libtool was called
public enum XCLibtoolMode {
public enum XCLibtoolMode: Equatable {
/// Creating a static library (ar format) from a set of .o input files
case createLibrary(output: String, filelist: String, dependencyInfo: String)
/// Creating a universal library (multiple-architectures) from a set of input .a static libraries
@@ -27,13 +27,19 @@ protocol ThinningConsumerArtifactsOrganizerFactory {
}
class ThinningConsumerZipArtifactsOrganizerFactory: ThinningConsumerArtifactsOrganizerFactory {
private let processors: [ArtifactProcessor]
private let fileManager: FileManager
init(fileManager: FileManager) {
init(processors: [ArtifactProcessor], fileManager: FileManager) {
self.processors = processors
self.fileManager = fileManager
}
func build(targetTempDir: URL) -> ArtifactOrganizer {
ZipArtifactOrganizer(targetTempDir: targetTempDir, fileManager: fileManager)
ZipArtifactOrganizer(
targetTempDir: targetTempDir,
artifactProcessors: processors,
fileManager: fileManager
)
}
}
@@ -58,7 +58,7 @@ class ThinningDiskSwiftcProductsGenerator: SwiftcProductsGenerator {
func generateFrom(
artifactSwiftModuleFiles sourceAtifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL {
) throws -> SwiftcProductsGeneratorOutput {
// Move cached -Swift.h file to the expected location
try diskCopier.copy(file: artifactSwiftModuleObjCFile, destination: objcHeaderOutput)
for (ext, url) in sourceAtifactSwiftModuleFiles {
@@ -79,6 +79,9 @@ class ThinningDiskSwiftcProductsGenerator: SwiftcProductsGenerator {
}
// Build parent dir of the .swiftmodule file that contains a module
return modulePathOutput.deletingLastPathComponent()
return SwiftcProductsGeneratorOutput(
swiftmoduleDir: modulePathOutput.deletingLastPathComponent(),
objcHeaderFile: objcHeaderOutput
)
}
}
@@ -73,11 +73,12 @@ class UnzippedArtifactSwiftProductsOrganizer: SwiftProductsOrganizer {
.appendingPathComponent(moduleName)
.appendingPathComponent("\(moduleName)-Swift.h")
let generatedModuleDir = try productsGenerator.generateFrom(
let generatedModule = try productsGenerator.generateFrom(
artifactSwiftModuleFiles: artifactSwiftmoduleFiles,
artifactSwiftModuleObjCFile: artifactSwiftModuleObjCFile
)
try fingerprintSyncer.decorate(sourceDir: generatedModuleDir, fingerprint: fingerprint)
try fingerprintSyncer.decorate(sourceDir: generatedModule.swiftmoduleDir, fingerprint: fingerprint)
try fingerprintSyncer.decorate(file: generatedModule.objcHeaderFile, fingerprint: fingerprint)
}
}
@@ -238,13 +238,32 @@ class Postbuild {
let moduleSwiftProductURL = context.productsDir
.appendingPathComponent(context.modulesFolderPath)
.appendingPathComponent("\(modulename).swiftmodule")
let objcHeaderSwiftProductURL = context.derivedSourcesDir
.appendingPathComponent("\(modulename)-Swift.h")
// This header is obly valid if building a frameworks
let objcHeaderSwiftPublicPathURL = context.publicHeadersFolderPath?
.appendingPathComponent("\(modulename)-Swift.h")
if let fingerprint = contextSpecificFingerprint {
try fingerprintSyncer.decorate(
sourceDir: moduleSwiftProductURL,
fingerprint: fingerprint
)
try fingerprintSyncer.decorate(
file: objcHeaderSwiftProductURL,
fingerprint: fingerprint
)
if let objcPublic = objcHeaderSwiftPublicPathURL {
try fingerprintSyncer.decorate(
file: objcPublic,
fingerprint: fingerprint
)
}
} else {
try fingerprintSyncer.delete(sourceDir: moduleSwiftProductURL)
try fingerprintSyncer.delete(sourceDir: objcHeaderSwiftProductURL)
if let objcPublic = objcHeaderSwiftPublicPathURL {
try fingerprintSyncer.delete(file: objcPublic)
}
}
}
}
@@ -74,7 +74,7 @@ public struct PostbuildContext {
let builtProductsDir: URL
/// Location to the product bundle. Can be nil for libraries
let bundleDir: URL?
let derivedSourcesDir: URL
var derivedSourcesDir: URL
/// List of all targets to downloaded from the thinning aggregation target
var thinnedTargets: [String]
/// Action type: build, indexbuild etc
@@ -85,6 +85,8 @@ public struct PostbuildContext {
let overlayHeadersPath: URL
/// Regexes of files that should not be included in the dependency list
let irrelevantDependenciesPaths: [String]
/// Location of public headers. Not always available (e.g. static libraries)
var publicHeadersFolderPath: URL?
}
extension PostbuildContext {
@@ -138,5 +140,11 @@ extension PostbuildContext {
/// Note: The file has yaml extension, even it is in the json format
overlayHeadersPath = targetTempDir.appendingPathComponent("all-product-headers.yaml")
irrelevantDependenciesPaths = config.irrelevantDependenciesPaths
let publicHeadersPathEnv: String? = env.readEnv(key: "PUBLIC_HEADERS_FOLDER_PATH")
if let publicHeadersPath = publicHeadersPathEnv, publicHeadersPathEnv != "/usr/local/include" {
// '/usr/local/include' is a value of PUBLIC_HEADERS_FOLDER_PATH when no public headers are automatically
// generated and it is up to a project configuration to place it in a common location (e.g. static library)
publicHeadersFolderPath = builtProductsDir.appendingPathComponent(publicHeadersPath)
}
}
}
@@ -87,8 +87,14 @@ public class XCPostbuild {
fingerprintFilesGenerator,
algorithm: MD5Algorithm()
)
let organizer = ZipArtifactOrganizer(targetTempDir: context.targetTempDir, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: context.targetTempDir,
// In postbuild we don't preprocess artifacts (no need to replace path placeholders)
artifactProcessors: [],
fileManager: fileManager
)
let metaWriter = JsonMetaWriter(fileWriter: fileManager, pretty: config.prettifyMetaFiles)
let fileRemapper = TextFileDependenciesRemapper(remapper: envsRemapper, fileAccessor: fileManager)
let artifactCreator = BuildArtifactCreator(
buildDir: context.productsDir,
tempDir: context.targetTempDir,
@@ -97,6 +103,7 @@ public class XCPostbuild {
modulesFolderPath: context.modulesFolderPath,
dSYMPath: context.dSYMPath,
metaWriter: metaWriter,
artifactProcessor: UnzippedArtifactProcessor(fileRemapper: fileRemapper, dirScanner: fileManager),
fileManager: fileManager
)
let dirAccessor = DirAccessorComposer(
@@ -123,6 +130,7 @@ public class XCPostbuild {
let networkClient = NetworkClientImpl(
session: sessionFactory.build(),
retries: config.uploadRetries,
retryDelay: config.retryDelay,
fileManager: fileManager,
awsV4Signature: awsV4Signature
)
@@ -130,6 +138,7 @@ public class XCPostbuild {
mode: context.mode,
downloadStreamURL: context.recommendedCacheAddress,
upstreamStreamURL: context.cacheAddresses,
uploadBatchSize: config.uploadBatchSize,
networkClient: networkClient,
urlBuilderFactory: {
try URLBuilderImpl(
@@ -200,7 +209,10 @@ public class XCPostbuild {
if context.moduleName == config.thinningTargetModuleName {
switch context.mode {
case .consumer:
// no need to process artifacts in postbuild. Prebuild has already
// run a processor on a downloaded artifact
let artifactOrganizerFactory = ThinningConsumerZipArtifactsOrganizerFactory(
processors: [],
fileManager: fileManager
)
let swiftProductsLocationProvider =
@@ -109,6 +109,7 @@ public class XCPrebuild {
let networkClient = NetworkClientImpl(
session: sessionFactory.build(),
retries: config.downloadRetries,
retryDelay: config.retryDelay,
fileManager: fileManager,
awsV4Signature: awsV4Signature
)
@@ -151,13 +152,25 @@ public class XCPrebuild {
filesFingerprintGenerator,
algorithm: MD5Algorithm()
)
let organizer = ZipArtifactOrganizer(targetTempDir: context.targetTempDir, fileManager: fileManager)
let fileRemapper = TextFileDependenciesRemapper(
remapper: envsRemapper,
fileAccessor: fileManager
)
let artifactProcessor = UnzippedArtifactProcessor(fileRemapper: fileRemapper, dirScanner: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: context.targetTempDir,
artifactProcessors: [artifactProcessor],
fileManager: fileManager
)
let metaReader = JsonMetaReader(fileAccessor: fileManager)
var consumerPlugins: [ArtifactConsumerPrebuildPlugin] = []
if config.thinningEnabled {
if context.moduleName == config.thinningTargetModuleName, let thinnedTarget = context.thinnedTargets {
let organizerFactory = ThinningConsumerZipArtifactsOrganizerFactory(fileManager: .default)
let organizerFactory = ThinningConsumerZipArtifactsOrganizerFactory(
processors: [artifactProcessor],
fileManager: fileManager
)
let aggregationPlugin = ThinningConsumerPrebuildPlugin(
targetName: context.targetName,
tempDir: context.targetTempDir,
@@ -396,7 +396,8 @@ class TemplateBasedCCWrapperBuilder: CCWrapperBuilder {
const char *output_arg_name = "-o";
const char *serialize_diagnostics_arg_name = "--serialize-diagnostics";
const char *language_mode_arg_name = "-x";
const char *precompile_header_arg_value = "objective-c-header";
const char *precompile_objc_header_arg_value = "objective-c-header";
const char *precompile_c_header_arg_value = "c-header";
const char *clang_cmd = "\(clangCommand)";
const char *markerFile = "\(markerFilename)";
const char *compilationHistoryFile = "\(compilationHistoryFilename)";
@@ -464,7 +465,7 @@ class TemplateBasedCCWrapperBuilder: CCWrapperBuilder {
clang_args[argc] = NULL;
// Verify mode. Even a target is cached, pch mode is not supported. Fallback to the local compilation
if (language_mode != NULL && strcmp(language_mode, precompile_header_arg_value) == 0) {
if (language_mode != NULL && (strcmp(language_mode, precompile_objc_header_arg_value) == 0 || strcmp(language_mode, precompile_c_header_arg_value) == 0)) {
return execvp(clang_cmd, (char *const*) clang_args);
}
@@ -44,11 +44,13 @@ class XcodeProjBuildSettingsIntegrateAppender: BuildSettingsIntegrateAppender {
func appendToBuildSettings(buildSettings: BuildSettings, wrappers: XCRCBinariesPaths) -> BuildSettings {
var result = buildSettings
result["SWIFT_EXEC"] = wrappers.swiftc.path
result["SWIFT_USE_INTEGRATED_DRIVER"] = "NO"
// When generating artifacts, no need to shell-out all compilation commands to our wrappers
if case .consumer = mode {
result["CC"] = wrappers.cc.path
result["LD"] = wrappers.ld.path
result["LIBTOOL"] = wrappers.libtool.path
result["LDPLUSPLUS"] = wrappers.ldplusplus.path
}
let existingSwiftFlags = result["OTHER_SWIFT_FLAGS"] as? String
@@ -53,6 +53,7 @@ extension IntegrateContext {
swiftc: binariesDir.appendingPathComponent("xcswiftc"),
libtool: binariesDir.appendingPathComponent("xclibtool"),
ld: binariesDir.appendingPathComponent("xcld"),
ldplusplus: binariesDir.appendingPathComponent("xcldplusplus"),
prebuild: binariesDir.appendingPathComponent("xcprebuild"),
postbuild: binariesDir.appendingPathComponent("xcpostbuild")
)
@@ -26,6 +26,7 @@ struct XCRCBinariesPaths {
let swiftc: URL
let libtool: URL
let ld: URL
let ldplusplus: URL
let prebuild: URL
let postbuild: URL
}
@@ -230,10 +230,12 @@ struct XcodeProjIntegrate: Integrate {
if let sourceIndex = target.buildPhases.map(\.buildPhase).firstIndex(of: .sources) {
// add (pre|post)build phases only when a target has some compilation steps
// otherwise they make no sense (nothing to store in an artifact)
// add postbuild right after compilation as custom build steps may depend on files generated by
// the xcpostbuild (e.g. to copy -Swift.h.md5)
pbxproj.add(object: postbuildPhase)
target.buildPhases.insert(postbuildPhase, at: sourceIndex + 1)
pbxproj.add(object: prebuildPhase)
target.buildPhases.insert(prebuildPhase, at: sourceIndex)
pbxproj.add(object: postbuildPhase)
target.buildPhases.append(postbuildPhase)
}
}
@@ -87,6 +87,7 @@ public class XCPrepare {
let networkClient = NetworkClientImpl(
session: sessionFactory.build(),
retries: config.downloadRetries,
retryDelay: config.retryDelay,
fileManager: fileManager,
awsV4Signature: awsV4Signature
)
@@ -69,6 +69,7 @@ public class XCPrepareMark {
let networkClient = NetworkClientImpl(
session: sessionFactory.build(),
retries: config.uploadRetries,
retryDelay: config.retryDelay,
fileManager: fileManager,
awsV4Signature: awsV4Signature
)
@@ -76,6 +77,7 @@ public class XCPrepareMark {
mode: .producer,
downloadStreamURL: context.recommendedCacheAddress,
upstreamStreamURL: context.cacheAddresses,
uploadBatchSize: config.uploadBatchSize,
networkClient: networkClient
) { [configuration, platform] cacheAddress in
// Prepare URLs don't include target name or envFingperint, which are valid only for a target level
@@ -78,7 +78,12 @@ public class XCCreateBinary {
}
let markerURL = tempDir.appendingPathComponent(config.modeMarkerPath)
do {
let organizer = ZipArtifactOrganizer(targetTempDir: tempDir, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: tempDir,
// Creation binary doesn't call artifact preprocessing
artifactProcessors: [],
fileManager: fileManager
)
let dependenciesWriter = FileDatWriter(dependencyInfo, fileManager: fileManager)
let markerReader = FileMarkerReader(markerURL, fileManager: fileManager)
guard fileManager.fileExists(atPath: markerURL.path) else {
@@ -55,7 +55,7 @@ class MirroredLinkingSwiftcProductsGenerator: SwiftcProductsGenerator {
func generateFrom(
artifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL {
) throws -> SwiftcProductsGeneratorOutput {
/// Predict moduleName from the `*.swiftmodule` artifact
let foundSwiftmoduleFile = artifactSwiftModuleFiles[.swiftmodule]
guard let mainSwiftmoduleFile = foundSwiftmoduleFile else {
@@ -26,14 +26,19 @@ enum DiskSwiftcProductsGeneratorError: Error {
case unknownSwiftmoduleFile
}
struct SwiftcProductsGeneratorOutput {
let swiftmoduleDir: URL
let objcHeaderFile: URL
}
/// Generates swiftc product to the expected location
protocol SwiftcProductsGenerator {
/// Generates products from given files
/// - Returns: location dir where .swiftmodule files have been placed
/// - Returns: location dir where .swiftmodule and ObjC header files have been placed
func generateFrom(
artifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL
) throws -> SwiftcProductsGeneratorOutput
}
/// Generator that produces all products in the locations where Xcode expects it, using provided disk copier
@@ -64,7 +69,7 @@ class DiskSwiftcProductsGenerator: SwiftcProductsGenerator {
func generateFrom(
artifactSwiftModuleFiles sourceAtifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL {
) throws -> SwiftcProductsGeneratorOutput {
// Move cached -Swift.h file to the expected location
try diskCopier.copy(file: artifactSwiftModuleObjCFile, destination: objcHeaderOutput)
for (ext, url) in sourceAtifactSwiftModuleFiles {
@@ -85,6 +90,9 @@ class DiskSwiftcProductsGenerator: SwiftcProductsGenerator {
}
// Build parent dir of the .swiftmodule file that contains a module
return modulePathOutput.deletingLastPathComponent()
return SwiftcProductsGeneratorOutput(
swiftmoduleDir: modulePathOutput.deletingLastPathComponent(),
objcHeaderFile: objcHeaderOutput
)
}
}
@@ -83,7 +83,12 @@ public class XCSwiftc {
let inputReader = SwiftcFilemapInputEditor(context.filemap, fileManager: fileManager)
let fileListEditor = FileListEditor(context.fileList, fileManager: fileManager)
let artifactOrganizer = ZipArtifactOrganizer(targetTempDir: context.tempDir, fileManager: fileManager)
let artifactOrganizer = ZipArtifactOrganizer(
targetTempDir: context.tempDir,
// xcswiftc doesn't call artifact preprocessing
artifactProcessors: [],
fileManager: fileManager
)
// TODO: check for allowedFile comparing a list of all inputfiles, not dependencies from a marker
let makerReferencedFilesListScanner = FileListScannerImpl(markerReader, caseSensitive: false)
let allowedFilesListScanner = ExceptionsFilteredFileListScanner(
@@ -83,6 +83,10 @@ public struct XCRemoteCacheConfig: Encodable {
var downloadRetries: Int = 0
/// Number of retries for upload requests
var uploadRetries: Int = 3
/// Delay between retries in seconds
var retryDelay: Double = 10.0
/// Maximum number of simultaneous requests. 0 means no limits
var uploadBatchSize: Int = 0
/// Extra headers appended to all remote HTTP(S) requests
var requestCustomHeaders: [String: String] = [:]
/// Filename (without an extension) of the compilation input file that is used
@@ -107,7 +111,8 @@ public struct XCRemoteCacheConfig: Encodable {
var turnOffRemoteCacheOnFirstTimeout: Bool = false
/// List of all extensions that should carry over source fingerprints. Extensions of all product files that
/// contain non-deterministic content (absolute paths, timestamp, etc) should be included
var productFilesExtensionsWithContentOverride = ["swiftmodule"]
/// .h files may contain absolute paths if NS_ENUM is used in a public API from Swift code
var productFilesExtensionsWithContentOverride = ["swiftmodule", "h"]
/// If true, plugins for thinning support should be enabled
var thinningEnabled: Bool = false
/// Module name of a target that works as a helper for thinned targets
@@ -175,6 +180,8 @@ extension XCRemoteCacheConfig {
merge.statsDir = scheme.statsDir ?? statsDir
merge.downloadRetries = scheme.downloadRetries ?? downloadRetries
merge.uploadRetries = scheme.uploadRetries ?? uploadRetries
merge.retryDelay = scheme.retryDelay ?? retryDelay
merge.uploadBatchSize = scheme.uploadBatchSize ?? uploadBatchSize
merge.requestCustomHeaders = scheme.requestCustomHeaders ?? requestCustomHeaders
merge.thinTargetMockFilename = scheme.thinTargetMockFilename ?? thinTargetMockFilename
merge.focusedTargets = scheme.focusedTargets ?? focusedTargets
@@ -243,6 +250,8 @@ struct ConfigFileScheme: Decodable {
let statsDir: String?
let downloadRetries: Int?
let uploadRetries: Int?
let retryDelay: Double?
let uploadBatchSize: Int?
let requestCustomHeaders: [String: String]?
let thinTargetMockFilename: String?
let focusedTargets: [String]?
@@ -291,6 +300,8 @@ struct ConfigFileScheme: Decodable {
case statsDir = "stats_dir"
case downloadRetries = "download_retries"
case uploadRetries = "upload_retries"
case retryDelay = "retry_delay"
case uploadBatchSize = "upload_batch_size"
case requestCustomHeaders = "request_custom_headers"
case thinTargetMockFilename = "thin_target_mock_filename"
case focusedTargets = "focused_targets"
@@ -357,6 +368,7 @@ class XCRemoteCacheConfigReader {
extraConfURL = URL(fileURLWithPath: config.extraConfigurationFile, relativeTo: rootURL)
} catch {
infoLog("Extra config override failed with \(error). Skipping extra configuration")
// swiftlint:disable:next unneeded_break_in_switch
break
}
}
@@ -51,34 +51,22 @@ public class FileDependenciesReader: DependenciesReader {
public func findDependencies() throws -> [String] {
let yaml = try readRaw()
struct ParseState {
var buffer: String = ""
var prevChar: Character?
var result: [String] = []
func with(buffer: String? = nil, prevChar: Character? = nil, result: [String]? = nil) -> ParseState {
var new = self
new.buffer = buffer ?? new.buffer
new.prevChar = prevChar ?? new.prevChar
new.result = result ?? new.result
return new
}
}
let dependencies = yaml.reduce(Set<String>()) { prev, arg1 -> Set<String> in
let (key, value) = arg1
switch key {
case "dependencies":
// 'clang' output formatting
return Set(splitDependencyFileList(value))
return Set(parseDependencyFileList(value))
case let s where s.hasSuffix(".o") || s.hasSuffix(".bc"):
// 'swiftc' output formatting
// take dependencies from any .o or .bc file
// Note: For WMO, all .{o|bc} files have the same dependencies
return Set(splitDependencyFileList(value))
return Set(parseDependencyFileList(value))
default:
return prev
}
}
return Array(dependencies)
}
@@ -92,56 +80,92 @@ public class FileDependenciesReader: DependenciesReader {
return yaml.mapValues { $0.components(separatedBy: .whitespaces) }
}
private func readRaw() throws -> [String: String] {
func readRaw() throws -> [String: String] {
let fileData = try getFileData()
let fileString = try getFileStringFromData(fileData: fileData)
let yaml = try getYaml(fileString: fileString)
return yaml
}
func getFileData() throws -> Data {
guard let fileData = fileManager.contents(atPath: file.path) else {
throw DependenciesReaderError.readingError
}
return fileData
}
func getFileStringFromData(fileData: Data) throws -> String {
guard let fileString = String(data: fileData, encoding: .utf8) else {
throw DependenciesReaderError.invalidFile
}
// .d matches the .yaml format
return fileString
}
func getYaml(fileString: String) throws -> [String: String] {
guard let yaml = try Yams.load(yaml: fileString) as? [String: String] else {
throw DependenciesReaderError.invalidFile
}
return yaml
}
/// Splits space or new line separated files into a set of files
/// Parses the String to get the list of files
/// It iterates over the String using its UTF8View since it is more performant (String type operates
/// in a higher abstraction level and supports features that have a negative impact in the performance)
/// It supports escaping whitespace charaters, prefixed with "\\"
/// - Parameter string: string of whitespace charaters separated file paths
/// - Returns: Array of all file paths
private func splitDependencyFileList(_ string: String) -> [String] {
struct ParseState {
var buffer: String = ""
var prevChar: Character?
var result: [String] = []
func with(buffer: String? = nil, prevChar: Character? = nil, result: [String]? = nil) -> ParseState {
var new = self
new.buffer = buffer ?? new.buffer
new.prevChar = prevChar ?? new.prevChar
new.result = result ?? new.result
return new
}
func parseDependencyFileList(_ string: String) -> [String] {
var result: [String] = []
var prevChar: UTF8.CodeUnit?
// These index are used to move over the UTF8View of the string
// The goal is to optimize the memory used, since UTF8View uses
// the same memory as the original String without copying it
var startIndex = string.utf8.startIndex
var endIndex = startIndex
// This buffer is only used to save the part of the path that has been already parsed when finding a backslash
var buffer: String = ""
for c in string.utf8 {
switch c {
case UTF8.CodeUnit(ascii: "\n") where prevChar == UTF8.CodeUnit(ascii: "\\"):
startIndex = string.utf8.index(after: startIndex)
endIndex = startIndex
case UTF8.CodeUnit(ascii: " ") where startIndex == endIndex && buffer.isEmpty:
startIndex = string.utf8.index(after: startIndex)
endIndex = startIndex
case UTF8.CodeUnit(ascii: " ") where prevChar != UTF8.CodeUnit(ascii: "\\"):
// If a space is found and it is not escaped, then that's the end of the file path
buffer += String(Substring(string.utf8[startIndex ..< endIndex]))
result.append(buffer)
buffer = ""
prevChar = nil
startIndex = string.utf8.index(after: endIndex)
endIndex = startIndex
case UTF8.CodeUnit(ascii: "\\"):
// If a backslash is found it is not included in the file path
// The current parsed range of the UTF8View is saved in the buffer as a String
buffer += String(Substring(string.utf8[startIndex ..< endIndex]))
// The backslash is assigned as the previous char
prevChar = c
// The indexes are moved to the next char so we continue parsing the String
startIndex = string.utf8.index(after: endIndex)
endIndex = startIndex
default:
// As long as it is possible the indexes are used to track the range of the string that
// will be included in the file path (until it ends or until a backslash is found)
endIndex = string.utf8.index(after: endIndex)
// The char is assigned as the previous char
prevChar = c
}
}
let parseResult = string.reduce(ParseState()) { total, char in
switch char {
case "\n" where total.prevChar == "\\":
return total
case " " where total.buffer.isEmpty:
return total
case " " where total.prevChar == "\\":
return total.with(buffer: "\(total.buffer) ")
case " ":
return total.with(buffer: "", prevChar: nil, result: total.result + [total.buffer])
case "\\":
return total.with(prevChar: "\\")
default:
return total.with(buffer: "\(total.buffer)\(char)", prevChar: char, result: total.result)
}
if startIndex != endIndex {
buffer += String(Substring(string.utf8[startIndex ..< endIndex]))
result.append(buffer)
}
if !parseResult.buffer.isEmpty {
return parseResult.result + [parseResult.buffer]
}
return parseResult.result
return result
}
}
@@ -50,7 +50,7 @@ public class FileDependenciesWriter: DependenciesWriter {
var content = ""
for (file, deps) in dependencies {
content.append(file + ": ")
content.append(deps.joined(separator: " "))
content.append(deps.map { $0.replacingOccurrences(of: " ", with: "\\ ") }.joined(separator: " "))
content.append("\n")
}
try content.write(to: file, atomically: true, encoding: .utf8)
@@ -30,6 +30,10 @@ protocol FingerprintSyncer {
func decorate(sourceDir: URL, fingerprint: String) throws
/// Deletes fingerprint overrides in the dir (if already created)
func delete(sourceDir: URL) throws
/// Sets a fingerprint override for a singe file placed
func decorate(file: URL, fingerprint: String) throws
/// Deletes fingerprint override for a file (if already created)
func delete(file: URL) throws
}
class FileFingerprintSyncer: FingerprintSyncer {
@@ -78,4 +82,25 @@ class FileFingerprintSyncer: FingerprintSyncer {
try dirAccessor.removeItem(atPath: file.path)
}
}
func decorate(file: URL, fingerprint: String) throws {
guard let fingerprintData = fingerprint.data(using: .utf8) else {
throw FingerprintSyncerError.invalidFingerprint
}
let fingerprintFile = file.appendingPathExtension(fingerprintExtension)
try dirAccessor.write(toPath: fingerprintFile.path, contents: fingerprintData)
}
func delete(file: URL) throws {
guard case .file = try dirAccessor.itemType(atPath: file.path) else {
// no file to decorate (no module was generated)
return
}
let overrideURL = file.appendingPathExtension(fingerprintExtension)
guard case .file = try dirAccessor.itemType(atPath: overrideURL.path) else {
// no override
return
}
try dirAccessor.removeItem(atPath: overrideURL.path)
}
}
@@ -33,8 +33,13 @@ protocol DirScanner {
/// Returns all items in a directory (shallow search)
/// - Parameter at: url of an existing directory to search
/// - Throws: an error if dir doesn't exist or I/O error
/// - Throws: an error if a dir doesn't exist or on I/O error
func items(at dir: URL) throws -> [URL]
/// Returns all items in a directory (recursive search)
/// - Parameter at: url of an existing directory to search
/// - Throws: an error if a dir doesn't exist or on I/O error
func recursiveItems(at dir: URL) throws -> [URL]
}
typealias DirAccessor = FileAccessor & DirScanner
@@ -54,4 +59,18 @@ extension FileManager: DirScanner {
let resolvedDir = dir.resolvingSymlinksInPath()
return try contentsOfDirectory(at: resolvedDir, includingPropertiesForKeys: nil, options: [])
}
func recursiveItems(at dir: URL) throws -> [URL] {
// Iterating DFS
var queue: [URL] = [dir]
var results: [URL] = []
while let item = queue.popLast() {
if try itemType(atPath: item.path) == .dir {
try queue.append(contentsOf: items(at: item))
} else {
results.append(item)
}
}
return results
}
}
@@ -52,4 +52,8 @@ class DirAccessorComposer: DirAccessor {
func items(at dir: URL) throws -> [URL] {
try dirScanner.items(at: dir)
}
func recursiveItems(at dir: URL) throws -> [URL] {
try dirScanner.recursiveItems(at: dir)
}
}
@@ -52,7 +52,9 @@ class EnvironmentFingerprintGenerator {
}
try fill(envKeys: Self.defaultEnvFingerprintKeys + customFingerprintEnvs)
try generator.append(version)
return try generator.generate()
let result = try generator.generate()
generatedFingerprint = result
return result
}
/// Creates a fingerprint of the environemtn, by hashing all ENVs specified in keys
@@ -29,12 +29,14 @@ class NetworkClientImpl: NetworkClient {
private let session: URLSession
private let fileManager: FileManager
private let maxRetries: Int
private let retryDelay: TimeInterval
private let awsV4Signature: AWSV4Signature?
init(session: URLSession, retries: Int, fileManager: FileManager, awsV4Signature: AWSV4Signature?) {
init(session: URLSession, retries: Int, retryDelay: TimeInterval, fileManager: FileManager, awsV4Signature: AWSV4Signature?) {
self.session = session
self.fileManager = fileManager
maxRetries = retries
self.maxRetries = retries
self.retryDelay = retryDelay
self.awsV4Signature = awsV4Signature
}
@@ -75,7 +77,12 @@ class NetworkClientImpl: NetworkClient {
func download(_ url: URL, to location: URL, completion: @escaping (Result<Void, NetworkClientError>) -> Void) {
var request = URLRequest(url: url)
setupAuthenticationSignatureIfPresent(&request)
makeDownloadRequest(request, output: location, completion: completion)
makeDownloadRequest(
request,
output: location,
retries: maxRetries,
completion: completion
)
}
func upload(_ file: URL, as url: URL, completion: @escaping (Result<Void, NetworkClientError>) -> Void) {
@@ -123,7 +130,7 @@ class NetworkClientImpl: NetworkClient {
dataTask.resume()
}
private func makeDownloadRequest(_ request: URLRequest, output: URL, completion: @escaping (Result<Void, NetworkClientError>) -> Void) {
private func makeDownloadRequest(_ request: URLRequest, output: URL, retries: Int, completion: @escaping (Result<Void, NetworkClientError>) -> Void) {
guard fileManager.fileExists(atPath: output.path) == false else {
infoLog("Download file found in the destination, skipping download.")
completion(.success(()))
@@ -133,6 +140,17 @@ class NetworkClientImpl: NetworkClient {
let dataTask = session.downloadTask(with: request) { [fileManager] fileURL, _, error in
guard let fileURL = fileURL else {
let networkError = error.map(NetworkClientError.build) ?? .inconsistentSession
if retries > 0 {
infoLog("Download request failed with \(networkError). Left retries: \(retries).")
self.retryDownload(
request,
output: output,
retries: retries,
completion: completion,
after: self.retryDelay
)
return
}
errorLog("Download request failed: \(networkError)")
completion(.failure(networkError))
return
@@ -173,7 +191,13 @@ class NetworkClientImpl: NetworkClient {
if let error = responseError {
if retries > 0 {
infoLog("Upload request failed with \(error). Left retries: \(retries).")
self.makeUploadRequest(request, input: input, retries: retries - 1, completion: completion)
self.retryUpload(
request,
input: input,
retries: retries,
completion: completion,
after: self.retryDelay
)
return
}
errorLog("Upload request failed: \(error)")
@@ -184,6 +208,30 @@ class NetworkClientImpl: NetworkClient {
}
dataTask.resume()
}
private func retryUpload(_ request: URLRequest, input: URL, retries: Int, completion: @escaping (Result<Void, NetworkClientError>) -> Void, after: TimeInterval) {
DispatchQueue.global().asyncAfter(deadline: .now() + after) { [weak self] in
guard let self = self else { return }
self.makeUploadRequest(
request,
input: input,
retries: retries - 1,
completion: completion
)
}
}
private func retryDownload(_ request: URLRequest, output: URL, retries: Int, completion: @escaping (Result<Void, NetworkClientError>) -> Void, after: TimeInterval) {
DispatchQueue.global().asyncAfter(deadline: .now() + after) { [weak self] in
guard let self = self else { return }
self.makeDownloadRequest(
request,
output: output,
retries: retries - 1,
completion: completion
)
}
}
}
private extension NetworkClientError {
@@ -27,11 +27,20 @@ class RemoteNetworkClientAbstractFactory {
private let upstreamStreamURL: [URL]
private let networkClient: NetworkClient
private let urlBuilderFactory: (URL) throws -> URLBuilder
private let uploadBatchSize: Int
init(mode: Mode, downloadStreamURL: URL, upstreamStreamURL: [URL], networkClient: NetworkClient, urlBuilderFactory: @escaping (URL) throws -> URLBuilder) {
init(
mode: Mode,
downloadStreamURL: URL,
upstreamStreamURL: [URL],
uploadBatchSize: Int,
networkClient: NetworkClient,
urlBuilderFactory: @escaping (URL) throws -> URLBuilder
) {
self.mode = mode
self.downloadStreamURL = downloadStreamURL
self.upstreamStreamURL = upstreamStreamURL
self.uploadBatchSize = uploadBatchSize
self.networkClient = networkClient
self.urlBuilderFactory = urlBuilderFactory
}
@@ -49,7 +58,8 @@ class RemoteNetworkClientAbstractFactory {
return ReplicatedRemotesNetworkClient(
networkClient,
download: downloadURLBuilder,
uploads: upstreamBuilders
uploads: upstreamBuilders,
uploadBatchSize: uploadBatchSize
)
case .consumer:
return RemoteNetworkClientImpl(networkClient, downloadURLBuilder)
@@ -23,10 +23,12 @@ import Foundation
class ReplicatedRemotesNetworkClient: RemoteNetworkClientImpl {
private let networkClient: NetworkClient
private let uploadURLBuilders: [URLBuilder]
private let uploadBatchSize: Int
init(_ networkClient: NetworkClient, download: URLBuilder, uploads uploadURLBuilders: [URLBuilder]) {
init(_ networkClient: NetworkClient, download: URLBuilder, uploads uploadURLBuilders: [URLBuilder], uploadBatchSize: Int) {
self.networkClient = networkClient
self.uploadURLBuilders = uploadURLBuilders
self.uploadBatchSize = uploadBatchSize
super.init(networkClient, download)
}
@@ -39,6 +41,9 @@ class ReplicatedRemotesNetworkClient: RemoteNetworkClientImpl {
let group = DispatchGroup()
var results: [Result<Void, NetworkClientError>] = Array(repeating: .failure(.noResponse), count: urls.count)
urls.enumerated().forEach { index, url in
if uploadBatchSize > 0 && index > 0 && index % uploadBatchSize == 0 {
group.wait()
}
group.enter()
networkClient.upload(file, as: url) { receivedResult in
results[index] = receivedResult
@@ -58,6 +63,9 @@ class ReplicatedRemotesNetworkClient: RemoteNetworkClientImpl {
let group = DispatchGroup()
var results: [Result<Void, NetworkClientError>] = Array(repeating: .failure(.noResponse), count: urls.count)
urls.enumerated().forEach { index, url in
if uploadBatchSize > 0 && index > 0 && index % uploadBatchSize == 0 {
group.wait()
}
group.enter()
networkClient.create(url) { receivedResult in
results[index] = receivedResult
+1 -1
View File
@@ -21,7 +21,7 @@ import Foundation
import XCRemoteCache
/// Wrapper for a `LD` program that copies the dynamic executable from a cached-downloaded location
/// Fallbacks to a standard `clang` when the Ramote cache is not applicable (e.g. modified sources)
/// Fallbacks to a standard `clang` when the Remote cache is not applicable (e.g. modified sources)
public class XCLDMain {
public func main() {
let args = ProcessInfo().arguments
+75
View File
@@ -0,0 +1,75 @@
// Copyright (c) 2021 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import XCRemoteCache
/// Wrapper for a `LDPLUSPLUS` program that copies the dynamic executable from a cached-downloaded location
/// Fallbacks to a standard `clang++` when the Remote cache is not applicable (e.g. modified sources)
public class XCLDPlusPlusMain {
public func main() {
let args = ProcessInfo().arguments
var output: String?
var filelist: String?
var dependencyInfo: String?
var i = 0
while i < args.count {
switch args[i] {
case "-o":
output = args[i + 1]
i += 1
case "-filelist":
filelist = args[i + 1]
i += 1
case "-dependency_info":
// Skip following `-Xlinker` argument. Sample call:
// `clang -dynamiclib ... -Xlinker -dependency_info -Xlinker /path/Target_dependency_info.dat`
dependencyInfo = args[i + 2]
i += 2
default:
break
}
i += 1
}
guard let outputInput = output, let filelistInput = filelist, let dependencyInfoInput = dependencyInfo else {
let ldCommand = "clang++"
print("Fallbacking to compilation using \(ldCommand).")
let args = ProcessInfo().arguments
let paramList = [ldCommand] + args.dropFirst()
let cargs = paramList.map { strdup($0) } + [nil]
execvp(ldCommand, cargs)
/// C-function `execv` returns only when the command fails
exit(1)
}
// TODO: consider using `clang_command` from .rcinfo
/// concrete clang path should be taken from the current toolchain
let fallbackCommand = "clang++"
XCCreateBinary(
output: outputInput,
filelist: filelistInput,
dependencyInfo: dependencyInfoInput,
fallbackCommand: fallbackCommand,
stepDescription: "xcldplusplus"
).run()
}
}
+22
View File
@@ -0,0 +1,22 @@
// Copyright (c) 2021 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import XCRemoteCache
XCLDPlusPlusMain().main()
+9 -38
View File
@@ -18,53 +18,24 @@
// under the License.
import Foundation
import xclibtoolSupport
import XCRemoteCache
public enum XCLibtoolMainError: Error {
case missingOutput
case unsupportedMode
}
/// Wrapper for a `libtool` program that copies the build executable (e.g. .a) from a cached-downloaded location
/// Fallbacks to a standard `libtool` when the Ramote cache is not applicable (e.g. modified sources)
public class XCLibtoolMain {
public init() { }
public func main() {
let args = ProcessInfo().arguments
var output: String?
// all input arguments library '.a'. Used to create an universal binary
var inputLibraries: [String] = []
var filelist: String?
var dependencyInfo: String?
var i = 0
while i < args.count {
switch args[i] {
case "-o":
output = args[i + 1]
i += 1
case "-filelist":
filelist = args[i + 1]
i += 1
case "-dependency_info":
dependencyInfo = args[i + 1]
i += 1
case let input where input.hasSuffix(".a"):
inputLibraries.append(input)
default:
break
}
i += 1
}
guard let outputInput = output else {
exit(1, "Missing 'output' argument. Args: \(args)")
}
let mode: XCLibtoolMode
if let filelistInput = filelist, let dependencyInfoInput = dependencyInfo {
// libtool is creating a library
mode = .createLibrary(output: outputInput, filelist: filelistInput, dependencyInfo: dependencyInfoInput)
} else if !inputLibraries.isEmpty {
// multiple input libraries suggest creating an universal binary
mode = .createUniversalBinary(output: outputInput, inputs: inputLibraries)
} else {
// unknown mode
exit(1, "Unsupported mode. Args: \(args)")
}
do {
let mode = try XCLibtoolHelper.buildMode(args: args)
try XCLibtool(mode).run()
} catch {
exit(1, "Failed with: \(error). Args: \(args)")
@@ -0,0 +1,72 @@
// Copyright (c) 2023 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import XCRemoteCache
public enum XCLibtoolHelperError: Error {
case missingOutput
case unsupportedMode
}
public class XCLibtoolHelper {
public static func buildMode(args: [String]) throws -> XCLibtoolMode {
var output: String?
// all input arguments are '*.a' or no path extension. Used to create an universal binary
var inputLibraries: [String] = []
var filelist: String?
var dependencyInfo: String?
var i = 0
while i < args.count {
switch args[i] {
case "-o":
output = args[i + 1]
i += 1
case "-filelist":
filelist = args[i + 1]
i += 1
case "-dependency_info":
dependencyInfo = args[i + 1]
i += 1
case let input where ["", "a"].contains(URL(string: args[i])?.pathExtension):
// Support for static frameworks (no extension) and static libraries (.a)
inputLibraries.append(input)
default:
break
}
i += 1
}
guard let outputInput = output else {
throw XCLibtoolHelperError.missingOutput
}
let mode: XCLibtoolMode
if let filelistInput = filelist, let dependencyInfoInput = dependencyInfo {
// libtool is creating a library
mode = .createLibrary(output: outputInput, filelist: filelistInput, dependencyInfo: dependencyInfoInput)
} else if !inputLibraries.isEmpty {
// multiple input libraries suggest creating an universal binary
mode = .createUniversalBinary(output: outputInput, inputs: inputLibraries)
} else {
// unknown mode
throw XCLibtoolHelperError.unsupportedMode
}
return mode
}
}
@@ -28,6 +28,8 @@ class ArtifactSwiftProductsBuilderImplTests: FileXCTestCase {
private var swiftmoduleDocFile: URL!
private var swiftmoduleSourceInfoFile: URL!
private var swiftmoduleInterfaceFile: URL!
private var privateSwiftmoduleInterfaceFile: URL!
private var abiJsonFile: URL!
private var workingDir: URL!
private var builder: ArtifactSwiftProductsBuilderImpl!
@@ -39,6 +41,9 @@ class ArtifactSwiftProductsBuilderImplTests: FileXCTestCase {
swiftmoduleDocFile = moduleDir.appendingPathComponent("MyModule.swiftdoc")
swiftmoduleSourceInfoFile = moduleDir.appendingPathComponent("MyModule.swiftsourceinfo")
swiftmoduleInterfaceFile = moduleDir.appendingPathComponent("MyModule.swiftinterface")
privateSwiftmoduleInterfaceFile = moduleDir.appendingPathComponent("MyModule.private.swiftinterface")
abiJsonFile = moduleDir.appendingPathComponent("MyModule.abi.json")
workingDir = rootDir.appendingPathComponent("working")
builder = ArtifactSwiftProductsBuilderImpl(
workingDir: workingDir,
@@ -98,6 +103,8 @@ class ArtifactSwiftProductsBuilderImplTests: FileXCTestCase {
try fileManager.spt_createEmptyFile(swiftmoduleDocFile)
try fileManager.spt_createEmptyFile(swiftmoduleSourceInfoFile)
try fileManager.spt_createEmptyFile(swiftmoduleInterfaceFile)
try fileManager.spt_createEmptyFile(privateSwiftmoduleInterfaceFile)
try fileManager.spt_createEmptyFile(abiJsonFile)
let builderSwiftmoduleDir =
builder
.buildingArtifactSwiftModulesLocation()
@@ -110,6 +117,10 @@ class ArtifactSwiftProductsBuilderImplTests: FileXCTestCase {
builderSwiftmoduleDir.appendingPathComponent("MyModule.swiftsourceinfo")
let expectedBuildedSwiftInterfaceFile =
builderSwiftmoduleDir.appendingPathComponent("MyModule.swiftinterface")
let expectedPrivateSwiftmoduleInterfaceFile =
builderSwiftmoduleDir.appendingPathComponent("MyModule.private.swiftinterface")
let expectedAbiJsonFile =
builderSwiftmoduleDir.appendingPathComponent("MyModule.abi.json")
try builder.includeModuleDefinitionsToTheArtifact(arch: "arm64", moduleURL: swiftmoduleFile)
@@ -117,6 +128,8 @@ class ArtifactSwiftProductsBuilderImplTests: FileXCTestCase {
XCTAssertTrue(fileManager.fileExists(atPath: expectedBuildedSwiftmoduledocFile.path))
XCTAssertTrue(fileManager.fileExists(atPath: expectedBuildedSwiftSourceInfoFile.path))
XCTAssertTrue(fileManager.fileExists(atPath: expectedBuildedSwiftInterfaceFile.path))
XCTAssertTrue(fileManager.fileExists(atPath: expectedPrivateSwiftmoduleInterfaceFile.path))
XCTAssertTrue(fileManager.fileExists(atPath: expectedAbiJsonFile.path))
}
func testFailsIncludingWhenMissingRequiredSwiftmoduleFiles() throws {
@@ -32,6 +32,8 @@ class BuildArtifactCreatorTests: FileXCTestCase {
private var swiftdocURL: URL!
private var swiftSourceInfoURL: URL!
private var swiftInterfaceURL: URL!
private var privateSwiftInterfaceURL: URL!
private var abiJsonURL: URL!
private var executablePath: String!
private var executableURL: URL!
private var creator: BuildArtifactCreator!
@@ -53,11 +55,16 @@ class BuildArtifactCreatorTests: FileXCTestCase {
.appendingPathComponent("Target.swiftsourceinfo")
swiftInterfaceURL = workDirectory.appendingPathComponent("Objects-normal")
.appendingPathComponent("Target.swiftinterface")
privateSwiftInterfaceURL = workDirectory.appendingPathComponent("Objects-normal")
.appendingPathComponent("Target.private.swiftinterface")
abiJsonURL = workDirectory.appendingPathComponent("Objects-normal")
.appendingPathComponent("Target.abi.json")
executablePath = "libTarget.a"
executableURL = buildDir.appendingPathComponent(executablePath)
dSYM = executableURL.deletingPathExtension().appendingPathExtension(".dSYM")
try fileManager.spt_createEmptyFile(executableURL)
try fileManager.spt_createEmptyFile(headerURL)
let artifactProcessor = NoopArtifactProcessor()
creator = BuildArtifactCreator(
buildDir: buildDir,
@@ -67,6 +74,7 @@ class BuildArtifactCreatorTests: FileXCTestCase {
modulesFolderPath: "",
dSYMPath: dSYM,
metaWriter: JsonMetaWriter(fileWriter: fileManager, pretty: false),
artifactProcessor: artifactProcessor,
fileManager: fileManager
)
}
@@ -122,6 +130,8 @@ class BuildArtifactCreatorTests: FileXCTestCase {
try fileManager.spt_createEmptyFile(swiftdocURL)
try fileManager.spt_createEmptyFile(swiftSourceInfoURL)
try fileManager.spt_createEmptyFile(swiftInterfaceURL)
try fileManager.spt_createEmptyFile(privateSwiftInterfaceURL)
try fileManager.spt_createEmptyFile(abiJsonURL)
try creator.includeModuleDefinitionsToTheArtifact(arch: "arch", moduleURL: swiftmoduleURL)
let artifact = try creator.createArtifact(artifactKey: "key", meta: sampleMeta)
@@ -136,6 +146,8 @@ class BuildArtifactCreatorTests: FileXCTestCase {
unzippedURL.appendingPathComponent("swiftmodule/arch/Target.swiftdoc"),
unzippedURL.appendingPathComponent("swiftmodule/arch/Target.swiftsourceinfo"),
unzippedURL.appendingPathComponent("swiftmodule/arch/Target.swiftinterface"),
unzippedURL.appendingPathComponent("swiftmodule/arch/Target.private.swiftinterface"),
unzippedURL.appendingPathComponent("swiftmodule/arch/Target.abi.json"),
])
}
@@ -0,0 +1,101 @@
// Copyright (c) 2022 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
@testable import XCRemoteCache
import XCTest
class TextFileDependenciesRemapperTests: FileXCTestCase {
let stringsRemapper = StringDependenciesRemapper(
mappings: [
.init(generic: "$(SRCROOT)", local: "/example"),
])
let fileAccessor = FileAccessorFake(mode: .strict)
var remapper: TextFileDependenciesRemapper!
override func setUp() {
super.setUp()
remapper = TextFileDependenciesRemapper(
remapper: stringsRemapper,
fileAccessor: fileAccessor
)
}
func testRemapsGenericPlaceholders() throws {
try fileAccessor.write(toPath: "/file", contents: "Some $(SRCROOT).")
try remapper.remap(fromGeneric: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), "Some /example.")
}
func testRemapsLocalPathsToPlaceholders() throws {
try fileAccessor.write(toPath: "/file", contents: "Some /example.")
try remapper.remap(fromLocal: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), "Some $(SRCROOT).")
}
func testPersistsEmptyLines() throws {
let multilineData = """
Line1
Line 2
""".data(using: .utf8)
try fileAccessor.write(toPath: "/file", contents: multilineData)
try remapper.remap(fromGeneric: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), multilineData)
}
func testPersistsEmptyLineAtTheEnd() throws {
// swiftlint:disable trailing_whitespace
let multilineData = """
Line1
Line 2
""".data(using: .utf8)
// swiftlint:enable trailing_whitespace
try fileAccessor.write(toPath: "/file", contents: multilineData)
try remapper.remap(fromGeneric: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), multilineData)
}
func testReplacesMultipletimesInLine() throws {
try fileAccessor.write(toPath: "/file", contents: "$(SRCROOT) and $(SRCROOT)")
try remapper.remap(fromGeneric: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), "/example and /example")
}
func testReplacesInMultipleLine() throws {
try fileAccessor.write(toPath: "/file", contents: "$(SRCROOT)\n$(SRCROOT)")
try remapper.remap(fromGeneric: "/file")
try XCTAssertEqual(fileAccessor.contents(atPath: "/file"), "/example\n/example")
}
}
@@ -0,0 +1,71 @@
// Copyright (c) 2022 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
@testable import XCRemoteCache
import XCTest
class UnzippedArtifactProcessorTests: FileXCTestCase {
private let fileAccessor = FileAccessorFake(mode: .strict)
private let remapper = StringDependenciesRemapper(mappings: [.init(generic: "$(SRCROOT)", local: "/local")])
private var fileRemapper: FileDependenciesRemapper!
private var processor: UnzippedArtifactProcessor!
override func setUp() {
super.setUp()
fileRemapper = TextFileDependenciesRemapper(remapper: remapper, fileAccessor: fileAccessor)
processor = UnzippedArtifactProcessor(
fileRemapper: fileRemapper,
dirScanner: fileAccessor
)
}
func testProcessingRawArtifactReplacesPlaceholders() throws {
try fileAccessor.write(toPath: "/artifact/include/file", contents: "Some $(SRCROOT)")
try processor.process(rawArtifact: "/artifact")
XCTAssertEqual(try fileAccessor.contents(atPath: "/artifact/include/file"), "Some /local")
}
func testProcessingRawArtifactReplacesInNestedInclude() throws {
try fileAccessor.write(toPath: "/artifact/include/nested/file", contents: "Some $(SRCROOT)")
try processor.process(rawArtifact: "/artifact")
XCTAssertEqual(try fileAccessor.contents(atPath: "/artifact/include/nested/file"), "Some /local")
}
func testProcessingRawArtifactDoesntReplacesInNonIncludeDir() throws {
try fileAccessor.write(toPath: "/artifact/some/file", contents: "Some $(SRCROOT)")
try processor.process(rawArtifact: "/artifact")
XCTAssertEqual(try fileAccessor.contents(atPath: "/artifact/some/file"), "Some $(SRCROOT)")
}
func testDoesntProcessEmptyFiles() throws {
try fileAccessor.write(toPath: "/artifact/include/.hidden", contents: "Some $(SRCROOT)")
try processor.process(rawArtifact: "/artifact")
XCTAssertEqual(try fileAccessor.contents(atPath: "/artifact/include/.hidden"), "Some $(SRCROOT)")
}
}
@@ -54,7 +54,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
func testPreparePlacesArtifactInTheActiveLocation() throws {
let zipURL = try prepareZipFile(content: "Magic", fileName: "content.txt")
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
let preparedArtifact = try organizer.prepare(artifact: zipURL)
@@ -64,7 +68,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
func testPreparingExistingArtifact() throws {
let zipURL = try prepareZipFile(content: "Magic", fileName: "content.txt")
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
_ = try organizer.prepare(artifact: zipURL)
let preparedArtifact = try organizer.prepare(artifact: zipURL)
@@ -75,7 +83,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
func testPreparePlacesArtifactInTheFileKeyRelatedLocation() throws {
let zipURL = try prepareZipFile(content: "Magic", fileName: "content.txt", zipFileName: "abb32_fileKey")
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
let expectedArtifactLocation = workingDirectory.appendingPathComponent("abb32_fileKey")
let preparedArtifact = try organizer.prepare(artifact: zipURL)
@@ -89,7 +101,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
let artifactLocation = workingDirectory.appendingPathComponent("xccache")
.appendingPathComponent(sampleFileKey, isDirectory: true)
try fileManager.createDirectory(at: artifactLocation, withIntermediateDirectories: true, attributes: nil)
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
let result = try organizer.prepareArtifactLocationFor(fileKey: sampleFileKey)
if case .artifactExists(artifactDir: let u) = result {
@@ -105,7 +121,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
.appendingPathComponent("xccache")
.appendingPathComponent(sampleFileKey)
.appendingPathExtension("zip")
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
let result = try organizer.prepareArtifactLocationFor(fileKey: sampleFileKey)
@@ -126,7 +146,11 @@ class ZipArtifactOrganizerTests: XCTestCase {
try fileManager.createDirectory(at: activeArtifact, withIntermediateDirectories: true, attributes: nil)
try fileManager.spt_forceSymbolicLink(at: activeLink, withDestinationURL: activeArtifact)
let organizer = ZipArtifactOrganizer(targetTempDir: workingDirectory, fileManager: fileManager)
let organizer = ZipArtifactOrganizer(
targetTempDir: workingDirectory,
artifactProcessors: [],
fileManager: fileManager
)
let fileKey = try organizer.getActiveArtifactFilekey()
@@ -67,7 +67,8 @@ class ThinningDiskSwiftcProductsGeneratorTests: FileXCTestCase {
artifactSwiftModuleObjCFile: headerFile
)
XCTAssertEqual(generatedModulePath, destinationSwiftModuleDir)
XCTAssertEqual(generatedModulePath.swiftmoduleDir, destinationSwiftModuleDir)
XCTAssertEqual(generatedModulePath.objcHeaderFile, objCHeader)
XCTAssertEqual(fileManager.contents(atPath: expectedSwiftSourceInfoFile.path), "sourceInfo".data(using: .utf8))
XCTAssertEqual(fileManager.contents(atPath: objCHeader.path), "header".data(using: .utf8))
}
@@ -30,6 +30,7 @@ class UnzippedArtifactSwiftProductsOrganizerTests: XCTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
let destination = SwiftcProductsGeneratorOutput(swiftmoduleDir: destination, objcHeaderFile: "")
generator = SwiftcProductsGeneratorSpy(generatedDestination: destination)
dirAccessor = DirAccessorFake()
syncer = FileFingerprintSyncer(
@@ -44,6 +44,7 @@ class PostbuildContextTests: FileXCTestCase {
"BUILT_PRODUCTS_DIR": "BUILT_PRODUCTS_DIR",
"DERIVED_SOURCES_DIR": "DERIVED_SOURCES_DIR",
"CURRENT_VARIANT": "normal",
"PUBLIC_HEADERS_FOLDER_PATH": "/usr/local/include",
]
override func setUpWithError() throws {
@@ -130,4 +131,32 @@ class PostbuildContextTests: FileXCTestCase {
XCTAssertEqual(context.compilationTempDir, "/OBJECT_FILE_DIR_custom/x86_64")
}
func testGenericPublicHeaderDestinationIsSkipped() throws {
var envs = Self.SampleEnvs
envs["PUBLIC_HEADERS_FOLDER_PATH"] = "/usr/local/include"
let context = try PostbuildContext(config, env: envs)
XCTAssertNil(context.publicHeadersFolderPath)
}
func testPublicHeaderFolderIsRelativeToProductsDir() throws {
var envs = Self.SampleEnvs
envs["BUILT_PRODUCTS_DIR"] = "/MyBuiltProductsDir"
envs["PUBLIC_HEADERS_FOLDER_PATH"] = "MyModule.grameworks/Headers"
let context = try PostbuildContext(config, env: envs)
XCTAssertEqual(context.publicHeadersFolderPath, "/MyBuiltProductsDir/MyModule.grameworks/Headers")
}
func testPublicHeaderFolderPathEnvIsOptional() throws {
var envs = Self.SampleEnvs
envs.removeValue(forKey: "PUBLIC_HEADERS_FOLDER_PATH")
let context = try PostbuildContext(config, env: envs)
XCTAssertNil(context.publicHeadersFolderPath)
}
}
@@ -55,7 +55,8 @@ class PostbuildTests: FileXCTestCase {
action: .build,
modeMarkerPath: "",
overlayHeadersPath: "",
irrelevantDependenciesPaths: []
irrelevantDependenciesPaths: [],
publicHeadersFolderPath: nil
)
private var network = RemoteNetworkClientImpl(
NetworkClientFake(fileManager: .default),
@@ -643,4 +644,79 @@ class PostbuildTests: FileXCTestCase {
XCTAssertEqual(downloadedMeta, expectedMeta)
}
func testDecoratesDerivedSwiftHeaderWithEmptyModulesFolderPath() throws {
let dir = try prepareTempDir()
let derivedSourcesDir = dir
.appendingPathComponent("DerivedSources")
let swiftSwiftHeader = derivedSourcesDir
.appendingPathComponent("MyModule-Swift.h")
let swiftSwiftHeaderOverride = swiftSwiftHeader
.appendingPathExtension("md5")
try fileManager.spt_createEmptyDir(derivedSourcesDir)
try fileManager.spt_createEmptyFile(swiftSwiftHeader)
postbuildContext.moduleName = "MyModule"
postbuildContext.derivedSourcesDir = derivedSourcesDir
let postbuild = Postbuild(
context: postbuildContext,
networkClient: network,
remapper: remapper,
fingerprintAccumulator: fingerprintGenerator,
artifactsOrganizer: organizer,
artifactCreator: artifactCreator,
fingerprintSyncer: syncer,
dependenciesReader: dependenciesReader,
dependencyProcessor: processor,
fingerprintOverrideManager: overrideManager,
dSYMOrganizer: DSYMOrganizerFake(dSYMFile: nil),
modeController: modeController,
metaReader: metaReader,
metaWriter: metaWriter,
creatorPlugins: [],
consumerPlugins: []
)
try postbuild.performBuildCompletion()
XCTAssertTrue(fileManager.fileExists(atPath: swiftSwiftHeaderOverride.path))
}
func testDecoratesPublicSwiftHeaderWithEmptyModulesFolderPath() throws {
let dir = try prepareTempDir()
let productsDir = dir
.appendingPathComponent("MyModule.framework")
.appendingPathComponent("Headers")
let swiftSwiftHeader = productsDir
.appendingPathComponent("MyModule-Swift.h")
let swiftSwiftHeaderOverride = swiftSwiftHeader
.appendingPathExtension("md5")
try fileManager.spt_createEmptyDir(productsDir)
try fileManager.spt_createEmptyFile(swiftSwiftHeader)
postbuildContext.moduleName = "MyModule"
postbuildContext.publicHeadersFolderPath = productsDir
let postbuild = Postbuild(
context: postbuildContext,
networkClient: network,
remapper: remapper,
fingerprintAccumulator: fingerprintGenerator,
artifactsOrganizer: organizer,
artifactCreator: artifactCreator,
fingerprintSyncer: syncer,
dependenciesReader: dependenciesReader,
dependencyProcessor: processor,
fingerprintOverrideManager: overrideManager,
dSYMOrganizer: DSYMOrganizerFake(dSYMFile: nil),
modeController: modeController,
metaReader: metaReader,
metaWriter: metaWriter,
creatorPlugins: [],
consumerPlugins: []
)
try postbuild.performBuildCompletion()
XCTAssertTrue(fileManager.fileExists(atPath: swiftSwiftHeaderOverride.path))
}
}
@@ -35,6 +35,7 @@ class XcodeProjBuildSettingsIntegrateAppenderTests: XCTestCase {
swiftc: binariesDir.appendingPathComponent("xcswiftc"),
libtool: binariesDir.appendingPathComponent("xclibtool"),
ld: binariesDir.appendingPathComponent("xcld"),
ldplusplus: binariesDir.appendingPathComponent("xcldplusplus"),
prebuild: binariesDir.appendingPathComponent("xcprebuild"),
postbuild: binariesDir.appendingPathComponent("xcpostbuild")
)
@@ -59,4 +60,14 @@ class XcodeProjBuildSettingsIntegrateAppenderTests: XCTestCase {
XCTAssertEqual(resultURL, fakeRootURL.path)
}
func testConsumerSettingLdPlusPlus() throws {
let mode: Mode = .consumer
let fakeRootURL: URL = "/xxxxxxxxxxC"
let appender = XcodeProjBuildSettingsIntegrateAppender(mode: mode, repoRoot: rootURL, fakeSrcRoot: fakeRootURL)
let result = appender.appendToBuildSettings(buildSettings: buildSettings, wrappers: binaries)
let ldPlusPlus: String = try XCTUnwrap(result["LDPLUSPLUS"] as? String)
XCTAssertEqual(ldPlusPlus, binaries.ldplusplus.path)
}
}
@@ -70,7 +70,9 @@ class SwiftcTests: FileXCTestCase {
)
context = try SwiftcContext(config: config, input: input)
markerWriter = MarkerWriterSpy()
productsGenerator = SwiftcProductsGeneratorSpy()
productsGenerator = SwiftcProductsGeneratorSpy(
generatedDestination: SwiftcProductsGeneratorOutput(swiftmoduleDir: "", objcHeaderFile: "")
)
let dependenciesWriterSpy = DependenciesWriterSpy()
self.dependenciesWriterSpy = dependenciesWriterSpy
dependenciesWriterFactory = { [dependenciesWriterSpy] _, _ in dependenciesWriterSpy }
@@ -283,6 +285,12 @@ class SwiftcTests: FileXCTestCase {
let artifactSwiftInterfaceInfo = URL(
fileURLWithPath: "/cachedArtifact/swiftmodule/archTest/Target.swiftinterface"
)
let artifactPrivateSwiftInterfaceInfo = URL(
fileURLWithPath: "/cachedArtifact/swiftmodule/archTest/Target.private.swiftinterface"
)
let artifactAbiJsonInfo = URL(
fileURLWithPath: "/cachedArtifact/swiftmodule/archTest/Target.abi.json"
)
artifactOrganizer = ArtifactOrganizerFake(artifactRoot: artifactRoot)
let swiftc = Swiftc(
@@ -303,17 +311,14 @@ class SwiftcTests: FileXCTestCase {
_ = try swiftc.mockCompilation()
let swiftModuleFiles = try productsGenerator.generated.first.unwrap()
let swiftModuleURL = swiftModuleFiles.0[.swiftmodule]
let swiftDocURL = swiftModuleFiles.0[.swiftdoc]
let swiftSourceInfoURL = swiftModuleFiles.0[.swiftsourceinfo]
let swiftInterfaceURL = swiftModuleFiles.0[.swiftinterface]
let swiftHeaderURL = swiftModuleFiles.1
XCTAssertEqual(swiftModuleURL, artifactSwiftmodule)
XCTAssertEqual(swiftDocURL, artifactSwiftdoc)
XCTAssertEqual(swiftSourceInfoURL, artifactSwiftSourceInfo)
XCTAssertEqual(swiftHeaderURL, artifactObjCHeader)
XCTAssertEqual(swiftInterfaceURL, artifactSwiftInterfaceInfo)
XCTAssertEqual(swiftModuleFiles.0[.swiftmodule], artifactSwiftmodule)
XCTAssertEqual(swiftModuleFiles.0[.swiftdoc], artifactSwiftdoc)
XCTAssertEqual(swiftModuleFiles.0[.swiftsourceinfo], artifactSwiftSourceInfo)
XCTAssertEqual(swiftModuleFiles.0[.swiftinterface], artifactSwiftInterfaceInfo)
XCTAssertEqual(swiftModuleFiles.0[.privateSwiftinterface], artifactPrivateSwiftInterfaceInfo)
XCTAssertEqual(swiftModuleFiles.0[.abiJson], artifactAbiJsonInfo)
XCTAssertEqual(swiftModuleFiles.1, artifactObjCHeader)
}
@@ -333,7 +333,7 @@ class TemplateBasedCCWrapperBuilderTests: FileXCTestCase {
XCTAssertNotEqual(newFileOutputData, Data())
}
func testPCHCompilationFallbacks() throws {
func testPCHObjCCompilationFallbacks() throws {
// Marker is empty to mimic the new file scenario
let pchFile = directory.appendingPathComponent("input.pch")
createValidPCHFile(pchFile)
@@ -344,6 +344,17 @@ class TemplateBasedCCWrapperBuilderTests: FileXCTestCase {
XCTAssertTrue(fileManager.fileExists(atPath: outputFile.path))
}
func testPCHCCompilationFallbacks() throws {
// Marker is empty to mimic the new file scenario
let pchFile = directory.appendingPathComponent("input.pch")
createValidPCHFile(pchFile)
arguments = ["-x", "c-header", "-MF", dependencyFile.path, "-o", outputFile.path, pchFile.path]
try shellExec(Self.xccc.path, args: arguments, inDir: directory.path)
XCTAssertTrue(fileManager.fileExists(atPath: outputFile.path))
}
/// Creates a simple C code in the location
private func createValidCFile(_ location: URL) {
fileManager.createFile(atPath: location.path, contents: "int main(){}".data(using: .utf8), attributes: nil)
@@ -32,11 +32,18 @@ class XCRemoteCacheConfigReaderTests: XCTestCase {
}
func testReadsFromExtraConfig() throws {
try fileReader.write(toPath: "/.rcinfo", contents: "cache_addresses: [test]")
let contents = [
"cache_addresses: [test]",
"retry_delay: 30",
"upload_batch_size: 5",
].joined(separator: "\n").data(using: .utf8)
try fileReader.write(toPath: "/.rcinfo", contents: contents)
let config = try reader.readConfiguration()
XCTAssertEqual(config.cacheAddresses, ["test"])
XCTAssertEqual(config.retryDelay, 30)
XCTAssertEqual(config.uploadBatchSize, 5)
}
func testOverridesExtraConfigFromExtraFile() throws {
@@ -0,0 +1,139 @@
// Copyright (c) 2021 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
@testable import XCRemoteCache
import XCTest
class DependenciesReaderPerformanceTest: XCTestCase {
private static let resourcesSubdirectory = "TestData/Dependencies/DependenciesReaderPerformanceTest"
private func pathForTestData(name: String) throws -> URL {
return try XCTUnwrap(Bundle.module.url(
forResource: name,
withExtension: "d",
subdirectory: DependenciesReaderPerformanceTest.resourcesSubdirectory
))
}
func testFindDependenciesPerformance() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
self.measure { // 0.005
do {
_ = try reader.findDependencies()
} catch {
print("Error reading dependencies")
}
}
}
func testReadRawFilePerformance() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
self.measure { // 0.002
do {
_ = try reader.readRaw()
} catch {
print("Error reading dependencies")
}
}
}
func testGetFileDataPerformance() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
self.measure { // 0.00008
do {
_ = try reader.getFileData()
} catch {
print("Error reading dependencies")
}
}
}
func testGetFileStringPerformance() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
let fileData = try reader.getFileData()
self.measure { // 0.00002
do {
_ = try reader.getFileStringFromData(fileData: fileData)
} catch {
print("Error reading dependencies")
}
}
}
func testGetYamlPerformance() throws { // 0.222
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
let fileData = try reader.getFileData()
let fileString = try reader.getFileStringFromData(fileData: fileData)
self.measure { // 0.0022
do {
_ = try reader.getYaml(fileString: fileString)
} catch {
print("Error reading dependencies")
}
}
}
func testParseDependencyFileListUsingUTF8View() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
let fileData = try reader.getFileData()
let fileString = try reader.getFileStringFromData(fileData: fileData)
let yaml = try reader.getYaml(fileString: fileString)
guard let dependencies = yaml["dependencies"] else {
XCTAssertTrue(false)
return
}
self.measure { // 0.004
let deps = reader.parseDependencyFileList(dependencies)
XCTAssertTrue(deps.count == 1000)
}
}
func testDeprecatedParseDependenciesFilesListOfAnObjectUsingUTF8View() throws {
let file = try pathForTestData(name: "dependencies")
let reader = FileDependenciesReader(file, accessor: FileManager.default)
let fileData = try reader.getFileData()
let fileString = try reader.getFileStringFromData(fileData: fileData)
let yaml = try reader.getYaml(fileString: fileString)
guard let dependencies = yaml["/This/Is/A/Path/To/Some/Object/objectfile.o"] else {
XCTAssertTrue(false)
return
}
self.measure { // 0.00048
let deps = reader.parseDependencyFileList(dependencies)
XCTAssertTrue(deps.count == 100)
}
}
}
@@ -0,0 +1,47 @@
// Copyright (c) 2021 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
@testable import XCRemoteCache
import XCTest
class FileDependenciesWriterTests: XCTestCase {
private func generateTempFileURL(name: String = #function) throws -> URL {
let directory = NSTemporaryDirectory()
return try NSURL.fileURL(withPathComponents: [directory, name]).unwrap()
}
func testWriteDependencyWithSpace() throws {
let url = try generateTempFileURL()
let writer = FileDependenciesWriter(url, accessor: FileManager.default)
try writer.writeGeneric(dependencies: [
"/SomePath/Pods/Target Support Files/lottie-ios/lottie-ios-dummy.m",
])
let expectedContent = """
dependencies: /SomePath/Pods/Target\\ Support\\ Files/lottie-ios/lottie-ios-dummy.m
"""
let content = String(data: try Data(contentsOf: url), encoding: .utf8)
XCTAssertEqual(content, expectedContent)
}
}
@@ -74,4 +74,51 @@ class FileFingerprintSyncerTests: FileXCTestCase {
XCTAssertTrue(fileManager.fileExists(atPath: nonOverrideFile.path))
}
func testDecoratesFile() throws {
let header = swiftmoduleDir.appendingPathComponent("Module-Swift.h")
let headerOverride = swiftmoduleDir.appendingPathComponent("Module-Swift.h.md5")
try fileManager.spt_createEmptyFile(header)
try syncer.decorate(file: header, fingerprint: "1")
XCTAssertEqual(try String(contentsOf: headerOverride), "1")
}
func testFileDecorateOverridesPreviousOverlay() throws {
let header = swiftmoduleDir.appendingPathComponent("Module-Swift.h")
let headerOverride = swiftmoduleDir.appendingPathComponent("Module-Swift.h.md5")
try fileManager.spt_createEmptyFile(header)
try "1".write(to: headerOverride, atomically: true, encoding: .utf8)
try syncer.decorate(file: header, fingerprint: "2")
XCTAssertEqual(try String(contentsOf: headerOverride), "2")
}
func testDeletesFileOverride() throws {
let header = swiftmoduleDir.appendingPathComponent("Module-Swift.h")
let headerOverride = swiftmoduleDir.appendingPathComponent("Module-Swift.h.md5")
try fileManager.spt_createEmptyFile(header)
try fileManager.spt_createEmptyFile(headerOverride)
try syncer.delete(file: header)
XCTAssertFalse(fileManager.fileExists(atPath: headerOverride.path))
}
func testDeletesDoesntDeleteWhenFileIsMissing() throws {
let nonExistingFile = swiftmoduleDir.appendingPathComponent("Module-Swift.h")
XCTAssertNoThrow(try syncer.delete(file: nonExistingFile))
}
func testDeletesDoesntDeleteWhenOverrideIsMissing() throws {
let header = swiftmoduleDir.appendingPathComponent("Module-Swift.h")
try fileManager.spt_createEmptyFile(header)
XCTAssertNoThrow(try syncer.delete(file: header))
}
}
@@ -71,4 +71,17 @@ class FileManagerDirScannerTests: FileXCTestCase {
try XCTAssertThrowsError(dirScanner.items(at: dir))
}
func testFindsAllFilesRecursively() throws {
let dir = workingDirectory!.appendingPathComponent("dir")
let nestedDir = dir.appendingPathComponent("nested")
let nestedFile = nestedDir.appendingPathComponent("file")
try fileManager.spt_createEmptyFile(nestedFile)
let allFiles = try dirScanner.recursiveItems(at: dir)
// returned items may contain symbolic links in a path
let allFilesResolve = allFiles.map { $0.resolvingSymlinksInPath() }
XCTAssertEqual(allFilesResolve, [nestedFile])
}
}
@@ -39,13 +39,17 @@ class EnvironmentFingerprintGeneratorTests: XCTestCase {
private static let currentVersion = "5"
private var config: XCRemoteCacheConfig!
private var generator: FingerprintAccumulator!
private var generator: FingerprintAccumulator! {
return generatorFake
}
private var generatorFake: FingerprintAccumulatorFake!
private var fingerprintGenerator: EnvironmentFingerprintGenerator!
override func setUp() {
super.setUp()
config = XCRemoteCacheConfig(sourceRoot: "")
generator = FingerprintAccumulatorFake()
generatorFake = FingerprintAccumulatorFake()
fingerprintGenerator = EnvironmentFingerprintGenerator(
configuration: config,
env: Self.defaultENV,
@@ -92,4 +96,11 @@ class EnvironmentFingerprintGeneratorTests: XCTestCase {
XCTAssertEqual(fingerprint, "GCC,YES,TARGET,CONG,PLAT,XC,1,2,3,4,AR,CUSTOM_VALUE,\(Self.currentVersion)")
}
func testFingerprintIsGeneratedOnce() throws {
let fingerprint1 = try fingerprintGenerator.generateFingerprint()
let fingerprint2 = try fingerprintGenerator.generateFingerprint()
XCTAssertEqual(fingerprint1, fingerprint2)
XCTAssertEqual(generatorFake.generateCallsCount, 1)
}
}
@@ -72,7 +72,13 @@ class NetworkClientImplTests: XCTestCase {
configuration.protocolClasses = [URLProtocolStub.self]
session = URLSession(configuration: configuration)
fileManager = FileManager.default
client = NetworkClientImpl(session: session, retries: 0, fileManager: fileManager, awsV4Signature: nil)
client = NetworkClientImpl(
session: session,
retries: 0,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: nil
)
}
override func tearDown() {
@@ -87,7 +93,7 @@ class NetworkClientImplTests: XCTestCase {
super.tearDown()
}
func waitForResponse<R>(_ action: (@escaping Completion<R>) -> Void) throws -> Result<R, NetworkClientError> {
func waitForResponse<R>(_ action: (@escaping Completion<R>) -> Void, timeout: TimeInterval = 0.1) throws -> Result<R, NetworkClientError> {
let responseExpectation = expectation(description: "RequestResponse")
var receivedResponse: Result<R, NetworkClientError>?
@@ -95,7 +101,7 @@ class NetworkClientImplTests: XCTestCase {
receivedResponse = response
responseExpectation.fulfill()
}
waitForExpectations(timeout: 0.1)
waitForExpectations(timeout: timeout)
return try receivedResponse.unwrap()
}
@@ -141,9 +147,15 @@ class NetworkClientImplTests: XCTestCase {
}
func testUploadFilureWith400Retries() throws {
client = NetworkClientImpl(session: session, retries: 2, fileManager: fileManager, awsV4Signature: nil)
client = NetworkClientImpl(
session: session,
retries: 2,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: nil
)
responses[url] = .success(failureResponse, Data())
_ = try waitForResponse { client.upload(fileURL, as: url, completion: $0) }
_ = try waitForResponse({ client.upload(fileURL, as: url, completion: $0) }, timeout: 0.5)
XCTAssertEqual(
requests.map(\.url),
@@ -153,13 +165,51 @@ class NetworkClientImplTests: XCTestCase {
}
func testUploadSuccessDoesntRetry() throws {
client = NetworkClientImpl(session: session, retries: 0, fileManager: fileManager, awsV4Signature: nil)
client = NetworkClientImpl(
session: session,
retries: 2,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: nil
)
responses[url] = .success(successResponse, Data())
_ = try waitForResponse { client.upload(fileURL, as: url, completion: $0) }
XCTAssertEqual(requests.map(\.url), [url], "Expected 1 request - original only")
}
func testDownloadFilureWith400Retries() throws {
client = NetworkClientImpl(
session: session,
retries: 2,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: nil
)
responses[url] = nil
_ = try waitForResponse({ client.download(url, to: fileURL, completion: $0) }, timeout: 0.5)
XCTAssertEqual(
requests.map(\.url),
Array(repeating: url, count: 3),
"Expected 3 requests (original + 2 retries)"
)
}
func testDownloadSuccessDoesntRetry() throws {
client = NetworkClientImpl(
session: session,
retries: 2,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: nil
)
responses[url] = .success(successResponse, Data())
_ = try waitForResponse { client.download(url, to: fileURL, completion: $0) }
XCTAssertEqual(requests.map(\.url), [url], "Expected 1 request - original only")
}
func testFileExits400CompletesWithFalse() throws {
responses[url] = .success(failureResponse, Data())
let response = try waitForResponse { client.fileExists(url, completion: $0) }
@@ -208,7 +258,13 @@ class NetworkClientImplTests: XCTestCase {
service: "iam",
date: Date(timeIntervalSince1970: 1_440_938_160)
)
client = NetworkClientImpl(session: session, retries: 0, fileManager: fileManager, awsV4Signature: signature)
client = NetworkClientImpl(
session: session,
retries: 0,
retryDelay: 0,
fileManager: fileManager,
awsV4Signature: signature
)
responses[url] = .success(successResponse, Data())
_ = try waitForResponse { client.fetch(url, completion: $0) }
@@ -39,7 +39,12 @@ class ReplicatedRemotesNetworkClientTests: XCTestCase {
uploadURLs = try [URL(string: "http://upload1.com").unwrap(), URL(string: "http://upload2.com").unwrap()]
download = URLBuilderFake(downloadURL)
uploads = uploadURLs.map(URLBuilderFake.init)
client = ReplicatedRemotesNetworkClient(networkClient, download: download, uploads: uploads)
client = ReplicatedRemotesNetworkClient(
networkClient,
download: download,
uploads: uploads,
uploadBatchSize: 1
)
}
private func prepareLocalEmptyFile() throws -> URL {
@@ -62,6 +67,30 @@ class ReplicatedRemotesNetworkClientTests: XCTestCase {
XCTAssertTrue(try networkClient.fileExistsSynchronously(expectedArtifact2))
}
func testUploadsWithLimit() throws {
var expectedArtifacts = [URL]()
var uploadURLs = [URL]()
for index in 0...99 {
let expectedArtifact = try URL(string: "http://upload\(index).com/file/id1").unwrap()
expectedArtifacts.append(expectedArtifact)
let uploadURL = try URL(string: "http://upload\(index).com").unwrap()
uploadURLs.append(uploadURL)
}
uploads = uploadURLs.map(URLBuilderFake.init)
client = ReplicatedRemotesNetworkClient(
networkClient,
download: download,
uploads: uploads,
uploadBatchSize: 10
)
try client.uploadSynchronously(localSampleFile, as: .artifact(id: "id1"))
for expectedArtifact in expectedArtifacts {
XCTAssertTrue(try networkClient.fileExistsSynchronously(expectedArtifact))
}
}
func testCreatesInAllStreams() throws {
let expectedMeta1 = try URL(string: "http://upload1.com/meta/commit_id").unwrap()
let expectedMeta2 = try URL(string: "http://upload2.com/meta/commit_id").unwrap()
@@ -71,4 +100,5 @@ class ReplicatedRemotesNetworkClientTests: XCTestCase {
XCTAssertTrue(try networkClient.fileExistsSynchronously(expectedMeta1))
XCTAssertTrue(try networkClient.fileExistsSynchronously(expectedMeta2))
}
}
File diff suppressed because one or more lines are too long
@@ -47,6 +47,16 @@ class DirAccessorFake: DirAccessor {
}
}
func recursiveItems(at dir: URL) throws -> [URL] {
memory.compactMap { url, _ in
// comparing paths to ignore dir or url's "isDir" property
if url.deletingLastPathComponent().path.starts(with: dir.path) {
return url
}
return nil
}
}
func contents(atPath path: String) throws -> Data? {
memory[URL(fileURLWithPath: path)]
}
@@ -60,3 +60,28 @@ class FileAccessorFake: FileAccessor {
return storage[path]?.mdate
}
}
extension FileAccessorFake: DirScanner {
func itemType(atPath path: String) throws -> ItemType {
if storage[path] != nil {
return .file
}
if try !recursiveItems(at: URL(fileURLWithPath: path)).isEmpty {
return .dir
}
return .nonExisting
}
func items(at dir: URL) throws -> [URL] {
storage.keys.map(URL.init(fileURLWithPath:)).filter {
$0.deletingLastPathComponent() == dir
}
}
func recursiveItems(at dir: URL) throws -> [URL] {
let paths = storage.keys.filter {
$0.hasPrefix(dir.path)
}
return paths.map(URL.init(fileURLWithPath:))
}
}
@@ -34,5 +34,11 @@ class FingerprintAccumulatorFake: FingerprintAccumulator {
appendedStrings.append("FILE{\(file.path)}")
}
func generate() throws -> RawFingerprint { return appendedStrings.joined(separator: ",") }
private(set) var generateCallsCount = 0
func generate() throws -> RawFingerprint {
defer {
generateCallsCount += 1
}
return appendedStrings.joined(separator: ",")
}
}
@@ -0,0 +1,28 @@
// Copyright (c) 2022 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
@testable import XCRemoteCache
/// No-operation processor
class NoopArtifactProcessor: ArtifactProcessor {
func process(rawArtifact url: URL) throws {}
func process(localArtifact url: URL) throws {}
}
@@ -39,7 +39,7 @@ class SwiftcProductsGeneratorFake: SwiftcProductsGenerator {
func generateFrom(
artifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL {
) throws -> SwiftcProductsGeneratorOutput {
let swiftmoduleDestBasename = swiftmoduleDest.deletingPathExtension()
for (ext, url) in artifactSwiftModuleFiles {
try dirAccessor.write(
@@ -51,6 +51,9 @@ class SwiftcProductsGeneratorFake: SwiftcProductsGenerator {
toPath: swiftmoduleObjCFile.path,
contents: dirAccessor.contents(atPath: artifactSwiftModuleObjCFile.path)
)
return swiftmoduleDest.deletingLastPathComponent()
return SwiftcProductsGeneratorOutput(
swiftmoduleDir: swiftmoduleDest.deletingLastPathComponent(),
objcHeaderFile: swiftmoduleObjCFile
)
}
}
@@ -22,16 +22,16 @@ import Foundation
class SwiftcProductsGeneratorSpy: SwiftcProductsGenerator {
private(set) var generated: [([SwiftmoduleFileExtension: URL], URL)] = []
private let generationDestination: URL
private let generationDestination: SwiftcProductsGeneratorOutput
init(generatedDestination: URL = "") {
init(generatedDestination: SwiftcProductsGeneratorOutput) {
generationDestination = generatedDestination
}
func generateFrom(
artifactSwiftModuleFiles: [SwiftmoduleFileExtension: URL],
artifactSwiftModuleObjCFile: URL
) throws -> URL {
) throws -> SwiftcProductsGeneratorOutput {
generated.append((
artifactSwiftModuleFiles,
artifactSwiftModuleObjCFile
@@ -0,0 +1,66 @@
// Copyright (c) 2023 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
@testable import xclibtoolSupport
import XCTest
class XCLibtoolHelperTests: XCTestCase {
func testStaticFrameworkUniversalBinary() throws {
let mode = try XCLibtoolHelper.buildMode(
args: ["-o", "/universal/static", "/arch1/static", "arch2/static"]
)
XCTAssertEqual(mode, .createUniversalBinary(
output: "/universal/static",
inputs: ["/arch1/static", "arch2/static"]
))
}
func testStaticLibraryUniversalBinary() throws {
let mode = try XCLibtoolHelper.buildMode(
args: ["-o", "/universal/static.a", "/arch1/static.a", "arch2/static.a"]
)
XCTAssertEqual(mode, .createUniversalBinary(
output: "/universal/static.a",
inputs: ["/arch1/static.a", "arch2/static.a"]
))
}
func testUnknownExtensionInputThrowsUnsupportedMode() throws {
XCTAssertThrowsError(
try XCLibtoolHelper.buildMode(args: ["-o", "/universal/static.a", "/arch1/static.unknown"])) { error in
switch error {
case XCLibtoolHelperError.unsupportedMode: break
default:
XCTFail("Not expected error")
}
}
}
func testMissingOutputThrowsMissingOutput() throws {
XCTAssertThrowsError(try XCLibtoolHelper.buildMode(args: ["/arch1/static"])) { error in
switch error {
case XCLibtoolHelperError.missingOutput: break
default:
XCTFail("Not expected error")
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: XCRemoteCache
spec:
type: library
owner: foundation
@@ -127,6 +127,8 @@ module CocoapodsXCRemoteCacheModifier
config.build_settings['SWIFT_EXEC'] = ["$SRCROOT/#{srcroot_relative_xc_location}/xcswiftc"]
config.build_settings['LIBTOOL'] = ["$SRCROOT/#{srcroot_relative_xc_location}/xclibtool"]
config.build_settings['LD'] = ["$SRCROOT/#{srcroot_relative_xc_location}/xcld"]
config.build_settings['LDPLUSPLUS'] = ["$SRCROOT/#{srcroot_relative_xc_location}/xcldplusplus"]
config.build_settings['SWIFT_USE_INTEGRATED_DRIVER'] = ['NO']
config.build_settings['XCREMOTE_CACHE_FAKE_SRCROOT'] = fake_src_root
config.build_settings['XCRC_PLATFORM_PREFERRED_ARCH'] = ["$(LINK_FILE_LIST_$(CURRENT_VARIANT)_$(PLATFORM_PREFERRED_ARCH):dir:standardizepath:file:default=arm64)"]
@@ -181,6 +183,11 @@ module CocoapodsXCRemoteCacheModifier
"$(TARGET_BUILD_DIR)/$(MODULES_FOLDER_PATH)/$(PRODUCT_MODULE_NAME).swiftmodule/$(XCRC_PLATFORM_PREFERRED_ARCH)-$(LLVM_TARGET_TRIPLE_VENDOR)-$(SWIFT_PLATFORM_TARGET_PREFIX)$(LLVM_TARGET_TRIPLE_SUFFIX).swiftmodule.md5"
]
postbuild_script.dependency_file = "$(TARGET_TEMP_DIR)/postbuild.d"
# Move postbuild (last element) to the position after compile sources phase (to make it real 'postbuild')
if !existing_postbuild_script
compile_phase_index = target.build_phases.index(target.source_build_phase)
target.build_phases.insert(compile_phase_index + 1, target.build_phases.delete(postbuild_script))
end
# Mark a sha as ready for a given platform and configuration when building the final_target
if (mode == 'producer' || mode == 'producer-fast') && target.name == final_target
@@ -208,6 +215,8 @@ module CocoapodsXCRemoteCacheModifier
config.build_settings.delete('SWIFT_EXEC') if config.build_settings.key?('SWIFT_EXEC')
config.build_settings.delete('LIBTOOL') if config.build_settings.key?('LIBTOOL')
config.build_settings.delete('LD') if config.build_settings.key?('LD')
config.build_settings.delete('LDPLUSPLUS') if config.build_settings.key?('LDPLUSPLUS')
config.build_settings.delete('SWIFT_USE_INTEGRATED_DRIVER') if config.build_settings.key?('SWIFT_USE_INTEGRATED_DRIVER')
# Remove Fake src root for ObjC & Swift
config.build_settings.delete('XCREMOTE_CACHE_FAKE_SRCROOT')
config.build_settings.delete('XCRC_PLATFORM_PREFERRED_ARCH')
@@ -231,7 +240,7 @@ module CocoapodsXCRemoteCacheModifier
end
def self.download_xcrc_if_needed(local_location)
required_binaries = ['xcld', 'xclibtool', 'xcpostbuild', 'xcprebuild', 'xcprepare', 'xcswiftc']
required_binaries = ['xcld', 'xcldplusplus', 'xclibtool', 'xcpostbuild', 'xcprebuild', 'xcprepare', 'xcswiftc']
binaries_exist = required_binaries.reduce(true) do |exists, filename|
file_path = File.join(local_location, filename)
exists = exists && File.exist?(file_path)
@@ -353,12 +362,73 @@ module CocoapodsXCRemoteCacheModifier
File.write(LLDB_INIT_PATH, lldbinit_lines.join("\n"), mode: "w")
end
Pod::HooksManager.register('cocoapods-xcremotecache', :post_install) do |installer_context|
Pod::HooksManager.register('cocoapods-xcremotecache', :pre_install) do |installer_context|
# The main responsibility of that hook is forcing Pods regeneration when XCRemoteCache is enabled for the first time
# In the post_install hook, this plugin adds extra build settings and steps to all Pods targets, but only when XCRemoteCache
# is enabled and all artifacts are available (i.e. xcprepare returns 0).
# If Pods projects/targets are cached from previous `pod install` action that didn't enable XCRemoteCache (e.g. artifacts
# are not available in the remote cache), these projects/targets should be invalidated to include XCRemoteCache-related
# build steps and build settings.
if @@configuration.nil?
Pod::UI.puts "[XCRC] Warning! XCRemoteCache not configured. Call xcremotecache({...}) in Podfile to enable XCRemoteCache"
next
end
begin
# `user_pod_directory`` and `user_proj_directory` in the 'postinstall' should be equal
user_pod_directory = File.dirname(installer_context.podfile.defined_in_file)
set_configuration_default_values
unless @@configuration['enabled']
# No need to check if enabling remote cache for the first time
next
end
validate_configuration()
mode = @@configuration['mode']
remote_commit_file = @@configuration['remote_commit_file']
xcrc_location = @@configuration['xcrc_location']
check_build_configuration = @@configuration['check_build_configuration']
check_platform = @@configuration['check_platform']
xcrc_location_absolute = "#{user_pod_directory}/#{xcrc_location}"
remote_commit_file_absolute = "#{user_pod_directory}/#{remote_commit_file}"
# Download XCRC
download_xcrc_if_needed(xcrc_location_absolute)
# Save .rcinfo
root_rcinfo = generate_rcinfo()
save_rcinfo(root_rcinfo, user_pod_directory)
# Create directory for xccc & arc.rc location
Dir.mkdir(BIN_DIR) unless File.exist?(BIN_DIR)
# Remove previous xccc & arc.rc
was_previously_enabled = File.exist?(remote_commit_file_absolute)
File.delete(remote_commit_file_absolute) if File.exist?(remote_commit_file_absolute)
prepare_result = YAML.load`#{xcrc_location_absolute}/xcprepare --configuration #{check_build_configuration} --platform #{check_platform}`
if !prepare_result['result'] && mode == 'consumer'
# Remote cache is still disabled - no need to force Pods projects/targets regeneration
next
end
# Force rebuilding all Pods project, because XCRC build steps and settings need to be added to Pods project/targets
# It is relevant only when 'incremental_installation' is enabled, otherwise installed_cache_path does not exist on a disk
installed_cache_path = installer_context.sandbox.project_installation_cache_path
if !was_previously_enabled && File.exist?(installed_cache_path)
Pod::UI.puts "[XCRC] Forces Pods project regenerations because XCRC is enabled for the first time."
File.delete(installed_cache_path)
end
end
end
Pod::HooksManager.register('cocoapods-xcremotecache', :post_install) do |installer_context|
if @@configuration.nil?
next
end
user_project = installer_context.umbrella_targets[0].user_project
begin
@@ -385,20 +455,12 @@ module CocoapodsXCRemoteCacheModifier
xccc_location_absolute = "#{user_proj_directory}/#{xccc_location}"
xcrc_location_absolute = "#{user_proj_directory}/#{xcrc_location}"
remote_commit_file_absolute = "#{user_proj_directory}/#{remote_commit_file}"
# Download XCRC
download_xcrc_if_needed(xcrc_location_absolute)
# Save .rcinfo
root_rcinfo = generate_rcinfo()
save_rcinfo(root_rcinfo, user_proj_directory)
# Create directory for xccc & arc.rc location
Dir.mkdir(BIN_DIR) unless File.exist?(BIN_DIR)
# Remove previous xccc & arc.rc
File.delete(remote_commit_file_absolute) if File.exist?(remote_commit_file_absolute)
# Remove previous xccc
File.delete(xccc_location_absolute) if File.exist?(xccc_location_absolute)
# Prepare XCRC
@@ -449,6 +511,7 @@ module CocoapodsXCRemoteCacheModifier
# Enabled/disable XCRemoteCache for the main (user) project
begin
# TODO: Do not compile xcc again. `xcprepare` compiles it in pre-install anyway
prepare_result = YAML.load`#{xcrc_location_absolute}/xcprepare --configuration #{check_build_configuration} --platform #{check_platform}`
unless prepare_result['result'] || mode != 'consumer'
# Uninstall the XCRemoteCache for the consumer mode
@@ -13,5 +13,5 @@
# limitations under the License.
module CocoapodsXcremotecache
VERSION = "0.0.12"
VERSION = "0.0.14"
end
+8
View File
@@ -0,0 +1,8 @@
---
cache_addresses:
- 'http://localhost:8080/cache/pods'
primary_repo: '.'
primary_branch: 'e2e-test-branch'
mode: 'consumer'
final_target': XCRemoteCacheSample'
artifact_maximum_age: 0 # do not use local cache in ~/Library/Caches/XCRemoteCache
@@ -0,0 +1,5 @@
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "SomeObjC.h"
@@ -0,0 +1,6 @@
import Foundation
@objc
public class SomeClass: NSObject {
@objc public var someEnum: SomeEnum = .default
}
@@ -0,0 +1,10 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, SomeEnum) {
SomeEnumDefault
};
NS_ASSUME_NONNULL_END
@@ -0,0 +1,725 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 55;
objects = {
/* Begin PBXBuildFile section */
36201A102843B3C3002FF70F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36201A0F2843B3C3002FF70F /* AppDelegate.swift */; };
36201A122843B3C3002FF70F /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36201A112843B3C3002FF70F /* SceneDelegate.swift */; };
36201A142843B3C3002FF70F /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36201A132843B3C3002FF70F /* ViewController.swift */; };
36201A172843B3C3002FF70F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 36201A152843B3C3002FF70F /* Main.storyboard */; };
36201A192843B3C7002FF70F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 36201A182843B3C7002FF70F /* Assets.xcassets */; };
36201A1C2843B3C7002FF70F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 36201A1A2843B3C7002FF70F /* LaunchScreen.storyboard */; };
36201A2A2843B3D3002FF70F /* MixedTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36201A292843B3D3002FF70F /* MixedTarget.swift */; };
36201A362843B435002FF70F /* libMixedTarget.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 36201A272843B3D3002FF70F /* libMixedTarget.a */; };
36201A392843BDDC002FF70F /* StandaloneObjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 36201A382843BDDC002FF70F /* StandaloneObjc.m */; };
4EE6CF4929B6C1A000AEE1B4 /* StaticFramework.h in Headers */ = {isa = PBXBuildFile; fileRef = 4EE6CF4829B6C1A000AEE1B4 /* StaticFramework.h */; settings = {ATTRIBUTES = (Public, ); }; };
4EE6CF5329B6C1AF00AEE1B4 /* StaticFrameworkFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EE6CF5229B6C1AF00AEE1B4 /* StaticFrameworkFile.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
36201A332843B431002FF70F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 36201A042843B3C3002FF70F /* Project object */;
proxyType = 1;
remoteGlobalIDString = 36201A262843B3D3002FF70F;
remoteInfo = MixedTarget;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
36201A252843B3D3002FF70F /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "include/$(PRODUCT_NAME)";
dstSubfolderSpec = 16;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
4EE6CF4E29B6C1A000AEE1B4 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
36201A0C2843B3C3002FF70F /* StandaloneApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = StandaloneApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
36201A0F2843B3C3002FF70F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
36201A112843B3C3002FF70F /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
36201A132843B3C3002FF70F /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
36201A162843B3C3002FF70F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
36201A182843B3C7002FF70F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
36201A1B2843B3C7002FF70F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
36201A1D2843B3C7002FF70F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
36201A272843B3D3002FF70F /* libMixedTarget.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libMixedTarget.a; sourceTree = BUILT_PRODUCTS_DIR; };
36201A292843B3D3002FF70F /* MixedTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MixedTarget.swift; sourceTree = "<group>"; };
36201A2F2843B413002FF70F /* MixedTarget-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MixedTarget-Bridging-Header.h"; sourceTree = "<group>"; };
36201A302843B414002FF70F /* SomeObjC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SomeObjC.h; sourceTree = "<group>"; };
36201A372843BDDC002FF70F /* StandaloneObjc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = StandaloneObjc.h; sourceTree = "<group>"; };
36201A382843BDDC002FF70F /* StandaloneObjc.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = StandaloneObjc.m; sourceTree = "<group>"; };
4E628CA229B8066500AF2DB0 /* SandaloneWatchAppExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SandaloneWatchAppExtension.swift; sourceTree = "<group>"; };
4E628CA429B8066500AF2DB0 /* SandaloneWatchApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SandaloneWatchApp.swift; sourceTree = "<group>"; };
4E628CA629B8066500AF2DB0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
4EE6CF4629B6C1A000AEE1B4 /* StaticFramework.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = StaticFramework.framework; sourceTree = BUILT_PRODUCTS_DIR; };
4EE6CF4829B6C1A000AEE1B4 /* StaticFramework.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = StaticFramework.h; sourceTree = "<group>"; };
4EE6CF5229B6C1AF00AEE1B4 /* StaticFrameworkFile.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StaticFrameworkFile.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
36201A092843B3C3002FF70F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
36201A362843B435002FF70F /* libMixedTarget.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
36201A242843B3D3002FF70F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
4EE6CF4329B6C1A000AEE1B4 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
36201A032843B3C3002FF70F = {
isa = PBXGroup;
children = (
36201A0E2843B3C3002FF70F /* StandaloneApp */,
36201A282843B3D3002FF70F /* MixedTarget */,
4EE6CF4729B6C1A000AEE1B4 /* StaticFramework */,
4E628CA129B8066500AF2DB0 /* SandaloneWatchApp */,
36201A0D2843B3C3002FF70F /* Products */,
36201A352843B435002FF70F /* Frameworks */,
);
sourceTree = "<group>";
};
36201A0D2843B3C3002FF70F /* Products */ = {
isa = PBXGroup;
children = (
36201A0C2843B3C3002FF70F /* StandaloneApp.app */,
36201A272843B3D3002FF70F /* libMixedTarget.a */,
4EE6CF4629B6C1A000AEE1B4 /* StaticFramework.framework */,
);
name = Products;
sourceTree = "<group>";
};
36201A0E2843B3C3002FF70F /* StandaloneApp */ = {
isa = PBXGroup;
children = (
36201A0F2843B3C3002FF70F /* AppDelegate.swift */,
36201A112843B3C3002FF70F /* SceneDelegate.swift */,
36201A132843B3C3002FF70F /* ViewController.swift */,
36201A152843B3C3002FF70F /* Main.storyboard */,
36201A182843B3C7002FF70F /* Assets.xcassets */,
36201A1A2843B3C7002FF70F /* LaunchScreen.storyboard */,
36201A1D2843B3C7002FF70F /* Info.plist */,
36201A372843BDDC002FF70F /* StandaloneObjc.h */,
36201A382843BDDC002FF70F /* StandaloneObjc.m */,
);
path = StandaloneApp;
sourceTree = "<group>";
};
36201A282843B3D3002FF70F /* MixedTarget */ = {
isa = PBXGroup;
children = (
36201A292843B3D3002FF70F /* MixedTarget.swift */,
36201A302843B414002FF70F /* SomeObjC.h */,
36201A2F2843B413002FF70F /* MixedTarget-Bridging-Header.h */,
);
path = MixedTarget;
sourceTree = "<group>";
};
36201A352843B435002FF70F /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
4E628CA129B8066500AF2DB0 /* SandaloneWatchApp */ = {
isa = PBXGroup;
children = (
4E628CA229B8066500AF2DB0 /* SandaloneWatchAppExtension.swift */,
4E628CA429B8066500AF2DB0 /* SandaloneWatchApp.swift */,
4E628CA629B8066500AF2DB0 /* Info.plist */,
);
path = SandaloneWatchApp;
sourceTree = "<group>";
};
4EE6CF4729B6C1A000AEE1B4 /* StaticFramework */ = {
isa = PBXGroup;
children = (
4EE6CF5229B6C1AF00AEE1B4 /* StaticFrameworkFile.swift */,
4EE6CF4829B6C1A000AEE1B4 /* StaticFramework.h */,
);
path = StaticFramework;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
4EE6CF4129B6C1A000AEE1B4 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
4EE6CF4929B6C1A000AEE1B4 /* StaticFramework.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
36201A0B2843B3C3002FF70F /* StandaloneApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 36201A202843B3C7002FF70F /* Build configuration list for PBXNativeTarget "StandaloneApp" */;
buildPhases = (
36201A082843B3C3002FF70F /* Sources */,
36201A092843B3C3002FF70F /* Frameworks */,
36201A0A2843B3C3002FF70F /* Resources */,
4EE6CF4E29B6C1A000AEE1B4 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
36201A342843B431002FF70F /* PBXTargetDependency */,
);
name = StandaloneApp;
productName = StandaloneApp;
productReference = 36201A0C2843B3C3002FF70F /* StandaloneApp.app */;
productType = "com.apple.product-type.application";
};
36201A262843B3D3002FF70F /* MixedTarget */ = {
isa = PBXNativeTarget;
buildConfigurationList = 36201A2B2843B3D3002FF70F /* Build configuration list for PBXNativeTarget "MixedTarget" */;
buildPhases = (
36201A232843B3D3002FF70F /* Sources */,
36201A242843B3D3002FF70F /* Frameworks */,
36201A252843B3D3002FF70F /* CopyFiles */,
36201A3A2843BE0E002FF70F /* Copy Swift Objective-C Interface Header */,
);
buildRules = (
);
dependencies = (
);
name = MixedTarget;
productName = MixedTarget;
productReference = 36201A272843B3D3002FF70F /* libMixedTarget.a */;
productType = "com.apple.product-type.library.static";
};
4EE6CF4529B6C1A000AEE1B4 /* StaticFramework */ = {
isa = PBXNativeTarget;
buildConfigurationList = 4EE6CF5129B6C1A000AEE1B4 /* Build configuration list for PBXNativeTarget "StaticFramework" */;
buildPhases = (
4EE6CF4129B6C1A000AEE1B4 /* Headers */,
4EE6CF4229B6C1A000AEE1B4 /* Sources */,
4EE6CF4329B6C1A000AEE1B4 /* Frameworks */,
4EE6CF4429B6C1A000AEE1B4 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = StaticFramework;
productName = StaticFramework;
productReference = 4EE6CF4629B6C1A000AEE1B4 /* StaticFramework.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
36201A042843B3C3002FF70F /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1420;
LastUpgradeCheck = 1320;
TargetAttributes = {
36201A0B2843B3C3002FF70F = {
CreatedOnToolsVersion = 13.2.1;
LastSwiftMigration = 1320;
};
36201A262843B3D3002FF70F = {
CreatedOnToolsVersion = 13.2.1;
LastSwiftMigration = 1320;
};
4EE6CF4529B6C1A000AEE1B4 = {
CreatedOnToolsVersion = 14.2;
LastSwiftMigration = 1420;
};
};
};
buildConfigurationList = 36201A072843B3C3002FF70F /* Build configuration list for PBXProject "StandaloneApp" */;
compatibilityVersion = "Xcode 13.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 36201A032843B3C3002FF70F;
productRefGroup = 36201A0D2843B3C3002FF70F /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
36201A0B2843B3C3002FF70F /* StandaloneApp */,
36201A262843B3D3002FF70F /* MixedTarget */,
4EE6CF4529B6C1A000AEE1B4 /* StaticFramework */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
36201A0A2843B3C3002FF70F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
36201A1C2843B3C7002FF70F /* LaunchScreen.storyboard in Resources */,
36201A192843B3C7002FF70F /* Assets.xcassets in Resources */,
36201A172843B3C3002FF70F /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
4EE6CF4429B6C1A000AEE1B4 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
36201A3A2843BE0E002FF70F /* Copy Swift Objective-C Interface Header */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)",
"$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME).md5",
);
name = "Copy Swift Objective-C Interface Header";
outputFileListPaths = (
);
outputPaths = (
"$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)",
"$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME).md5",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "ditto \"${SCRIPT_INPUT_FILE_0}\" \"${SCRIPT_OUTPUT_FILE_0}\"\n[ -f \"${SCRIPT_INPUT_FILE_1}\" ] && ditto \"${SCRIPT_INPUT_FILE_1}\" \"${SCRIPT_OUTPUT_FILE_1}\" || rm \"${SCRIPT_OUTPUT_FILE_1}\"\n\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
36201A082843B3C3002FF70F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
36201A142843B3C3002FF70F /* ViewController.swift in Sources */,
36201A102843B3C3002FF70F /* AppDelegate.swift in Sources */,
36201A392843BDDC002FF70F /* StandaloneObjc.m in Sources */,
36201A122843B3C3002FF70F /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
36201A232843B3D3002FF70F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
36201A2A2843B3D3002FF70F /* MixedTarget.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
4EE6CF4229B6C1A000AEE1B4 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
4EE6CF5329B6C1AF00AEE1B4 /* StaticFrameworkFile.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
36201A342843B431002FF70F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 36201A262843B3D3002FF70F /* MixedTarget */;
targetProxy = 36201A332843B431002FF70F /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
36201A152843B3C3002FF70F /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
36201A162843B3C3002FF70F /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
36201A1A2843B3C7002FF70F /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
36201A1B2843B3C7002FF70F /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
36201A1E2843B3C7002FF70F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.2;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
36201A1F2843B3C7002FF70F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.2;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
36201A212843B3C7002FF70F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
HEADER_SEARCH_PATHS = "$(BUILT_PRODUCTS_DIR)/include/";
INFOPLIST_FILE = StandaloneApp/Info.plist;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UIMainStoryboardFile = Main;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.xcremotecache.StandaloneApp;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
36201A222843B3C7002FF70F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
HEADER_SEARCH_PATHS = "$(BUILT_PRODUCTS_DIR)/include/";
INFOPLIST_FILE = StandaloneApp/Info.plist;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
INFOPLIST_KEY_UIMainStoryboardFile = Main;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.xcremotecache.StandaloneApp;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
36201A2C2843B3D3002FF70F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OBJC_BRIDGING_HEADER = "MixedTarget/MixedTarget-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
36201A2D2843B3D3002FF70F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OBJC_BRIDGING_HEADER = "MixedTarget/MixedTarget-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
4EE6CF4F29B6C1A000AEE1B4 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 15.2;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MACH_O_TYPE = staticlib;
MARKETING_VERSION = 1.0;
ONLY_ACTIVE_ARCH = NO;
PRODUCT_BUNDLE_IDENTIFIER = com.squareup.StaticFramework;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
WATCHOS_DEPLOYMENT_TARGET = 4.0;
};
name = Debug;
};
4EE6CF5029B6C1A000AEE1B4 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 15.2;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MACH_O_TYPE = staticlib;
MARKETING_VERSION = 1.0;
ONLY_ACTIVE_ARCH = NO;
PRODUCT_BUNDLE_IDENTIFIER = com.squareup.StaticFramework;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
WATCHOS_DEPLOYMENT_TARGET = 4.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
36201A072843B3C3002FF70F /* Build configuration list for PBXProject "StandaloneApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
36201A1E2843B3C7002FF70F /* Debug */,
36201A1F2843B3C7002FF70F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
36201A202843B3C7002FF70F /* Build configuration list for PBXNativeTarget "StandaloneApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
36201A212843B3C7002FF70F /* Debug */,
36201A222843B3C7002FF70F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
36201A2B2843B3D3002FF70F /* Build configuration list for PBXNativeTarget "MixedTarget" */ = {
isa = XCConfigurationList;
buildConfigurations = (
36201A2C2843B3D3002FF70F /* Debug */,
36201A2D2843B3D3002FF70F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
4EE6CF5129B6C1A000AEE1B4 /* Build configuration list for PBXNativeTarget "StaticFramework" */ = {
isa = XCConfigurationList;
buildConfigurations = (
4EE6CF4F29B6C1A000AEE1B4 /* Debug */,
4EE6CF5029B6C1A000AEE1B4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 36201A042843B3C3002FF70F /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1420"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "4EE6CF4529B6C1A000AEE1B4"
BuildableName = "StaticFramework.framework"
BlueprintName = "StaticFramework"
ReferencedContainer = "container:StandaloneApp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "4EE6CF4529B6C1A000AEE1B4"
BuildableName = "StaticFramework.framework"
BlueprintName = "StaticFramework"
ReferencedContainer = "container:StandaloneApp.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,29 @@
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"idiom" : "ipad",
"scale" : "1x",
"size" : "20x20"
},
{
"idiom" : "ipad",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "ipad",
"scale" : "1x",
"size" : "29x29"
},
{
"idiom" : "ipad",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "ipad",
"scale" : "1x",
"size" : "40x40"
},
{
"idiom" : "ipad",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "ipad",
"scale" : "1x",
"size" : "76x76"
},
{
"idiom" : "ipad",
"scale" : "2x",
"size" : "76x76"
},
{
"idiom" : "ipad",
"scale" : "2x",
"size" : "83.5x83.5"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,45 @@
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface StandaloneObjc : NSObject
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,6 @@
#import "StandaloneObjc.h"
#import "MixedTarget/MixedTarget-Swift.h"
@implementation StandaloneObjc
@end
@@ -0,0 +1,13 @@
import UIKit
import MixedTarget
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
@@ -0,0 +1,11 @@
#import <Foundation/Foundation.h>
//! Project version number for StaticFramework.
FOUNDATION_EXPORT double StaticFrameworkVersionNumber;
//! Project version string for StaticFramework.
FOUNDATION_EXPORT const unsigned char StaticFrameworkVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <StaticFramework/PublicHeader.h>
@@ -0,0 +1,5 @@
import Foundation
public class SomeClass {
public init() {}
}
+77 -19
View File
@@ -5,6 +5,7 @@ namespace :e2e do
COCOAPODS_DIR = 'cocoapods-plugin'
COCOAPODS_GEMSPEC_FILENAME = "cocoapods-xcremotecache.gemspec"
E2E_COCOAPODS_SAMPLE_DIR = 'e2eTests/XCRemoteCacheSample'
E2E_STANDALONE_SAMPLE_DIR = 'e2eTests/StandaloneSampleApp'
GIT_REMOTE_NAME = 'self'
# Location of the remote address that points to itself
GIT_REMOTE_ADDRESS = '.'
@@ -14,7 +15,7 @@ namespace :e2e do
NGINX_ROOT_DIR = '/tmp/cache'
XCRC_BINARIES = 'XCRC'
SHARED_COCOAPODS_CONFIG = {
'cache_addresses' => ['http://localhost:8080/cache/pods'],
'cache_addresses' => ['http://localhost:8080/cache/pods'],
'primary_repo' => GIT_REMOTE_ADDRESS,
'primary_branch' => GIT_BRANCH,
'mode' => 'consumer',
@@ -25,7 +26,7 @@ namespace :e2e do
Stats = Struct.new(:hits, :misses, :hit_rate)
# run E2E tests
task :run => [:run_cocoapods]
task :run => [:run_cocoapods, :run_standalone]
# run E2E tests for CocoaPods-powered projects
task :run_cocoapods do
@@ -41,6 +42,53 @@ namespace :e2e do
clean
end
# run E2E tests for standalone (non-CocoaPods) projects
task :run_standalone do
clean_server
start_nginx
configure_git
# Prepare binaries for the standalone mode
prepare_for_standalone(E2E_STANDALONE_SAMPLE_DIR)
puts 'Building standalone producer...'
####### Producer #########
Dir.chdir(E2E_STANDALONE_SAMPLE_DIR) do
clean_git
# Run integrate the project
system("pwd")
system("#{XCRC_BINARIES}/xcprepare integrate --input StandaloneApp.xcodeproj --mode producer --final-producer-target StandaloneApp")
# Build the project to fill in the cache
build_project(nil, "StandaloneApp.xcodeproj", 'StaticFramework', 'watch', 'watchOS')
build_project(nil, "StandaloneApp.xcodeproj", 'StandaloneApp')
system("#{XCRC_BINARIES}/xcprepare stats --reset --format json")
end
puts 'Building standalone consumer...'
####### Consumer #########
# new dir to emulate different srcroot
consumer_srcroot = "#{E2E_STANDALONE_SAMPLE_DIR}_consumer"
system("mv #{E2E_STANDALONE_SAMPLE_DIR} #{consumer_srcroot}")
at_exit { puts("reverting #{E2E_STANDALONE_SAMPLE_DIR}"); system("mv #{consumer_srcroot} #{E2E_STANDALONE_SAMPLE_DIR}") }
prepare_for_standalone(consumer_srcroot)
Dir.chdir(consumer_srcroot) do
system("#{XCRC_BINARIES}/xcprepare integrate --input StandaloneApp.xcodeproj --mode consumer")
build_project(nil, "StandaloneApp.xcodeproj", 'StaticFramework', 'watch', 'watchOS', {'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer"})
build_project(nil, "StandaloneApp.xcodeproj", 'StandaloneApp', 'iphone', 'iOS', {'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer"})
valide_hit_rate
puts 'Building standalone consumer with local change...'
# Extra: validate local compilation of the Standalone ObjC code
system("echo '' >> StandaloneApp/StandaloneObjc.m")
build_project(nil, "StandaloneApp.xcodeproj", 'StaticFramework', 'watch', 'watchOS', {'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer_local"})
build_project(nil, "StandaloneApp.xcodeproj", 'StandaloneApp', 'iphone', 'iOS', {'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer_local"})
end
# Revert all side effects
clean
end
# Build and install a plugin
def self.install_cocoapods_plugin
Dir.chdir(COCOAPODS_DIR) do
@@ -58,7 +106,7 @@ namespace :e2e do
at_exit { puts('resetting ngingx'); system('nginx -s stop') }
end
# Create a new branch out of a current commit and
# Create a new branch out of a current commit and
# add remote that points to itself
def self.configure_git
system("git checkout -B #{GIT_BRANCH}")
@@ -99,7 +147,7 @@ namespace :e2e do
def self.cocoapods_configuration_string(extra_configs = {})
configuration_lines = ['xcremotecache({']
all_properties = SHARED_COCOAPODS_CONFIG.merge(extra_configs)
config_lines = all_properties.map {|key, value| " \"#{key}\" => #{value.inspect},"}
config_lines = all_properties.map {|key, value| " \"#{key}\" => #{value.inspect},"}
configuration_lines.push(*config_lines)
configuration_lines << '})'
configuration_lines.join("\n")
@@ -114,24 +162,24 @@ namespace :e2e do
end
end
def self.build_project(extra_args = {})
system('pod install')
def self.build_project(workspace, project, scheme, sdk = 'iphone', platform = 'iOS', extra_args = {})
xcodebuild_args = {
'workspace' => 'XCRemoteCacheSample.xcworkspace',
'scheme' => 'XCRemoteCacheSample',
'workspace' => workspace,
'project' => project,
'scheme' => scheme,
'configuration' => 'Debug',
'sdk' => 'iphonesimulator',
'destination' => 'generic/platform=iOS Simulator',
'sdk' => "#{sdk}simulator",
'destination' => "generic/platform=#{platform} Simulator",
'derivedDataPath' => DERIVED_DATA_PATH,
}.merge(extra_args)
}.merge(extra_args).compact
xcodebuild_vars = {
'EXCLUDED_ARCHS' => 'arm64 i386'
'EXCLUDED_ARCHS' => 'arm64'
}
args = ['xcodebuild']
args = ['set -o pipefail;', 'xcodebuild']
args.push(*xcodebuild_args.map {|k,v| "-#{k} '#{v}'"})
args.push(*xcodebuild_vars.map {|k,v| "#{k}='#{v}'"})
args.push('clean build')
args.push("> #{LOG_NAME}")
args.push("| tee #{LOG_NAME}")
puts 'Building a project with xcodebuild...'
system(args.join(' '))
unless $?.success?
@@ -140,7 +188,12 @@ namespace :e2e do
end
end
def self.read_stats
def self.build_project_cocoapods(sdk = 'iphone', platform = 'iOS', extra_args = {})
system('pod install')
build_project('XCRemoteCacheSample.xcworkspace', nil, 'XCRemoteCacheSample', sdk, platform, extra_args)
end
def self.read_stats
stats_json_string = JSON.parse(`#{XCRC_BINARIES}/xcprepare stats --format json`)
misses = stats_json_string.fetch('miss_count', 0)
hits = stats_json_string.fetch('hit_count', 0)
@@ -153,8 +206,8 @@ namespace :e2e do
# validate 100% hit rate
def self.valide_hit_rate
status = read_stats()
raise "Failure: Hit rate is only #{status.hit_rate}% (#{status.hits}/#{status.all_targets})" if status.misses > 0
all_targets = status.misses + status.hits
raise "Failure: Hit rate is only #{status.hit_rate}% (#{all_targets})" if status.misses > 0
puts("Hit rate: #{status.hit_rate}% (#{status.hits}/#{all_targets})")
end
@@ -163,13 +216,13 @@ namespace :e2e do
consumer_configuration = cocoapods_configuration_string()
puts("****** Scenario: #{template_path}")
# Run producer build
pre_producer_setup
dump_podfile(producer_configuration, template_path)
puts('Building producer ...')
Dir.chdir(E2E_COCOAPODS_SAMPLE_DIR) do
build_project
build_project_cocoapods
# reset XCRemoteCache stats
system("#{XCRC_BINARIES}/xcprepare stats --reset --format json")
end
@@ -179,8 +232,13 @@ namespace :e2e do
dump_podfile(consumer_configuration, template_path)
puts('Building consumer ...')
Dir.chdir(E2E_COCOAPODS_SAMPLE_DIR) do
build_project({'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer"})
build_project_cocoapods('iphone', 'iOS', {'derivedDataPath' => "#{DERIVED_DATA_PATH}_consumer"})
valide_hit_rate
end
end
def self.prepare_for_standalone(dir)
clean_git
system("ln -s $(pwd)/releases #{dir}/#{XCRC_BINARIES}")
end
end