mirror of
https://github.com/xtool-org/xtool.git
synced 2026-11-21 10:45:53 +03:00
Compare commits
1 Commits
@@ -1,8 +0,0 @@
|
||||
*
|
||||
!/Package.swift
|
||||
!/Package.resolved
|
||||
!/Sources
|
||||
!/Tests
|
||||
!/Linux
|
||||
/Linux/packages
|
||||
/Linux/staging
|
||||
@@ -1,17 +0,0 @@
|
||||
## What does this PR do?
|
||||
|
||||
<!-- Focus on *what* the PR does in essence. The *how* should come second, if it's relevant. -->
|
||||
|
||||
## How was it tested?
|
||||
|
||||
<!-- e.g. Ran locally on macOS and added unit tests -->
|
||||
|
||||
## AI tool usage
|
||||
|
||||
How much of this PR was AI-assisted? (check one)
|
||||
|
||||
- [ ] **0** - No AI was used to write code
|
||||
- [ ] **1** - I was assisted by AI. I reviewed the finished result.
|
||||
- [ ] **2** - I set the AI going and left it to it; nobody has read the result - no review, or AI review only
|
||||
|
||||
<!-- If an AI agent is filling this in: declare the level honestly, and open as a draft if it is #2. Do not lower the declared level to get the PR reviewed. -->
|
||||
@@ -6,8 +6,6 @@ on:
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
XTL_CI: "1"
|
||||
jobs:
|
||||
build-linux:
|
||||
strategy:
|
||||
@@ -24,7 +22,7 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
- name: Build and test
|
||||
run: |
|
||||
docker compose run --build -e XTL_CI=1 xtool bash -c \
|
||||
docker compose run --build xtool bash -c \
|
||||
"swift build --product xtool && .build/debug/xtool --help && swift test"
|
||||
build-macos:
|
||||
runs-on: macos-26
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
concurrency:
|
||||
group: integration-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
integration-test-linux:
|
||||
# https://github.com/xtool-org/mac-actions-runner
|
||||
runs-on: ubuntu-on-macos
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
- name: Run integration tests
|
||||
run: |
|
||||
./integration-tests/run.sh
|
||||
@@ -3,9 +3,6 @@ on:
|
||||
tags:
|
||||
- "*"
|
||||
|
||||
env:
|
||||
XTL_CI: "1"
|
||||
|
||||
jobs:
|
||||
build-linux:
|
||||
strategy:
|
||||
@@ -26,7 +23,6 @@ jobs:
|
||||
run: |
|
||||
docker compose run --build \
|
||||
-e XTOOL_VERSION=${{ github.ref_name }} \
|
||||
-e XTL_CI=1 \
|
||||
--rm xtool Linux/build.sh
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -85,24 +81,3 @@ jobs:
|
||||
TAG="${{ github.ref_name }}"
|
||||
gh release create "$TAG" --draft --title "v$TAG"
|
||||
gh release upload "$TAG" output/**/*.{AppImage,AppImage.zsync,app.zip,app.dSYM.zip}
|
||||
docker:
|
||||
uses: docker/github-builder/.github/workflows/build.yml@v1
|
||||
permissions:
|
||||
contents: read # to fetch the repository content
|
||||
id-token: write # for signing attestations and cache entries with GitHub OIDC
|
||||
packages: write # to push built images to GitHub Container Registry
|
||||
with:
|
||||
build-args: |
|
||||
XTL_CI=1
|
||||
output: image
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
meta-images: |
|
||||
ghcr.io/xtool-org/xtool
|
||||
meta-tags: |
|
||||
type=semver,pattern={{version}}
|
||||
secrets:
|
||||
registry-auths: |
|
||||
- registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
# About
|
||||
|
||||
xtool is a cross-platform replacement for Xcode (including build system, provisioning, deployment).
|
||||
|
||||
The `xtool` CLI supports macOS, Linux, WSL. The lower-level XKit (provisioning and device interaction) library additionally supports iOS.
|
||||
|
||||
## Development
|
||||
|
||||
- The majority of the code is in the Swift Package. You can use `swift build` / `swift test` / etc for iteration.
|
||||
- Caveat: on macOS, xtool is distributed as an app bundle (allows entitlements like Keychain). To build the Mac app, use `make mac`. You can then invoke the CLI at `./macOS/Build/xtool`.
|
||||
- Make sure to run `make lint` (swiftlint) when you're done
|
||||
|
||||
## Conventions
|
||||
|
||||
- Use modern Swift 6. Strict concurrency is enabled.
|
||||
- Use swift-dependencies for Dependency Injection. Passing dependencies around as arguments is an anti-pattern.
|
||||
+21
-8
@@ -4,15 +4,28 @@
|
||||
|
||||
We welcome all bug reports and feature requests! Please create a [new issue](https://github.com/xtool-org/xtool/issues/new/choose) via GitHub.
|
||||
|
||||
## Code and documentation
|
||||
## Documentation
|
||||
|
||||
External contributions are very welcome. Take a look at [/Documentation/Contributing/README.md](/Documentation/Contributing/README.md) for details regarding the development process.
|
||||
The xtool documentation at <https://xtool.sh> is built with [swift-docc](https://github.com/swiftlang/swift-docc) and resides at [Documentation/xtool.docc](/Documentation/xtool.docc). It's hosted on Netlify, the configuration for which is in [netlify.toml](/netlify.toml).
|
||||
|
||||
## AI tool usage
|
||||
When editing the DocC bundle, you can preview it with `make docs-preview`.
|
||||
|
||||
You may use AI tools to assist your contributions. You are fully responsible
|
||||
for everything you submit.
|
||||
Once you make a pull request with your changes, we'll also generate a [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/) under your pull request. You can open this preview to see how the changes will look in production.
|
||||
|
||||
- **Understand it**: You must be able to explain every line of your code.
|
||||
- **Disclose it**: Pick an AI assistance level (0/1/2) in the PR template.
|
||||
- **Own it**: You are the author. If a reviewer asks "why?", you answer - not the AI. [Don't be a meat proxy.](https://dontbeameatproxy.com)
|
||||
## Code
|
||||
|
||||
When making code changes, please make sure to test them on both macOS and Linux if possible. If you can also test on Windows with WSL, that is ideal.
|
||||
|
||||
To build xtool for debugging, run `make` in the project directory. There are a few considerations depending on your host OS:
|
||||
|
||||
### macOS
|
||||
|
||||
On macOS, you'll firstly need to have Xcode set up.
|
||||
|
||||
The first time you run `make`, we'll try to detect your codesigning identity. If you have multiple, you'll see an interactive prompt to select the team you want to use. The team ID is saved to `./macOS/Support/Private-Team.xcconfig`. You can run `make team` to update it (or do so by hand).
|
||||
|
||||
After building, a symlink to the product will be created at `./macOS/Build/xtool`. We generate an Xcode project at `./macOS/XToolMac.xcodeproj` that you can open in order to work in Xcode.
|
||||
|
||||
### Linux
|
||||
|
||||
You need to have a few dependencies on Linux; see [Dockerfile](/Dockerfile) for specifics. It's often easiest to develop within Docker itself: see [Linux/README.md](/Linux/README.md) for details.
|
||||
|
||||
+17
-31
@@ -66,13 +66,23 @@ RUN cd libimobiledevice \
|
||||
&& make install DESTDIR=/prefix
|
||||
|
||||
|
||||
FROM build-base AS build-xtool-base
|
||||
FROM build-base AS build-xadi
|
||||
|
||||
RUN mkdir -p /prefix/usr/lib
|
||||
|
||||
RUN curl -fsS https://dlang.org/install.sh | bash -s ldc
|
||||
|
||||
ADD https://github.com/xtool-org/xadi.git#main /xadi
|
||||
|
||||
RUN cd xadi \
|
||||
&& /bin/bash -c 'source $(/root/dlang/install.sh ldc -a) && dub build --build=release' \
|
||||
&& cp -r bin/libxadi.so /prefix/usr/lib/libxadi.so
|
||||
|
||||
|
||||
FROM build-base
|
||||
|
||||
COPY --from=build-limd /prefix/usr /usr
|
||||
|
||||
WORKDIR /xtool
|
||||
|
||||
FROM build-xtool-base AS dev
|
||||
COPY --from=build-xadi /prefix/usr /usr
|
||||
|
||||
# Docker doesn't support FUSE
|
||||
ENV APPIMAGE_EXTRACT_AND_RUN=1
|
||||
@@ -82,30 +92,6 @@ ENV APPIMAGE_EXTRACT_AND_RUN=1
|
||||
# socat -dd TCP-LISTEN:27015,range=127.0.0.1/32,reuseaddr,fork UNIX-CLIENT:/var/run/usbmuxd
|
||||
ENV USBMUXD_SOCKET_ADDRESS=host.docker.internal:27015
|
||||
|
||||
WORKDIR /xtool
|
||||
|
||||
CMD [ "/bin/bash" ]
|
||||
|
||||
FROM dev AS dev-test
|
||||
|
||||
ENV XTL_TEST_ENV=1
|
||||
|
||||
COPY --from=bats/bats:latest /opt/bats /opt/bats
|
||||
COPY --from=bats/bats:latest /usr/lib/bats /usr/lib/bats
|
||||
RUN ln -s /opt/bats/bin/bats /usr/local/bin/bats
|
||||
|
||||
FROM build-xtool-base AS build-xtool
|
||||
|
||||
ARG XTL_CI
|
||||
|
||||
ADD Package.swift Package.resolved /xtool/
|
||||
RUN swift package resolve
|
||||
|
||||
ADD . /xtool
|
||||
RUN ./Linux/build.sh
|
||||
|
||||
FROM swift:6.3 AS xtool
|
||||
|
||||
COPY --from=build-xtool /xtool/Linux/packages/xtool-*.AppImage /xtool/xtool.AppImage
|
||||
RUN (cd /xtool && ./xtool.AppImage --appimage-extract) \
|
||||
&& mv /xtool/squashfs-root /usr/local/xtool \
|
||||
&& rm -rf /xtool \
|
||||
&& ln -s /usr/local/xtool/AppRun /usr/local/bin/xtool
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# Debugging
|
||||
|
||||
## Environment variables
|
||||
|
||||
Some environment variables that help with debugging. Use these as e.g. `XTL_FOO=1 xtool ...`
|
||||
|
||||
### General
|
||||
|
||||
- `XTL_DEBUG_ERRORS`: If xtool terminates with an error, it normally prints a user-friendly error description. Set `XTL_DEBUG_ERRORS=1` for more verbose error logging.
|
||||
|
||||
### Disk
|
||||
|
||||
- `XTL_DEBUG_TMP`: Set to `1` to log details when xtool creates/destroys temporary directories.
|
||||
- `XTL_TMPDIR`: Control the location where xtool stores temporary directories. We also respect `TMPDIR` and (on Linux) `XDG_CACHE_HOME`.
|
||||
|
||||
### Networking
|
||||
|
||||
- `XTL_DEV_LOG`: Regex. When making AppStoreConnect API requests, operation IDs that match the regex will log their response status and body. Set `XTL_DEV_LOG='.*'` to match all.
|
||||
- `XTL_DISABLE_TLS_VALIDATION`: Set to `1` to disable all TLS validation on HTTP requests. Useful when using an MITM proxy to inspect API requests. Use sparingly, since disabling TLS is generally unsafe.
|
||||
- `XTL_HTTP_PROXY`: non-Darwin only. Set to `<host>:<port>` to point the HTTP client to a proxy. e.g. `XTL_HTTP_PROXY=localhost:8080`. On Darwin (macOS/iOS), we instead use the system proxy configuration.
|
||||
@@ -1,31 +0,0 @@
|
||||
# Contributing to xtool
|
||||
|
||||
## Code
|
||||
|
||||
When making code changes, please make sure to test them on both macOS and Linux if possible. If you can also test on Windows with WSL, that is ideal.
|
||||
|
||||
To build xtool for debugging, run `make` in the project directory. There are a few considerations depending on your host OS:
|
||||
|
||||
### macOS
|
||||
|
||||
On macOS, you'll firstly need to have Xcode set up.
|
||||
|
||||
The first time you run `make`, we'll try to detect your codesigning identity. If you have multiple, you'll see an interactive prompt to select the team you want to use. The team ID is saved to `./macOS/Support/Private-Team.xcconfig`. You can run `make team` to update it (or do so by hand).
|
||||
|
||||
After building, a symlink to the product will be created at `./macOS/Build/xtool`. We generate an Xcode project at `./macOS/XToolMac.xcodeproj` that you can open in order to work in Xcode.
|
||||
|
||||
### Linux
|
||||
|
||||
You need to have a few dependencies on Linux; see [Dockerfile](/Dockerfile) for specifics. It's often easiest to develop within Docker itself: see [Linux/README.md](/Linux/README.md) for details.
|
||||
|
||||
## Debugging
|
||||
|
||||
Check out [./Debugging.md](./Debugging.md) for help with debugging xtool issues during development.
|
||||
|
||||
## Updating Documentation
|
||||
|
||||
The xtool documentation at <https://xtool.sh> is built with [swift-docc](https://github.com/swiftlang/swift-docc) and resides at [Documentation/xtool.docc](/Documentation/xtool.docc). It's hosted on Netlify, the configuration for which is in [netlify.toml](/netlify.toml).
|
||||
|
||||
When editing the DocC bundle, you can preview it with `make docs-preview`.
|
||||
|
||||
Once you make a pull request with your changes, we'll also generate a [Netlify Deploy Preview](https://docs.netlify.com/site-deploys/deploy-previews/) under your pull request. You can open this preview to see how the changes will look in production.
|
||||
@@ -22,5 +22,4 @@ else
|
||||
fi
|
||||
|
||||
"$docc" "$command" xtool.docc \
|
||||
--enable-experimental-code-block-annotations \
|
||||
--experimental-enable-custom-templates
|
||||
|
||||
@@ -14,12 +14,6 @@ If you're on Windows, you can use xtool via [Windows Subsystem for Linux](https:
|
||||
|
||||
Once you install WSL, you'll also need to set up USB passthrough. See Microsoft's instructions on [installing USBIPD](https://learn.microsoft.com/en-us/windows/wsl/connect-usb). Make sure you're able to bind your iOS device to WSL via USB.
|
||||
|
||||
> Note:
|
||||
>
|
||||
> If you encounter `Error: AFCClient.Error.muxError`, follow the steps described in [this issue comment](https://github.com/xtool-org/xtool/issues/19#issuecomment-2898986718) from user rena2019.
|
||||
>
|
||||
> This relays the device connection from iTunes on Windows, instead of relying on USBIPD.
|
||||
|
||||
### Swift
|
||||
|
||||
Install the Swift 6.3 toolchain for your Linux distribution from <https://swift.org/install/linux>.
|
||||
|
||||
@@ -56,10 +56,6 @@ linux-clean:
|
||||
linux-dist:
|
||||
docker compose run --build --rm xtool Linux/build.sh
|
||||
|
||||
.PHONY: docker
|
||||
docker:
|
||||
docker build . -t ghcr.io/xtool-org/xtool:latest
|
||||
|
||||
.PHONY: mac
|
||||
# dev build for macOS
|
||||
mac: project
|
||||
|
||||
+1
-10
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "699acd851f15c2680059dd4a90ef6f0aca240fda0f5bdda5ec4156ff0df44adf",
|
||||
"originHash" : "80db0cddb0e78cf6a4c79f94537cdfebd8004679161532fbae8a57ee9d1d8cd1",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "aexml",
|
||||
@@ -424,15 +424,6 @@
|
||||
"version" : "2.16.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "xadi",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/xtool-org/xadi",
|
||||
"state" : {
|
||||
"revision" : "831f8ddfc72f7a48d0c2c03ac9c864eee1f8f6b3",
|
||||
"version" : "0.4.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "xcodegen",
|
||||
"kind" : "remoteSourceControl",
|
||||
|
||||
+10
-27
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:6.2
|
||||
// swift-tools-version:6.0
|
||||
|
||||
import PackageDescription
|
||||
|
||||
@@ -19,14 +19,6 @@ let cSettings: [CSetting] = [
|
||||
.define("_GNU_SOURCE", .when(platforms: [.linux])),
|
||||
]
|
||||
|
||||
let swiftSettings: [SwiftSetting] = {
|
||||
var settings: [SwiftSetting] = []
|
||||
if Context.environment["XTL_CI"] == "1" {
|
||||
settings.append(.treatAllWarnings(as: .error))
|
||||
}
|
||||
return settings
|
||||
}()
|
||||
|
||||
let package = Package(
|
||||
name: "xtool",
|
||||
platforms: [
|
||||
@@ -51,7 +43,6 @@ let package = Package(
|
||||
.package(url: "https://github.com/xtool-org/xtool-core", .upToNextMinor(from: "1.4.0")),
|
||||
.package(url: "https://github.com/xtool-org/SwiftyMobileDevice", .upToNextMinor(from: "1.5.0")),
|
||||
.package(url: "https://github.com/xtool-org/zsign", .upToNextMinor(from: "1.7.0")),
|
||||
.package(url: "https://github.com/xtool-org/xadi", .upToNextMinor(from: "0.4.0")),
|
||||
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
|
||||
.package(url: "https://github.com/apple/swift-http-types", from: "1.3.1"),
|
||||
@@ -82,6 +73,7 @@ let package = Package(
|
||||
.package(url: "https://github.com/yonaskolb/XcodeGen", from: "2.45.4"),
|
||||
],
|
||||
targets: [
|
||||
.systemLibrary(name: "XADI"),
|
||||
.target(
|
||||
name: "CXKit",
|
||||
dependencies: [
|
||||
@@ -98,8 +90,7 @@ let package = Package(
|
||||
dependencies: [
|
||||
.product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
|
||||
],
|
||||
exclude: ["openapi-generator-config.yaml", "patch.js"],
|
||||
swiftSettings: swiftSettings,
|
||||
exclude: ["openapi-generator-config.yaml", "patch.js"]
|
||||
),
|
||||
// common utilities shared across xtool targets
|
||||
.target(
|
||||
@@ -111,8 +102,7 @@ let package = Package(
|
||||
package: "swift-subprocess",
|
||||
condition: .when(platforms: [.linux, .macOS])
|
||||
),
|
||||
],
|
||||
swiftSettings: swiftSettings,
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "XKit",
|
||||
@@ -120,7 +110,7 @@ let package = Package(
|
||||
"DeveloperAPI",
|
||||
"CXKit",
|
||||
"XUtils",
|
||||
.product(name: "XADI", package: "xadi", condition: .when(platforms: [.linux])),
|
||||
.byName(name: "XADI", condition: .when(platforms: [.linux])),
|
||||
.product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"),
|
||||
.product(name: "Dependencies", package: "swift-dependencies"),
|
||||
.product(name: "SwiftyMobileDevice", package: "SwiftyMobileDevice"),
|
||||
@@ -151,16 +141,13 @@ let package = Package(
|
||||
condition: .when(platforms: [.linux])
|
||||
),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings,
|
||||
cSettings: cSettings
|
||||
),
|
||||
.testTarget(
|
||||
name: "XToolTests",
|
||||
dependencies: [
|
||||
"XKit",
|
||||
"XToolSupport",
|
||||
],
|
||||
swiftSettings: swiftSettings,
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "XToolSupport",
|
||||
@@ -174,18 +161,15 @@ let package = Package(
|
||||
.product(name: "Version", package: "Version"),
|
||||
.product(name: "libunxip", package: "unxip"),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings,
|
||||
cSettings: cSettings
|
||||
),
|
||||
.target(
|
||||
name: "PackLib",
|
||||
dependencies: [
|
||||
"XUtils",
|
||||
.product(name: "Superutils", package: "xtool-core"),
|
||||
.product(name: "Yams", package: "Yams"),
|
||||
.product(name: "XcodeGenKit", package: "XcodeGen", condition: .when(platforms: [.macOS])),
|
||||
],
|
||||
swiftSettings: swiftSettings,
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
name: "xtool",
|
||||
@@ -194,8 +178,7 @@ let package = Package(
|
||||
"XKit",
|
||||
"XToolSupport",
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings,
|
||||
cSettings: cSettings
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import Foundation
|
||||
import XUtils
|
||||
import Subprocess
|
||||
import Superutils
|
||||
|
||||
public struct DarwinSDK {
|
||||
package struct TemporaryBundle: ~Copyable {
|
||||
package let url: URL
|
||||
|
||||
fileprivate init(url: URL) {
|
||||
self.url = url
|
||||
}
|
||||
|
||||
package consuming func install() async throws {
|
||||
guard DarwinSDK(bundle: url) != nil else {
|
||||
throw StringError("Invalid Darwin SDK at '\(url.path)'")
|
||||
}
|
||||
|
||||
try await DarwinSDK.addHostClangResourceDir(to: url)
|
||||
|
||||
let destination = url.deletingLastPathComponent()
|
||||
.appendingPathComponent("darwin.artifactbundle", isDirectory: true)
|
||||
try FileManager.default.moveItem(at: url, to: destination)
|
||||
}
|
||||
|
||||
deinit {
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
}
|
||||
|
||||
public enum Flavor {
|
||||
// can't be updated in place
|
||||
case slim
|
||||
// can be updated in place, includes a whole copy of Xcode.app
|
||||
case normal
|
||||
// from before the slim/normal split existed (version "develop")
|
||||
case legacy
|
||||
}
|
||||
|
||||
public let bundle: URL
|
||||
public let version: String
|
||||
public let flavor: Flavor
|
||||
|
||||
static func swiftPMDirectory(
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment,
|
||||
homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
) throws -> URL {
|
||||
if let configurationDirectory = environment["XDG_CONFIG_HOME"] {
|
||||
guard (configurationDirectory as NSString).isAbsolutePath else {
|
||||
throw StringError("XDG_CONFIG_HOME must be an absolute path: '\(configurationDirectory)'")
|
||||
}
|
||||
return URL(fileURLWithPath: configurationDirectory, isDirectory: true)
|
||||
.appendingPathComponent("swiftpm", isDirectory: true)
|
||||
} else {
|
||||
return homeDirectory.appendingPathComponent(".swiftpm", isDirectory: true)
|
||||
}
|
||||
}
|
||||
|
||||
private static func swiftSDKsDirectory(
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment,
|
||||
homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
) throws -> URL {
|
||||
try swiftPMDirectory(environment: environment, homeDirectory: homeDirectory)
|
||||
.appendingPathComponent("swift-sdks", isDirectory: true)
|
||||
}
|
||||
|
||||
public init?(bundle: URL) {
|
||||
self.bundle = bundle
|
||||
if let version = try? Data(contentsOf: bundle.appendingPathComponent("darwin-sdk-version.txt")) {
|
||||
self.version = String(decoding: version, as: UTF8.self)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
} else if ["darwin.xtoolsdk", "darwin.artifactbundle", "darwin.artifactbundle.tmp"].contains(bundle.lastPathComponent) {
|
||||
self.version = "develop"
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if version == "develop" {
|
||||
self.flavor = .legacy
|
||||
} else if bundle.appendingPathComponent("Xcode.app").dirExists {
|
||||
self.flavor = .normal
|
||||
} else {
|
||||
self.flavor = .slim
|
||||
}
|
||||
}
|
||||
|
||||
package static func prepareTemporaryBundle(
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment,
|
||||
homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
) throws -> TemporaryBundle {
|
||||
let sdksDirectory = try swiftSDKsDirectory(environment: environment, homeDirectory: homeDirectory)
|
||||
try FileManager.default.createDirectory(at: sdksDirectory, withIntermediateDirectories: true)
|
||||
let bundle = sdksDirectory.appendingPathComponent("darwin.artifactbundle.tmp", isDirectory: true)
|
||||
if FileManager.default.fileExists(atPath: bundle.path) {
|
||||
try FileManager.default.removeItem(at: bundle)
|
||||
}
|
||||
return TemporaryBundle(url: bundle)
|
||||
}
|
||||
|
||||
private static func addHostClangResourceDir(to sdk: URL) async throws {
|
||||
let clangURL = try await ToolRegistry.locate("clang")
|
||||
let process = try await Subprocess.run(
|
||||
.path(FilePath(clangURL.path)),
|
||||
arguments: ["-print-resource-dir"],
|
||||
output: .string(limit: .max)
|
||||
).checkSuccess()
|
||||
let output = process.standardOutput ?? ""
|
||||
let hostClangResources = URL(filePath: output.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
let hostInclude = hostClangResources.appending(path: "include")
|
||||
let sdkInclude = sdk.appending(path: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include")
|
||||
try await FileManager.default.copyItem(at: hostInclude, to: sdkInclude, preserveOwner: false)
|
||||
}
|
||||
|
||||
public static func current() throws -> DarwinSDK? {
|
||||
let bundle = try swiftSDKsDirectory().appendingPathComponent("darwin.artifactbundle", isDirectory: true)
|
||||
guard bundle.dirExists else { return nil }
|
||||
return DarwinSDK(bundle: bundle)
|
||||
}
|
||||
|
||||
public func remove() throws {
|
||||
try FileManager.default.removeItem(at: bundle)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module XADI [extern_c] {
|
||||
header "xadi.h"
|
||||
link "xadi"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#include <stdint.h>
|
||||
|
||||
void xadi_Load(const char *path);
|
||||
int32_t xadi_SetAndroidID(const char *identifier, uint32_t length);
|
||||
int32_t xadi_SetProvisioningPath(const char *path);
|
||||
int32_t xadi_ProvisioningErase(uint64_t dsId);
|
||||
int32_t xadi_Synchronize(uint64_t dsId, const void *serverIntermediateMetadata, uint32_t serverIntermediateMetadataLength, void **machineIdentifier, uint32_t *machineIdentifierLength, void **synchronizationResumeMetadata, uint32_t *synchronizationResumeMetadataLength);
|
||||
int32_t xadi_ProvisioningDestroy(uint32_t session);
|
||||
int32_t xadi_ProvisioningEnd(uint32_t session, const void *persistentTokenMetadata, uint32_t persistentTokenMetadataLength, const void *trustKey, uint32_t trustKeyLength);
|
||||
int32_t xadi_ProvisioningStart(uint64_t dsId, const void *serverProvisioningIntermediateMetadata, uint32_t serverProvisioningIntermediateMetadataLength, void **clientProvisioningIntermediateMetadata, uint32_t *clientProvisioningIntermediateMetadataLength, uint32_t *session);
|
||||
int32_t xadi_GetLoginCode(uint64_t dsId);
|
||||
int32_t xadi_Dispose(void *ptr);
|
||||
int32_t xadi_OTPRequest(uint64_t dsId, void **machineIdentifier, uint32_t *machineIdentifierLength, void **oneTimePassword, uint32_t *oneTimePasswordLength);
|
||||
@@ -138,9 +138,3 @@ extension WirelessAccessoryEntitlement: EntitlementWithCapability {
|
||||
DeveloperServicesCapability(.wirelessAccessoryConfiguration, isFree: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension WiFiAwareEntitlement: EntitlementWithCapability {
|
||||
var capability: DeveloperServicesCapability {
|
||||
DeveloperServicesCapability(rawName: "WIFI_AWARE", isFree: false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,10 +140,12 @@ public struct DeveloperAPIXcodeAuthMiddleware: ClientMiddleware {
|
||||
|
||||
// Xcode-specific
|
||||
request.headerFields[.userAgent] = "Xcode"
|
||||
request.headerFields[.init(DeviceInfo.xcodeVersionKey)!] = DeviceInfo.xcodeVersion
|
||||
request.headerFields[.init(DeviceInfo.xcodeVersionKey)!] = "16.2 (16C5031c)"
|
||||
|
||||
// MobileMe identity
|
||||
request.headerFields[.init(DeviceInfo.clientInfoKey)!] = deviceInfo.clientInfo.clientString
|
||||
request.headerFields[.init(DeviceInfo.clientInfoKey)!] = """
|
||||
<VirtualMac2,1> <macOS;15.1.1;24B91> <com.apple.AuthKit/1 (com.apple.dt.Xcode/23505)>
|
||||
""" // deviceInfo.clientInfo.clientString
|
||||
request.headerFields[.init(DeviceInfo.deviceIDKey)!] = deviceInfo.deviceID
|
||||
|
||||
// GrandSlam authentication
|
||||
|
||||
@@ -49,7 +49,7 @@ private struct UnimplementedRawADIProvider: RawADIProvider {
|
||||
private enum RawADIProviderDependencyKey: DependencyKey {
|
||||
static let testValue: RawADIProvider = UnimplementedRawADIProvider()
|
||||
static let liveValue: RawADIProvider = {
|
||||
#if canImport(XADI)
|
||||
#if os(Linux)
|
||||
return XADIProvider()
|
||||
#else
|
||||
return OmnisetteADIProvider()
|
||||
|
||||
@@ -14,19 +14,29 @@ public struct DeviceInfo: Codable, Sendable {
|
||||
/// `X-Xcode-Version`
|
||||
static let xcodeVersionKey = "X-Xcode-Version"
|
||||
/// Not included in `dictionary`
|
||||
public static let xcodeVersion = "26.5 (17F42)"
|
||||
public static let xcodeVersion = "14.2 (14C18)"
|
||||
|
||||
public struct ClientInfo: Codable {
|
||||
public static let macOSVersion = "14.3.1"
|
||||
public static let macOSBuild = "23D60"
|
||||
|
||||
public static let authKitVersion = "1"
|
||||
public static let akdVersion = "1.0"
|
||||
public static let cfNetworkVersion = "978.0.7"
|
||||
public static let darwinVersion = "18.7.0"
|
||||
|
||||
public let modelID: String // e.g. MacBookPro11,5
|
||||
|
||||
// TODO: Do we need to replace com.apple.akd with com.apple.dt.Xcode? See AltStore
|
||||
var clientString: String {
|
||||
"""
|
||||
<\(modelID)> <macOS;27.0;26A5378j> <com.apple.AuthKit/1 (com.apple.akd/1.0)>
|
||||
<\(modelID)> <Mac OS X;\(Self.macOSVersion);\(Self.macOSBuild)> \
|
||||
<com.apple.AuthKit/\(Self.authKitVersion) (com.apple.akd/\(Self.akdVersion))>
|
||||
"""
|
||||
}
|
||||
|
||||
var userAgent: String {
|
||||
"AuthKit/1 (Macintosh; OS X 27.0) (com.apple.dt.Xcode/26.5)"
|
||||
"akd/\(Self.akdVersion) CFNetwork/\(Self.cfNetworkVersion) Darwin/\(Self.darwinVersion)"
|
||||
}
|
||||
|
||||
public init(modelID: String) {
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
|
||||
#if false
|
||||
|
||||
// For reference: https://github.com/xtool-org/xtool/issues/196
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Creates a socket connected to `ip` on `port`.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if canImport(XADI)
|
||||
#if os(Linux)
|
||||
|
||||
import Foundation
|
||||
import XADI
|
||||
|
||||
@@ -41,11 +41,7 @@ struct GrandSlamClient: Sendable {
|
||||
}
|
||||
request.configure(request: &httpRequest, deviceInfo: deviceInfo, anisetteData: anisetteData)
|
||||
|
||||
// GrandSlam doesn't seem to like reused (keep-alive) connections so create a
|
||||
// new one for each request. cf https://github.com/rileytestut/AltSign/pull/52
|
||||
let resp = try await httpClient.withEphemeralClient {
|
||||
try await $0.makeRequest(httpRequest, body: body)
|
||||
}
|
||||
let resp = try await httpClient.makeRequest(httpRequest, body: body)
|
||||
return try R.Decoder.decode(data: resp.body)
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ actor GrandSlamLookupManager {
|
||||
} */
|
||||
var request = HTTPRequest(url: Self.lookupURL)
|
||||
request.headerFields = [
|
||||
.userAgent: deviceInfo.clientInfo.userAgent,
|
||||
.init(DeviceInfo.clientInfoKey)!: deviceInfo.clientInfo.clientString,
|
||||
.init(DeviceInfo.deviceIDKey)!: deviceInfo.deviceID,
|
||||
.init(AnisetteData.iLocaleKey)!: Locale.current.identifier,
|
||||
|
||||
@@ -18,47 +18,23 @@ import OpenAPIAsyncHTTPClient
|
||||
import Dependencies
|
||||
|
||||
extension HTTPClientDependencyKey: DependencyKey {
|
||||
public static let liveValue: HTTPClientProtocol = Client()
|
||||
}
|
||||
|
||||
private struct Client: HTTPClientProtocol {
|
||||
private static var proxyConfiguration: HTTPClient.Configuration.Proxy? {
|
||||
// e.g. `XTL_HTTP_PROXY=localhost:8080`
|
||||
guard let value = ProcessInfo.processInfo.environment["XTL_HTTP_PROXY"],
|
||||
let separator = value.lastIndex(of: ":"),
|
||||
let port = Int(value[value.index(after: separator)...]) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let host = String(value[..<separator])
|
||||
return host.isEmpty ? nil : .server(host: host, port: port)
|
||||
}
|
||||
|
||||
private static let tlsConfiguration: TLSConfiguration = {
|
||||
public static let liveValue: HTTPClientProtocol = {
|
||||
// if ssl cert parsing fails we're screwed so we might as well force try
|
||||
// swiftlint:disable:next force_try
|
||||
let appleRootCA = try! NIOSSLCertificate(bytes: Array(appleRootPEM.utf8), format: .pem)
|
||||
var tlsConfiguration: TLSConfiguration = .makeClientConfiguration()
|
||||
tlsConfiguration.additionalTrustRoots = [.certificates([appleRootCA])]
|
||||
if ProcessInfo.processInfo.environment["XTL_DISABLE_TLS_VALIDATION"] == "1" {
|
||||
tlsConfiguration.certificateVerification = .none
|
||||
}
|
||||
return tlsConfiguration
|
||||
}()
|
||||
|
||||
var client: HTTPClient
|
||||
|
||||
init() {
|
||||
var config = HTTPClient.Configuration(
|
||||
tlsConfiguration: Self.tlsConfiguration,
|
||||
proxy: Self.proxyConfiguration,
|
||||
tlsConfiguration: tlsConfiguration,
|
||||
decompression: .enabled(limit: .none)
|
||||
)
|
||||
config.timeout.connect = .seconds(60)
|
||||
self.client = HTTPClient(configuration: config)
|
||||
}
|
||||
return HTTPClient(configuration: config)
|
||||
}()
|
||||
}
|
||||
|
||||
func makeWebSocket(url: URL) async throws -> any WebSocketSession {
|
||||
extension HTTPClient: HTTPClientProtocol {
|
||||
public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
|
||||
let (stream, continuation) = AsyncStream.makeStream(of: WebSocketSessionWrapper.self)
|
||||
async let value = stream.first(where: { _ in true })
|
||||
// must be after the `async let` so that we finish if connect throws
|
||||
@@ -66,7 +42,7 @@ private struct Client: HTTPClientProtocol {
|
||||
// we can't use the async overload because we need to immediately subscribe
|
||||
// to onText/onBinary in the same EventLoop tick that the WebSocket is created.
|
||||
// This is also why we create the SessionWrapper inside the closure.
|
||||
let future = WebSocket.connect(to: url, on: client.eventLoopGroup) {
|
||||
let future = WebSocket.connect(to: url, on: eventLoopGroup) {
|
||||
continuation.yield(WebSocketSessionWrapper(webSocket: $0))
|
||||
}
|
||||
try await future.get()
|
||||
@@ -80,17 +56,8 @@ private struct Client: HTTPClientProtocol {
|
||||
case connectFailed
|
||||
}
|
||||
|
||||
var asOpenAPITransport: any ClientTransport {
|
||||
AsyncHTTPClientTransport(configuration: .init(client: client))
|
||||
}
|
||||
|
||||
func withEphemeralClient<T>(
|
||||
perform: (any HTTPClientProtocol) async throws -> T
|
||||
) async throws -> T {
|
||||
let ephemeralClient = Client()
|
||||
let result = await Result { try await perform(ephemeralClient) }
|
||||
try? await ephemeralClient.client.shutdown()
|
||||
return try result.get()
|
||||
public var asOpenAPITransport: any ClientTransport {
|
||||
AsyncHTTPClientTransport(configuration: .init(client: self))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,6 @@ public protocol HTTPClientProtocol: Sendable {
|
||||
var asOpenAPITransport: ClientTransport { get }
|
||||
|
||||
func makeWebSocket(url: URL) async throws -> WebSocketSession
|
||||
|
||||
func withEphemeralClient<T>(
|
||||
perform: (any HTTPClientProtocol) async throws -> T
|
||||
) async throws -> T
|
||||
}
|
||||
|
||||
extension HTTPClientProtocol {
|
||||
@@ -45,72 +41,28 @@ extension HTTPClientProtocol {
|
||||
public func makeRequest(
|
||||
_ request: HTTPRequest,
|
||||
body: Data? = nil,
|
||||
requireHTTPSuccess: Bool = true,
|
||||
onProgress: @isolated(any) (Double?) -> Void = { _ in }
|
||||
) async throws -> (response: HTTPResponse, body: Data) {
|
||||
await onProgress(0)
|
||||
let (response, responseBody) = try await send(request, body: body.map { HTTPBody($0) })
|
||||
guard !requireHTTPSuccess || ![.clientError, .serverError].contains(response.status.kind) else {
|
||||
let errorBody = (try? await responseBody.collect()) ?? Data()
|
||||
throw HTTPResponseError(
|
||||
method: request.method,
|
||||
url: "\(request.scheme ?? "https")://\(request.authority ?? "")\(request.path ?? "")",
|
||||
status: response.status,
|
||||
// we don't use `decoding:as:` because we want to validate the UTF8
|
||||
body: String(data: errorBody, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
)
|
||||
let (response, body) = try await send(request, body: body.map { HTTPBody($0) })
|
||||
guard let body else {
|
||||
return (response, Data())
|
||||
}
|
||||
return (response, try await responseBody.collect(onProgress: onProgress))
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPBody? {
|
||||
fileprivate func collect(
|
||||
onProgress: @isolated(any) (Double?) -> Void = { _ in }
|
||||
) async throws -> Data {
|
||||
try await self?.collect(onProgress: onProgress) ?? Data()
|
||||
}
|
||||
}
|
||||
|
||||
extension HTTPBody {
|
||||
fileprivate func collect(
|
||||
onProgress: @isolated(any) (Double?) -> Void
|
||||
) async throws -> Data {
|
||||
switch self.length {
|
||||
switch body.length {
|
||||
case .unknown:
|
||||
return try await self.reduce(into: Data()) { $0 += $1 }
|
||||
return (response, try await body.reduce(into: Data()) { $0 += $1 })
|
||||
case .known(let length):
|
||||
var data = Data(capacity: Int(length))
|
||||
let total = Double(length)
|
||||
for try await chunk in self {
|
||||
for try await chunk in body {
|
||||
data += chunk
|
||||
await onProgress(Swift.min(Double(data.count) / total, 1))
|
||||
await onProgress(min(Double(data.count) / total, 1))
|
||||
}
|
||||
return data
|
||||
return (response, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct HTTPResponseError: Error, LocalizedError, Sendable, CustomStringConvertible {
|
||||
public let method: HTTPRequest.Method
|
||||
public let url: String
|
||||
public let status: HTTPResponse.Status
|
||||
public let body: String?
|
||||
|
||||
public var description: String {
|
||||
var description = "\(method.rawValue) \(url) failed: HTTP \(status.code)"
|
||||
if !status.reasonPhrase.isEmpty {
|
||||
description += " \(status.reasonPhrase)"
|
||||
}
|
||||
if let body, !body.isEmpty {
|
||||
description += ". Details:\n\(body)"
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
public var errorDescription: String? { description }
|
||||
}
|
||||
|
||||
private struct UnimplementedHTTPClient: HTTPClientProtocol, ClientTransport {
|
||||
public var asOpenAPITransport: ClientTransport { self }
|
||||
|
||||
@@ -132,12 +84,6 @@ private struct UnimplementedHTTPClient: HTTPClientProtocol, ClientTransport {
|
||||
return try closure()
|
||||
}
|
||||
|
||||
func withEphemeralClient<T>(
|
||||
perform: (any HTTPClientProtocol) async throws -> T
|
||||
) async throws -> T {
|
||||
try await perform(self)
|
||||
}
|
||||
|
||||
public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
|
||||
let closure: (URL) async throws -> any WebSocketSession = unimplemented()
|
||||
return try await closure(url)
|
||||
|
||||
@@ -40,18 +40,6 @@ private struct Client: HTTPClientProtocol {
|
||||
) {
|
||||
webSocketCallbacks.withValue { $0.removeValue(forKey: webSocketTask) }?(closeCode)
|
||||
}
|
||||
|
||||
func urlSession(
|
||||
_ session: URLSession,
|
||||
didReceive challenge: URLAuthenticationChallenge
|
||||
) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {
|
||||
if ProcessInfo.processInfo.environment["XTL_DISABLE_TLS_VALIDATION"] == "1",
|
||||
let trust = challenge.protectionSpace.serverTrust {
|
||||
return (.useCredential, URLCredential(trust: trust))
|
||||
} else {
|
||||
return (.performDefaultHandling, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let clientDelegate = ClientDelegate()
|
||||
@@ -68,15 +56,6 @@ private struct Client: HTTPClientProtocol {
|
||||
URLSessionTransport(configuration: .init(session: session))
|
||||
}
|
||||
|
||||
func withEphemeralClient<T>(
|
||||
perform: (any HTTPClientProtocol) async throws -> T
|
||||
) async throws -> T {
|
||||
let ephemeralClient = Client()
|
||||
let result = await Result { try await perform(ephemeralClient) }
|
||||
ephemeralClient.session.finishTasksAndInvalidate()
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
|
||||
let task = session.webSocketTask(with: url)
|
||||
let (event, eventContinuation) = AsyncStream<URLSessionWebSocketTask.CloseCode?>.makeStream()
|
||||
|
||||
@@ -26,7 +26,6 @@ extension EntitlementContainer {
|
||||
SiriKitEntitlement.self,
|
||||
InterAppAudioEntitlement.self,
|
||||
WirelessAccessoryEntitlement.self,
|
||||
WiFiAwareEntitlement.self,
|
||||
HomeKitEntitlement.self,
|
||||
HealthKitEntitlement.self,
|
||||
]
|
||||
@@ -156,21 +155,6 @@ public struct WirelessAccessoryEntitlement: Entitlement, RawRepresentable {
|
||||
public init(rawValue: Bool) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
public struct WiFiAwareEntitlement: Entitlement, RawRepresentable {
|
||||
public static let identifier = "com.apple.developer.wifi-aware"
|
||||
|
||||
public var rawValue: [String]
|
||||
public init(rawValue: [String]) { self.rawValue = rawValue }
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
rawValue = try decoder.singleValueContainer().decode([String].self)
|
||||
}
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
public struct HomeKitEntitlement: Entitlement, RawRepresentable {
|
||||
public static let identifier = "com.apple.developer.homekit"
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ struct DSTeamsListCommand: AsyncParsableCommand {
|
||||
func run() async throws {
|
||||
let token = try AuthToken.saved()
|
||||
|
||||
guard case let .xcode(authData) = token.authData() else {
|
||||
guard case let .xcode(authData) = try token.authData() else {
|
||||
throw Console.Error("This command requires password-based authentication")
|
||||
}
|
||||
let client = DeveloperServicesClient(authData: authData)
|
||||
|
||||
@@ -27,8 +27,6 @@ struct PackOperation {
|
||||
|
||||
@discardableResult
|
||||
func run() async throws -> URL {
|
||||
try await EnsureSDKOperation(quiet: true).run()
|
||||
|
||||
print("Planning...")
|
||||
|
||||
let schema: PackSchema
|
||||
|
||||
@@ -52,42 +52,13 @@ struct SDKBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
enum Mode {
|
||||
/// Create a slim SDK with just the files that this version of xtool uses
|
||||
case buildSlim
|
||||
/// Create an SDK that retains a full copy of Xcode.app/Contents/Developer.
|
||||
/// Larger but allows in-place updates.
|
||||
case buildNormal
|
||||
/// Update a normal SDK in-place.
|
||||
case update
|
||||
|
||||
var usesHardLinks: Bool {
|
||||
switch self {
|
||||
case .buildSlim: false
|
||||
case .buildNormal, .update: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let input: Input
|
||||
let output: URL
|
||||
let arch: Arch
|
||||
let mode: Mode
|
||||
|
||||
// bump this when the sdk builder logic changes
|
||||
static let sdkEpoch = 1
|
||||
|
||||
// tag from https://github.com/xtool-org/darwin-tools-linux-llvm
|
||||
static let darwinToolsVersion = "1.0.1"
|
||||
|
||||
static var currentSDKVersion: String {
|
||||
"""
|
||||
epoch=\(sdkEpoch),darwinTools=\(darwinToolsVersion)
|
||||
"""
|
||||
}
|
||||
|
||||
func buildSDK() async throws {
|
||||
let sdkVersion = Self.currentSDKVersion
|
||||
// TODO: store relevant info for staleness check
|
||||
let sdkVersion = "develop"
|
||||
|
||||
try? FileManager.default.removeItem(at: output)
|
||||
try FileManager.default.createDirectory(
|
||||
@@ -199,6 +170,9 @@ struct SDKBuilder {
|
||||
}
|
||||
|
||||
private func installToolset(in output: URL) async throws {
|
||||
// tag from https://github.com/xtool-org/darwin-tools-linux-llvm
|
||||
let darwinToolsVersion = "1.0.1"
|
||||
|
||||
let toolsetDir = output.appendingPathComponent("toolset")
|
||||
|
||||
try FileManager.default.createDirectory(
|
||||
@@ -209,7 +183,7 @@ struct SDKBuilder {
|
||||
@Dependency(\.httpClient) var httpClient
|
||||
let url = URL(string: """
|
||||
https://github.com/xtool-org/darwin-tools-linux-llvm/releases/download/\
|
||||
v\(Self.darwinToolsVersion)/toolset-\(arch.rawValue).tar.gz
|
||||
v\(darwinToolsVersion)/toolset-\(arch.rawValue).tar.gz
|
||||
""")!
|
||||
let (response, body) = try await httpClient.send(HTTPRequest(url: url))
|
||||
guard response.status == 200, let body else { throw Console.Error("Could not fetch toolset") }
|
||||
@@ -250,19 +224,23 @@ struct SDKBuilder {
|
||||
private func installDeveloper(in output: URL) async throws -> URL {
|
||||
let dev = output.appendingPathComponent("Developer")
|
||||
|
||||
let expectedAppDir = output.appendingPathComponent("Xcode.app")
|
||||
let appDir: URL
|
||||
let cleanupStageDir: URL?
|
||||
let wanted: Int?
|
||||
|
||||
switch (input, mode) {
|
||||
case (.xip(let inputPath), .buildSlim):
|
||||
let stage = output.appendingPathComponent("DeveloperStage")
|
||||
try FileManager.default.createDirectory(at: stage, withIntermediateDirectories: false)
|
||||
wanted = try await extractXIP(inputPath: inputPath, outDir: stage.path)
|
||||
switch input {
|
||||
case .xip(let inputPath):
|
||||
let devStage = output.appendingPathComponent("DeveloperStage")
|
||||
try FileManager.default.createDirectory(at: devStage, withIntermediateDirectories: false)
|
||||
// unxip doesn't like cooperative cancellation atm so shield it.
|
||||
// if the user does a ^C during unxip, we'll just wait until extraction
|
||||
// is over before bailing
|
||||
wanted = try await Task {
|
||||
try await extractXIP(inputPath: inputPath, outDir: devStage.path)
|
||||
}.value
|
||||
try Task.checkCancellation()
|
||||
let contents = try FileManager.default.contentsOfDirectory(
|
||||
at: stage,
|
||||
at: devStage,
|
||||
includingPropertiesForKeys: nil
|
||||
)
|
||||
let apps = contents.filter { $0.pathExtension == "app" }
|
||||
@@ -274,39 +252,12 @@ struct SDKBuilder {
|
||||
default:
|
||||
throw Console.Error("Unrecognized xip layout (multiple apps found)")
|
||||
}
|
||||
cleanupStageDir = stage
|
||||
case (.xip(let inputPath), .buildNormal):
|
||||
wanted = try await extractXIP(inputPath: inputPath, outDir: output.path)
|
||||
appDir = expectedAppDir
|
||||
cleanupStageDir = nil
|
||||
case (.xip, .update):
|
||||
throw Console.Error("Can't update with xip input")
|
||||
case (.app(let appPath), .buildSlim), (.app(let appPath), .update):
|
||||
cleanupStageDir = devStage
|
||||
case .app(let appPath):
|
||||
wanted = nil
|
||||
appDir = URL(fileURLWithPath: appPath)
|
||||
wanted = nil
|
||||
cleanupStageDir = nil
|
||||
case (.app(let appPath), .buildNormal):
|
||||
let source = URL(fileURLWithPath: appPath)
|
||||
let sourceContentsDir = source.appendingPathComponent("Contents")
|
||||
let expectedContentsDir = expectedAppDir.appendingPathComponent("Contents")
|
||||
try FileManager.default.createDirectory(at: expectedContentsDir, withIntermediateDirectories: true)
|
||||
print("[Copying Xcode.app] This might take a minute...")
|
||||
for child in ["Info.plist", "version.plist", "Developer"] {
|
||||
let expectedFile = expectedContentsDir.appendingPathComponent(child)
|
||||
let sourceFile = sourceContentsDir.appendingPathComponent(child)
|
||||
guard FileManager.default.fileExists(atPath: sourceFile.path) else {
|
||||
throw Console.Error("""
|
||||
The provided directory at '\(appPath)' does not appear to be a known version of Xcode: \
|
||||
could not read '\(sourceFile.path)'
|
||||
""")
|
||||
}
|
||||
try await FileManager.default.copyItem(at: sourceFile, to: expectedFile, preserveOwner: false)
|
||||
}
|
||||
appDir = expectedAppDir
|
||||
wanted = nil
|
||||
cleanupStageDir = nil
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
|
||||
try FileManager.default.createDirectory(at: dev, withIntermediateDirectories: false)
|
||||
|
||||
@@ -329,7 +280,7 @@ struct SDKBuilder {
|
||||
}
|
||||
if count % 100 == 0 {
|
||||
if wanted == nil {
|
||||
print("\r[Installing SDKs] Installed \(count) files", terminator: "")
|
||||
print("\r[Installing SDKs] Copied \(count) files", terminator: "")
|
||||
fflush(stdoutSafe)
|
||||
}
|
||||
await Task.yield()
|
||||
@@ -342,11 +293,7 @@ struct SDKBuilder {
|
||||
if try child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {
|
||||
toDoDirs.append(path)
|
||||
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: false)
|
||||
} else if mode.usesHardLinks {
|
||||
// Installed SDKs retain Xcode.app developer dir, so avoid storing their developer files twice.
|
||||
try FileManager.default.linkItem(at: child, to: dest)
|
||||
} else {
|
||||
// Slim SDKs omit Xcode.app and contain independent copies.
|
||||
try FileManager.default.copyItem(at: child, to: dest)
|
||||
}
|
||||
}
|
||||
@@ -358,9 +305,9 @@ struct SDKBuilder {
|
||||
}
|
||||
print()
|
||||
|
||||
print("[Cleaning up]")
|
||||
if let cleanupStageDir {
|
||||
print("[Cleaning up]")
|
||||
try FileManager.default.removeItem(at: cleanupStageDir)
|
||||
try? FileManager.default.removeItem(at: cleanupStageDir)
|
||||
}
|
||||
|
||||
print("[Finalizing SDKs]")
|
||||
@@ -403,8 +350,6 @@ struct SDKBuilder {
|
||||
)
|
||||
}
|
||||
|
||||
// we copy over the host's clang resorurce dir during install, because intrinsics can differ
|
||||
// by LLVM version
|
||||
try FileManager.default.removeItem(
|
||||
at: dev.appending(path: "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include")
|
||||
)
|
||||
@@ -412,18 +357,9 @@ struct SDKBuilder {
|
||||
return dev
|
||||
}
|
||||
|
||||
private func extractXIP(inputPath: String, outDir: String) async throws -> Int {
|
||||
// unxip doesn't like cooperative cancellation atm so shield it.
|
||||
// if the user does a ^C during unxip, we'll just wait until extraction
|
||||
// is over before bailing
|
||||
try await Task {
|
||||
try await _extractXIP(inputPath: inputPath, outDir: outDir)
|
||||
}.value
|
||||
}
|
||||
|
||||
// returns the number of files we actually want to keep,
|
||||
// useful for computing progress % during fs traversal
|
||||
private func _extractXIP(inputPath: String, outDir: String) async throws -> Int {
|
||||
private func extractXIP(inputPath: String, outDir: String) async throws -> Int {
|
||||
let fd = try FileDescriptor.open(inputPath, .readOnly)
|
||||
defer { try? fd.close() }
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ struct SDKCommand: AsyncParsableCommand {
|
||||
abstract: "Manage the Darwin Swift SDK",
|
||||
subcommands: [
|
||||
DevSDKInstallCommand.self,
|
||||
DevSDKUpdateCommand.self,
|
||||
DevSDKRemoveCommand.self,
|
||||
DevSDKBuildCommand.self,
|
||||
DevSDKStatusCommand.self,
|
||||
@@ -50,7 +49,7 @@ struct DevSDKBuildCommand: AsyncParsableCommand {
|
||||
let builderArch = try arch.sdkBuilderArch
|
||||
let input = try SDKBuilder.Input(path: path)
|
||||
let output = URL(fileURLWithPath: outputDir, isDirectory: true).appending(path: "darwin.xtoolsdk")
|
||||
let builder = SDKBuilder(input: input, output: output, arch: builderArch, mode: .buildSlim)
|
||||
let builder = SDKBuilder(input: input, output: output, arch: builderArch)
|
||||
try await builder.buildSDK()
|
||||
print("Built SDK at \(output.path). You can install it with `xtool sdk install`.")
|
||||
}
|
||||
@@ -91,24 +90,8 @@ struct DevSDKInstallCommand: AsyncParsableCommand {
|
||||
)
|
||||
var path: String
|
||||
|
||||
@Flag(
|
||||
help: "Install a slim SDK (uses less disk space). Slim SDKs cannot be updated in place."
|
||||
)
|
||||
var slim = false
|
||||
|
||||
func run() async throws {
|
||||
try await InstallSDKOperation(path: path, slim: slim).run()
|
||||
}
|
||||
}
|
||||
|
||||
struct DevSDKUpdateCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "update",
|
||||
abstract: "Update the installed Darwin Swift SDK"
|
||||
)
|
||||
|
||||
func run() async throws {
|
||||
try await UpdateSDKOperation().run()
|
||||
try await InstallSDKOperation(path: path).run()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,7 +102,7 @@ struct DevSDKRemoveCommand: AsyncParsableCommand {
|
||||
)
|
||||
|
||||
func run() async throws {
|
||||
guard let sdk = try DarwinSDK.current() else {
|
||||
guard let sdk = try await DarwinSDK.current() else {
|
||||
throw Console.Error("Cannot remove SDK: no Darwin SDK installed")
|
||||
}
|
||||
try sdk.remove()
|
||||
@@ -134,20 +117,103 @@ struct DevSDKStatusCommand: AsyncParsableCommand {
|
||||
)
|
||||
|
||||
func run() async throws {
|
||||
if let sdk = try DarwinSDK.current() {
|
||||
print("Darwin SDK is installed")
|
||||
print(" Path: \(sdk.bundle.path)")
|
||||
print(" Flavor: \(sdk.flavor)")
|
||||
print(" Version: \(sdk.version)")
|
||||
if let sdk = try await DarwinSDK.current() {
|
||||
print("Installed at \(sdk.bundle.path)")
|
||||
} else {
|
||||
print("Not installed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DarwinSDK {
|
||||
struct DarwinSDK {
|
||||
let bundle: URL
|
||||
let version: String
|
||||
|
||||
init?(bundle: URL) {
|
||||
self.bundle = bundle
|
||||
if let version = try? Data(contentsOf: bundle.appendingPathComponent("darwin-sdk-version.txt")) {
|
||||
self.version = String(decoding: version, as: UTF8.self)
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
} else if ["darwin.xtoolsdk", "darwin.artifactbundle"].contains(bundle.lastPathComponent) {
|
||||
self.version = "unknown"
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
static func install(from path: String) async throws {
|
||||
// we can't just move into ~/.swiftpm/swift-sdks because the swiftpm directory
|
||||
// location depends on factors like $XDG_CONFIG_HOME. Rather than replicating
|
||||
// SwiftPM's logic, which may change, it's more reliable to directly invoke
|
||||
// `swift sdk install`. See: https://github.com/xtool-org/xtool/pull/40
|
||||
|
||||
let url = URL(fileURLWithPath: path)
|
||||
guard DarwinSDK(bundle: url) != nil else { throw Console.Error("Invalid Darwin SDK at '\(path)'")}
|
||||
|
||||
try await addHostClangResourceDir(to: url)
|
||||
|
||||
try await Subprocess.run(
|
||||
.name("swift"),
|
||||
arguments: ["sdk", "install", url.path],
|
||||
output: .discarded
|
||||
)
|
||||
.checkSuccess()
|
||||
}
|
||||
|
||||
private static func addHostClangResourceDir(to sdk: URL) async throws {
|
||||
let clangURL = try await ToolRegistry.locate("clang")
|
||||
let process = try await Subprocess.run(
|
||||
.path(FilePath(clangURL.path)),
|
||||
arguments: ["-print-resource-dir"],
|
||||
output: .string(limit: .max)
|
||||
).checkSuccess()
|
||||
let output = process.standardOutput ?? ""
|
||||
let hostClangResources = URL(filePath: output.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
let hostInclude = hostClangResources.appending(path: "include")
|
||||
let sdkInclude = sdk.appending(path: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include")
|
||||
try FileManager.default.copyItem(at: hostInclude, to: sdkInclude)
|
||||
}
|
||||
|
||||
static func current() async throws -> DarwinSDK? {
|
||||
let outputString: String
|
||||
do {
|
||||
outputString = try await Subprocess.run(
|
||||
.name("swift"),
|
||||
arguments: ["sdk", "configure", "darwin", "arm64-apple-ios", "--show-configuration"],
|
||||
output: .string(limit: .max)
|
||||
)
|
||||
.checkSuccess()
|
||||
.standardOutput
|
||||
?? ""
|
||||
} catch SubprocessFailure.exited {
|
||||
return nil
|
||||
}
|
||||
|
||||
// should be something like
|
||||
// swiftResourcesPath: /home/user/.swiftpm/swift-sdks/darwin.artifactbundle/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift
|
||||
// swiftlint:disable:previous line_length
|
||||
let resourcesPathPrefix = "swiftResourcesPath: "
|
||||
|
||||
guard let resourcesPath = outputString
|
||||
.split(separator: "\n")
|
||||
.first(where: { $0.hasPrefix(resourcesPathPrefix) })?
|
||||
.dropFirst(resourcesPathPrefix.count)
|
||||
else { return nil }
|
||||
|
||||
var resourcesURL = URL(fileURLWithPath: String(resourcesPath))
|
||||
for _ in 0..<6 {
|
||||
resourcesURL = resourcesURL.deletingLastPathComponent()
|
||||
}
|
||||
|
||||
return DarwinSDK(bundle: resourcesURL)
|
||||
}
|
||||
|
||||
func isUpToDate() -> Bool {
|
||||
version == SDKBuilder.currentSDKVersion
|
||||
true
|
||||
}
|
||||
|
||||
func remove() throws {
|
||||
try FileManager.default.removeItem(at: bundle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,137 +251,38 @@ extension SwiftVersion {
|
||||
}
|
||||
}
|
||||
|
||||
struct EnsureSDKOperation {
|
||||
let quiet: Bool
|
||||
|
||||
func run() async throws {
|
||||
#if os(macOS)
|
||||
if !quiet {
|
||||
print("Skipping Darwin SDK setup since we're on macOS.")
|
||||
}
|
||||
#else
|
||||
let sdk = try DarwinSDK.current()
|
||||
switch sdk.map({ ($0.isUpToDate(), $0.flavor) }) {
|
||||
case (true, _)?: // swiftlint:disable:this optional_enum_case_matching
|
||||
if !quiet {
|
||||
print("Darwin SDK is up to date.")
|
||||
}
|
||||
case (false, .slim)?: // swiftlint:disable:this optional_enum_case_matching
|
||||
throw Console.Error("""
|
||||
Darwin SDK is out of date, and was installed in 'slim' mode.
|
||||
|
||||
Slim SDKs take less disk space, but can't be auto-updated.
|
||||
Please install a new SDK with
|
||||
xtool sdk install [--slim]
|
||||
""")
|
||||
case (false, .normal)?: // swiftlint:disable:this optional_enum_case_matching
|
||||
print("Darwin SDK is out of date. Rebuilding...")
|
||||
try await UpdateSDKOperation().run()
|
||||
case (false, .legacy)?: // swiftlint:disable:this optional_enum_case_matching
|
||||
print("""
|
||||
Darwin SDK is incompatible: built with an older version of xtool.
|
||||
|
||||
Requesting re-install. This is a one-time rebuild; after this,
|
||||
xtool will be able to resolve incompatibilities automatically.
|
||||
|
||||
""")
|
||||
try await generateSDK()
|
||||
case nil:
|
||||
print("Now generating the Darwin SDK.\n")
|
||||
try await generateSDK()
|
||||
}
|
||||
|
||||
func generateSDK() async throws {
|
||||
let path = try await Console.prompt("""
|
||||
Please download Xcode from http://developer.apple.com/download/all/?q=Xcode
|
||||
and enter the path to the downloaded Xcode.xip.
|
||||
|
||||
Path to Xcode.xip: \("" /* pacify swiftlint trailing_whitespace */)
|
||||
""")
|
||||
|
||||
let expanded = (path as NSString).expandingTildeInPath
|
||||
|
||||
try await InstallSDKOperation(path: expanded).run()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
struct InstallSDKOperation {
|
||||
let path: String
|
||||
let slim: Bool
|
||||
|
||||
init(path: String, slim: Bool = false) {
|
||||
self.path = path
|
||||
self.slim = slim
|
||||
}
|
||||
|
||||
func run() async throws {
|
||||
#if os(macOS)
|
||||
print("Skipping SDK install; the iOS SDK ships with Xcode on macOS")
|
||||
#else
|
||||
|
||||
let temporaryBundle = try DarwinSDK.prepareTemporaryBundle()
|
||||
let tempDir = try TemporaryDirectory(name: "DarwinSDKBuild")
|
||||
let sdkPath = tempDir.url.appending(path: "darwin.artifactbundle")
|
||||
|
||||
if path.hasSuffix(".xtoolsdk") {
|
||||
print("Installing prebuilt SDK...")
|
||||
try await FileManager.default.copyItem(at: URL(filePath: path), to: temporaryBundle.url, preserveOwner: false)
|
||||
try FileManager.default.copyItem(at: URL(filePath: path), to: sdkPath)
|
||||
} else {
|
||||
// validate input before removing existing SDK
|
||||
let input = try SDKBuilder.Input(path: path)
|
||||
let arch = try ArchSelection.auto.sdkBuilderArch
|
||||
|
||||
let mode: SDKBuilder.Mode = slim ? .buildSlim : .buildNormal
|
||||
let builder = SDKBuilder(input: input, output: temporaryBundle.url, arch: arch, mode: mode)
|
||||
let builder = SDKBuilder(input: input, output: sdkPath, arch: arch)
|
||||
try await builder.buildSDK()
|
||||
}
|
||||
|
||||
if let sdk = try DarwinSDK.current() {
|
||||
if let sdk = try await DarwinSDK.current() {
|
||||
print("Removing existing SDK...")
|
||||
try sdk.remove()
|
||||
}
|
||||
|
||||
try await temporaryBundle.install()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
struct UpdateSDKOperation {
|
||||
func run() async throws {
|
||||
#if os(macOS)
|
||||
print("Skipping SDK install; the iOS SDK ships with Xcode on macOS")
|
||||
#else
|
||||
guard let existing = try DarwinSDK.current() else {
|
||||
throw Console.Error("Could not locate existing SDK; cannot perform update.")
|
||||
}
|
||||
let xcode = existing.bundle.appendingPathComponent("Xcode.app")
|
||||
guard xcode.dirExists else {
|
||||
// This includes prebuilt .xtoolsdk installs and installs created with --slim.
|
||||
throw Console.Error("""
|
||||
The installed SDK was built in 'slim' mode and cannot be updated in place. \
|
||||
Please install a new copy with `xtool sdk install`.
|
||||
""")
|
||||
}
|
||||
|
||||
let input = try SDKBuilder.Input(path: xcode.path)
|
||||
let arch = try ArchSelection.auto.sdkBuilderArch
|
||||
|
||||
let temporaryBundle = try DarwinSDK.prepareTemporaryBundle()
|
||||
let builder = SDKBuilder(input: input, output: temporaryBundle.url, arch: arch, mode: .update)
|
||||
try await builder.buildSDK()
|
||||
|
||||
guard DarwinSDK(bundle: temporaryBundle.url) != nil else {
|
||||
throw Console.Error("Invalid Darwin SDK at '\(temporaryBundle.url.path)'")
|
||||
}
|
||||
|
||||
try FileManager.default.moveItem(
|
||||
at: xcode,
|
||||
to: temporaryBundle.url.appendingPathComponent("Xcode.app")
|
||||
)
|
||||
try existing.remove()
|
||||
try await temporaryBundle.install()
|
||||
|
||||
print("Updated SDK")
|
||||
try await DarwinSDK.install(from: sdkPath.path)
|
||||
|
||||
// don't destroy tempDir before this point
|
||||
withExtendedLifetime(tempDir) {}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import ArgumentParser
|
||||
import Foundation
|
||||
import XKit
|
||||
import PackLib
|
||||
|
||||
struct SetupCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
@@ -24,6 +23,36 @@ struct SetupOperation {
|
||||
|
||||
func run() async throws {
|
||||
try await AuthOperation(logoutFromExisting: false, quiet: quiet).run()
|
||||
try await EnsureSDKOperation(quiet: quiet).run()
|
||||
|
||||
#if os(macOS)
|
||||
if !quiet {
|
||||
print("Skipping Darwin SDK setup since we're on macOS.")
|
||||
}
|
||||
#else
|
||||
switch try await DarwinSDK.current()?.isUpToDate() {
|
||||
case true?:
|
||||
if !quiet {
|
||||
print("Darwin SDK is up to date.")
|
||||
}
|
||||
case false?:
|
||||
if !quiet {
|
||||
print("Darwin SDK is outdated.")
|
||||
}
|
||||
fallthrough
|
||||
case nil:
|
||||
let path = try await Console.prompt("""
|
||||
Now generating the Darwin SDK.
|
||||
|
||||
Please download Xcode from http://developer.apple.com/download/all/?q=Xcode
|
||||
and enter the path to the downloaded Xcode.xip.
|
||||
|
||||
Path to Xcode.xip: \("" /* pacify swiftlint trailing_whitespace */)
|
||||
""")
|
||||
|
||||
let expanded = (path as NSString).expandingTildeInPath
|
||||
|
||||
try await InstallSDKOperation(path: expanded).run()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import Foundation
|
||||
#if canImport(Subprocess)
|
||||
import Subprocess
|
||||
#endif
|
||||
|
||||
extension Data {
|
||||
// AsyncBytes is Darwin-only :/
|
||||
@@ -23,37 +20,6 @@ extension Data {
|
||||
}
|
||||
}
|
||||
|
||||
extension FileManager {
|
||||
/// Like `copyItem(at:to:)` but allows opting out of preserving the owner
|
||||
package func copyItem(
|
||||
at srcURL: URL,
|
||||
to dstURL: URL,
|
||||
preserveOwner: Bool,
|
||||
) async throws {
|
||||
// why this is needed: https://github.com/xtool-org/xtool/issues/254
|
||||
|
||||
#if canImport(Subprocess)
|
||||
if !preserveOwner {
|
||||
let result = try await Subprocess.run(
|
||||
.name("cp"),
|
||||
arguments: ["-R", srcURL.path, dstURL.path],
|
||||
output: .discarded,
|
||||
error: .string(limit: .max, encoding: UTF8.self),
|
||||
)
|
||||
do {
|
||||
try result.checkSuccess()
|
||||
} catch {
|
||||
print("Error copying \(srcURL.path) to \(dstURL.path): \(result.standardError ?? "unknown")")
|
||||
throw error
|
||||
}
|
||||
return
|
||||
}
|
||||
#endif
|
||||
|
||||
try self.copyItem(at: srcURL, to: dstURL)
|
||||
}
|
||||
}
|
||||
|
||||
package func stderrPrint(_ message: String, terminator: String = "\n") {
|
||||
try? FileHandle.standardError.write(contentsOf: Data("\(message)\(terminator)".utf8))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import Dependencies
|
||||
enum XToolMain {
|
||||
static func main() async throws {
|
||||
prepareDependencies { _ in
|
||||
// TODO: Improve persistence mechanism
|
||||
#warning("Improve persistence mechanism")
|
||||
// for Windows, we could use dpapi.h or wincred.h.
|
||||
// for Linux, maybe use libsecret?
|
||||
// see https://github.com/atom/node-keytar
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import PackLib
|
||||
|
||||
@Test func swiftPMDirectoryUsesXDGConfigHome() throws {
|
||||
let directory = try DarwinSDK.swiftPMDirectory(
|
||||
environment: ["XDG_CONFIG_HOME": "/xdg/config"],
|
||||
homeDirectory: URL(fileURLWithPath: "/home/test")
|
||||
)
|
||||
|
||||
#expect(directory.path == "/xdg/config/swiftpm")
|
||||
}
|
||||
|
||||
@Test func swiftPMDirectoryFallsBackToHomeDirectory() throws {
|
||||
let directory = try DarwinSDK.swiftPMDirectory(
|
||||
environment: [:],
|
||||
homeDirectory: URL(fileURLWithPath: "/home/test")
|
||||
)
|
||||
|
||||
#expect(directory.path == "/home/test/.swiftpm")
|
||||
}
|
||||
|
||||
@Test func swiftPMDirectoryRejectsRelativeXDGConfigHome() {
|
||||
#expect(throws: StringError.self) {
|
||||
try DarwinSDK.swiftPMDirectory(
|
||||
environment: ["XDG_CONFIG_HOME": "relative/config"],
|
||||
homeDirectory: URL(fileURLWithPath: "/home/test")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func temporaryDarwinSDKBundleUsesSwiftSDKsDirectory() throws {
|
||||
let configDirectory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("DarwinSDKTests-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: configDirectory) }
|
||||
|
||||
let environment = ["XDG_CONFIG_HOME": configDirectory.path]
|
||||
let sdksDirectory = configDirectory.appending(path: "swiftpm/swift-sdks")
|
||||
let temporaryURL = sdksDirectory.appendingPathComponent("darwin.artifactbundle.tmp", isDirectory: true)
|
||||
let installedBundle = sdksDirectory.appending(path: "darwin.artifactbundle")
|
||||
try FileManager.default.createDirectory(at: installedBundle, withIntermediateDirectories: true)
|
||||
try FileManager.default.createDirectory(at: temporaryURL, withIntermediateDirectories: false)
|
||||
|
||||
do {
|
||||
let temporaryBundle = try DarwinSDK.prepareTemporaryBundle(environment: environment)
|
||||
#expect(temporaryBundle.url == temporaryURL)
|
||||
#expect(!FileManager.default.fileExists(atPath: temporaryURL.path))
|
||||
|
||||
try FileManager.default.createDirectory(at: temporaryBundle.url, withIntermediateDirectories: false)
|
||||
#expect(DarwinSDK(bundle: temporaryBundle.url)?.version == "develop")
|
||||
}
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: temporaryURL.path))
|
||||
#expect(FileManager.default.fileExists(atPath: installedBundle.path))
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import Subprocess
|
||||
|
||||
enum TestXcode {
|
||||
/// A path to a copy of Xcode.app.
|
||||
///
|
||||
/// Tests that use this must be annotated with `Trait.requiresXcode`.
|
||||
static func current(sourceLocation: SourceLocation = #_sourceLocation) -> URL {
|
||||
guard let url = TestXcode._current else {
|
||||
Issue.record(
|
||||
"TestXcode.current was used without Trait.requiresXcode()",
|
||||
sourceLocation: sourceLocation
|
||||
)
|
||||
return URL(filePath: "/dev/null")
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
@TaskLocal fileprivate static var _current: URL?
|
||||
|
||||
fileprivate static let resolved = Task<URL?, Error> {
|
||||
if let xcode = ProcessInfo.processInfo.environment["XTL_TEST_XCODE_APP"], !xcode.isEmpty {
|
||||
return URL(filePath: xcode)
|
||||
}
|
||||
#if os(macOS)
|
||||
if
|
||||
let output = try await Subprocess.run(
|
||||
.path("/usr/bin/xcode-select"),
|
||||
arguments: ["-p"],
|
||||
output: .string(limit: .max, encoding: UTF8.self),
|
||||
).standardOutput?.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
output.hasSuffix(".app/Contents/Developer") {
|
||||
return URL(filePath: output).deletingLastPathComponent().deletingLastPathComponent()
|
||||
}
|
||||
#endif
|
||||
let candidate = URL(filePath: "/usr/local/share/Xcode.app")
|
||||
if FileManager.default.fileExists(atPath: candidate.path) {
|
||||
return candidate
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
struct RequiresXcodeTrait: TestTrait, SuiteTrait, TestScoping {
|
||||
func provideScope(
|
||||
for test: Test,
|
||||
testCase: Test.Case?,
|
||||
performing function: () async throws -> Void
|
||||
) async throws {
|
||||
guard let xcode = try? await TestXcode.resolved.value else {
|
||||
try Test.cancel("Could not resolve Xcode.app path. Set XTL_TEST_XCODE_APP.")
|
||||
}
|
||||
return try await TestXcode.$_current.withValue(xcode) {
|
||||
try await function()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Trait where Self == RequiresXcodeTrait {
|
||||
static var requiresXcode: Self {
|
||||
Self()
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import XKit
|
||||
|
||||
@Test func wifiAwareEntitlementMapsToDeveloperCapability() throws {
|
||||
let plist = """
|
||||
<?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>com.apple.developer.wifi-aware</key>
|
||||
<array>
|
||||
<string>Publish</string>
|
||||
<string>Subscribe</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
|
||||
let entitlements = try PropertyListDecoder().decode(
|
||||
Entitlements.self,
|
||||
from: Data(plist.utf8)
|
||||
)
|
||||
let wifiAware = try #require(
|
||||
entitlements.entitlements().compactMap { $0 as? WiFiAwareEntitlement }.first
|
||||
)
|
||||
|
||||
#expect(wifiAware.rawValue == ["Publish", "Subscribe"])
|
||||
#expect(wifiAware.capability.capabilityType.value1 == nil)
|
||||
#expect(wifiAware.capability.capabilityType.value2 == "WIFI_AWARE")
|
||||
#expect(wifiAware.capability.settings == nil)
|
||||
#expect(!wifiAware.capability.isFree)
|
||||
|
||||
let encoded = try PropertyListEncoder().encode(entitlements)
|
||||
let dictionary = try #require(
|
||||
PropertyListSerialization.propertyList(from: encoded, format: nil) as? [String: Any]
|
||||
)
|
||||
#expect(dictionary[WiFiAwareEntitlement.identifier] as? [String] == ["Publish", "Subscribe"])
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import Testing
|
||||
import Foundation
|
||||
|
||||
@Test(.requiresXcode) func validateXcode() {
|
||||
let xcode = TestXcode.current()
|
||||
let swift = xcode.appending(path: "Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift")
|
||||
#expect(
|
||||
FileManager.default.fileExists(atPath: swift.path),
|
||||
"Invalid or unrecognized layout for Xcode.app at \(xcode.path)"
|
||||
)
|
||||
}
|
||||
+2
-7
@@ -2,10 +2,8 @@ services:
|
||||
xtool:
|
||||
build:
|
||||
context: .
|
||||
target: dev
|
||||
volumes:
|
||||
- .:/xtool
|
||||
- .build/linux:/xtool/.build
|
||||
container_name: xtool
|
||||
stdin_open: true
|
||||
tty: true
|
||||
@@ -15,9 +13,6 @@ services:
|
||||
- seccomp:unconfined
|
||||
extra_hosts:
|
||||
# host.docker.internal doesn't exist by default on Linux hosts
|
||||
# TODO: Does this conflict with the default host on macOS?
|
||||
# we could rename this
|
||||
- "host.docker.internal:host-gateway"
|
||||
xtool-test:
|
||||
extends:
|
||||
service: xtool
|
||||
build:
|
||||
target: dev-test
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
xcode_path="${XTL_TEST_XCODE_APP:-}"
|
||||
|
||||
if [[ -z "$xcode_path" && $(uname -s) == "Darwin" ]]; then
|
||||
xcode_path="$(dirname $(dirname $(/usr/bin/xcode-select -p)))"
|
||||
fi
|
||||
|
||||
if [[ -z "$xcode_path" && -d /usr/local/share/Xcode.app ]]; then
|
||||
xcode_path="/usr/local/share/Xcode.app"
|
||||
fi
|
||||
|
||||
if [[ -z "$xcode_path" ]]; then
|
||||
echo "Xcode.app not found. Please set XTL_TEST_XCODE_APP."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export XTL_TEST_XCODE_APP="$xcode_path"
|
||||
|
||||
if [[ -z "${XTL_TEST_ENV:-}" ]]; then
|
||||
[[ -t 1 ]] && tty_flag="-it" || tty_flag=""
|
||||
|
||||
echo "Running"
|
||||
|
||||
exec docker compose run --build --rm -e XTL_CI=1 -v "$xcode_path":/usr/local/share/Xcode.app:ro \
|
||||
xtool-test bash -c \
|
||||
"./integration-tests/run.sh"
|
||||
fi
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
project_dir="$PWD"
|
||||
|
||||
swift build --product xtool
|
||||
swift test
|
||||
ln -fs $PWD/.build/debug/xtool /usr/local/bin/xtool
|
||||
hash -r
|
||||
|
||||
mkdir /testroot
|
||||
cd /testroot
|
||||
export XDG_CONFIG_HOME="/testroot/config"
|
||||
|
||||
echo "Installing SDK"
|
||||
xtool sdk install --slim "$XTL_TEST_XCODE_APP"
|
||||
|
||||
echo "Running tests..."
|
||||
bats "$project_dir/integration-tests/suite"
|
||||
@@ -1,21 +0,0 @@
|
||||
setup() {
|
||||
bats_require_minimum_version 1.5.0
|
||||
bats_load_library bats-support
|
||||
bats_load_library bats-assert
|
||||
}
|
||||
|
||||
@test "can run xtool" {
|
||||
xtool --version
|
||||
}
|
||||
|
||||
@test "can build a fresh app" {
|
||||
xtool new --skip-setup MyApp
|
||||
cd MyApp
|
||||
xtool dev build
|
||||
llvm-objdump -p ./xtool/MyApp.app/MyApp | grep "\bcmd LC_BUILD_VERSION\b" -a2 | grep "\bplatform ios\b"
|
||||
}
|
||||
|
||||
@test "slim sdk cannot be updated" {
|
||||
run ! xtool sdk update
|
||||
assert_output --partial "cannot be updated in place"
|
||||
}
|
||||
Reference in New Issue
Block a user