Compare commits

...

40 Commits

  • CI
  • Bundle entire Xcode.app
    Slim and normal mode
    
    Support SDK auto-updates
  • anisette: use XADI Swift Package (#258)
    ## What does this PR do?
    
    The xadi repo (https://github.com/xtool-org/xadi) now vends an
    artifactbundle for xadi, so we don't need to separately build/install it
    during the xtool build. This also makes it super easy to support macOS
    later (#259).
    
    ## How was it tested?
    
    - [x] Confirmed I can sign in (including provisioning)
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [ ] **0** - No AI was used to write code
    - [x] **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. -->
  • sdk: move DarwinSDK into PackLib (#256)
    ## What does this PR do?
    
    Mechanical move of DarwinSDK from XToolSupport -> PackLib. Needed for
    https://github.com/xtool-org/xtool/pull/229.
    
    ## How was it tested?
    
    Compiled + CI
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [x] **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. -->
  • gsa: fix auth again (#257)
    ## What does this PR do?
    
    Fixes HTTP 503 on GsService… again (followup from #244)
    
    Seems like GSA has stopped accepting `com.apple.dt.Xcode` in the client
    info string. Use `akd` instead.
    
    ## How was it tested?
    
    - [x] Logging in before failed
    - [x] Logging in after succeeds
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [x] **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. -->
  • sdk: fix permission issue when copying clang resources (#255)
    ## What does this PR do?
    
    Fixes #254 by using `cp -R` instead of `FileManager.copyItem`. The
    latter tries to preserve the original owner of files instead of using
    the caller, which fails if you're non-root and the original files are
    root-owned.
    
    ## How was it tested?
    
    I was able to repro the original issue by installing an SDK as a
    non-root user in an xtool Docker container.
    
    Applied this patch, tried `xtool sdk install` again, and it worked.
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [ ] **0** - No AI was used to write code
    - [x] **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. -->
  • docs: update contributor guide (#250)
    ## What does this PR do?
    
    Adds more info for contributors, plus AI policy.
    
    ## How was it tested?
    
    Read the docs on GitHub
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [x] **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. -->
  • http: add some debugging knobs (#249)
    ## What does this PR do?
    
    Improves support for HTTP MITM
    
    ## How was it tested?
    
    Did some MITMing on macOS + Linux via Docker, using Proxyman and
    mitmproxy. Didn't test `XTL_HTTP_PROXY` but Sol pinkie promises me that
    it's correct.
    
    ## AI tool usage
    
    How much of this PR was AI-assisted? (check one)
    
    - [ ] **0** - No AI was used to write code
    - [x] **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. -->
  • gsa: disregard keepalive (#247)
    GSA seems to, sometimes, reject HTTP requests made on a kept-alive
    connection with a 503. This was either the real root cause, or a second
    root cause, for #243. Fix this by creating a new HTTP connection for
    each GSA request.
    
    See also: https://github.com/rileytestut/AltSign/pull/52 and
    https://github.com/rileytestut/AltSign/pull/47
    
    Speculatively fixes #232
  • http: throw on unsuccessful responses (#246)
    Ref #243. `makeRequest` never inspected `response.status`, so a non-2xx
    body was
    returned as if it had succeeded. Every caller decodes that body as a
    property list
    or JSON, so Apple answering with an HTML error page surfaced as:
    
    ```
    Error: DecodingError.dataCorrupted: Data was corrupted. Debug description: The given
    data was not a valid property list.. Underlying error: ... Encountered unknown tag
    html on line 1
    ```
    
    which says nothing about what actually happened. In the case that
    prompted #243, GSA
    was returning `503 Service Temporarily Unavailable` for the `apptokens`
    operation. It
    now reads:
    
    ```
    Error: POST https://gsa.apple.com/grandslam/GsService2 failed: HTTP 503 Service
    Unavailable (text/html): <html> <head><title>503 Service Temporarily
    Unavailable</title></head> ...
    ```
    
    ### Notes
    
    - The response body is only included in the message for `text/html` and
    `text/plain`,
    i.e. gateway error pages. Bodies from the auth endpoints can carry
    account details
    (the 2FA requests use `Accept: application/x-buddyml`), and errors get
    printed
    verbatim in places such as `DevCommand.swift:164`, so those are left
    out. It also
      avoids emitting replacement characters for binary bodies.
    - The non-2xx path does not report progress, so `XADIProvider`'s
    download no longer
      prints `100%` immediately before failing.
    - Body collection moved to `collect(_:onProgress:)` so there is a single
    exit point.
      Buffer pre-sizing and progress reporting are unchanged.
    - `SDKBuilder` already does this check by hand on `send()`, so it is
    unaffected.
    
    ### Behaviour changes worth a look
    
    - `XADIProvider` writes the Apple Music APK download straight to disk; a
    failed
      download now throws instead of leaving a corrupt `applemusic.apk`.
    - The 2FA requests (`GrandSlamTrustedDeviceRequest`,
    `GrandSlamSMSAuthRequest`,
    `GrandSlamValidateRequest`) use no-op decoders, so a rejected request is
    currently
    discarded and xtool goes on to prompt for a code that was never sent —
    the symptom
      in #235. Those now fail loudly.
    
    ### Two things I left alone
    
    - `GrandSlamTwoFactorAuthenticateOperation.swift:47` catches
    `GrandSlamOperationError`
    with code `-21669` to report an incorrect verification code, but that
    error is only
    thrown by `GrandSlamOperationDecoder`, which the validate requests do
    not use, so the
    catch is unreachable. With this change a wrong code surfaces as a raw
    HTTP error
    instead. Mapping the status back to `incorrectVerificationCode` seemed
    like your call,
      since I do not know what GSA returns for a bad code.
    - If any endpoint reports errors in a decodable body under a non-2xx
    status, this guard
    would pre-empt it. I could not find one — `developerservices2` returns
    HTTP 200 with
      `resultCode`/`userString` in the body, which is untouched here.
    
    Built and linted on Linux (`swift build --product xtool`, `make lint`: 0
    violations).
    
    ---------
    
    Co-authored-by: Robetronica <noreply@Robetronica.com>
    Co-authored-by: Kabir Oberai <oberai.kabir@gmail.com>
  • gsa: update user agent to fix auth (#244)
    Fixes #243. GrandSlam seems to be rejecting clients that self-report as
    really old.
  • docs: enable copy-to-clipboard (#241)
    Ref https://github.com/swiftlang/swift-docc/pull/1273
    
    Could be a good idea to later add `nocopy` to some of the code blocks
    that aren't commands
  • Fix tmpdir reentrancy (#234)
    Previously, we would clear xtool's temporary directory on startup. This
    (practically) meant you couldn't have multiple instances running in
    parallel, because the second instance could delete the first instance's
    temp resources while the first instance still needed them. Fix this by
    having xtool instances declare locks on their temporary directories.
  • Fix clang headers (#228)
    A slightly different approach to #215.
    
    ---------
    
    Co-authored-by: sfusco <slf@stevenfusco.com>
  • Add build --sign option (#224)
    Running `xtool dev build --sign [--ipa]` will produce a codesigned
    app/ipa, without installing
  • Fix capability creation via public API (#220)
    Ref #216: the public API seems to now complain when passing in
    `capabilities`, but the field is still required when using the private
    API.
    
    Co-authored-by: sfusco <slf@stevenfusco.com>
  • fix(linux): use home cache dir to avoid tmpfs→ext4 EINVAL on SDK install (#211)
    ## Problem
    
    `xtool setup` fails on Linux Mint (and other distros) with:
    
    ```
    Error: Error Domain=NSCocoaErrorDomain Code=512 "(null)" UserInfo={
      NSUserStringVariant=["Copy"],
      NSSourceFilePathErrorKey=/tmp/sh.xtool/tmp-DarwinSDKBuild-.../darwin.artifactbundle/...,
      NSDestinationFilePath=/home/<user>/.swiftpm/swift-sdks/darwin.artifactbundle/...,
      NSUnderlyingError=Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument"
    }
    ```
    
    ## Root Cause
    
    On Linux Mint (and Ubuntu-based distros), `/tmp` is mounted as **tmpfs**
    while the home directory is on **ext4**. Foundation's
    `FileManager.copyItem` uses `sendfile(2)` internally, which returns
    `EINVAL (22)` when copying between different filesystem types.
    
    `TemporaryDirectoryRoot` defaults to
    `FileManager.default.temporaryDirectory` → `/tmp` on Linux. When `swift
    sdk install` copies the built SDK from `/tmp/sh.xtool/...` to
    `~/.swiftpm/swift-sdks/`, it crosses filesystem boundaries and fails.
    
    ## Fix
    
    On Linux, default the temp directory root to `$XDG_CACHE_HOME/xtool`
    (falling back to `~/.cache/xtool`) instead of `/tmp`. This keeps the
    build directory and install destination on the same filesystem, so the
    copy always succeeds.
    
    - `$XTL_TMPDIR` and `$TMPDIR` overrides continue to work as before
    - macOS behaviour is unchanged
    - Follows XDG Base Directory Specification
    
    ## Changes
    
    One file, `Sources/XUtils/TemporaryDirectory.swift` — 11 lines added
    inside a `#if os(Linux)` block.
    
    Fixes #181
  • Validate SDK before overwriting (#192)
    Running an invalid `sdk` subcommand like `xtool sdk list` (there's no
    `list` subcommand) is interpreted as "install the sdk at path `./list`".
    We previously unconditionally removed the existing SDK during
    installation. By switching the order so that we validate the path first,
    we avoid performing a potentially destructive action unless we have
    clear intent.
    
    See #186.
    
    Before:
    
    ```bash
    $ xtool sdk list
    Removing existing SDK... # destructive!
    Error: Could not read file or directory at path 'list'.
    ```
    
    After:
    
    ```bash
    $ xtool sdk list
    Error: Could not read file or directory at path 'list'.
      See 'xtool help sdk' for usage.
    ```
  • Bump zsign to 1.7.0 (#180)
    Includes the (speculative) fix for #14
  • Bump deployment to macOS 13, iOS 16 (#173)
    Necessary in order to pull in swift-subprocess
  • Clean up some entitlements code (#165)
    - We already do the `isFree` declarations in
    `DeveloperServiceCapability.swift`. Don't need to duplicate it on the
    entitlement types.
    - Add support for creating capabilities with raw names
  • Bump Swift version, dependencies (#166)
    Notably:
    
    - Build xtool with Swift 6.2
    - Resolve https://github.com/advisories/GHSA-xvr7-p2c6-j83w. That
    advisory shouldn't really affect us since we don't use NIO as a server
    but good hygiene anyway.
  • Enable cross import overlays (#153)
    Fixes #152
    
    We might want to figure out if there are any other flags we don't pass
    but should
  • Handle static xcframeworks not being unpacked (#156)
    SwiftPM may not unpack static xcframeworks. Handle this gracefully, if
    SwiftPM doesn't need the framework we don't either.
    
    Fixes #155.
  • Improve tmpdir management (#147)
    - We now have a single tmpdir "root" that can be recreated at launch to
    clean up old stragglers
    - The location of this tmpdir root can be controlled by `XTL_TMPDIR` or
    `TMPDIR`. In general the path is `$TMPDIR/sh.xtool`.
    
    With this change it should be possible to `export XTL_TMPDIR=/var/tmp`
    if `/tmp` doesn't have enough space, which fixes #23.
88 changed files with 2238 additions and 1656 deletions
+8
View File
@@ -0,0 +1,8 @@
*
!/Package.swift
!/Package.resolved
!/Sources
!/Tests
!/Linux
/Linux/packages
/Linux/staging
+17
View File
@@ -0,0 +1,17 @@
## 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. -->
@@ -0,0 +1,9 @@
name: 'Configure Xcode'
description: 'Set up Xcode version'
runs:
using: composite
steps:
- name: Set up Xcode
shell: bash
run: |
sudo xcode-select -s /Applications/Xcode_26.4.app
+16 -8
View File
@@ -6,6 +6,8 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
XTL_CI: "1"
jobs:
build-linux:
strategy:
@@ -19,23 +21,29 @@ jobs:
runs-on: ${{ matrix.host.runner }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build
uses: actions/checkout@v6
- name: Build and test
run: |
docker compose run --build --rm xtool swift build --product xtool
docker compose run --build -e XTL_CI=1 xtool bash -c \
"swift build --product xtool && .build/debug/xtool --help && swift test"
build-macos:
runs-on: macos-15
runs-on: macos-26
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- uses: ./.github/actions/configure-xcode
- name: Build
run: |
swift build --product xtool
swift build --product xtool && .build/debug/xtool --help
- name: Run tests
run: |
swift test
build-ios:
runs-on: macos-15
runs-on: macos-26
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- uses: ./.github/actions/configure-xcode
- name: Build
run: |
set -o pipefail \
+18
View File
@@ -0,0 +1,18 @@
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
+33 -7
View File
@@ -3,6 +3,9 @@ on:
tags:
- "*"
env:
XTL_CI: "1"
jobs:
build-linux:
strategy:
@@ -18,26 +21,28 @@ jobs:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Build
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@v4
uses: actions/upload-artifact@v7
with:
name: xtool-${{ matrix.host.arch }}
path: |
Linux/packages/xtool-${{ matrix.host.arch }}.AppImage
Linux/packages/xtool-${{ matrix.host.arch }}.AppImage.zsync
build-mac:
runs-on: macos-15
runs-on: macos-26
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v6
- uses: ./.github/actions/configure-xcode
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
@@ -55,7 +60,7 @@ jobs:
cd macOS
bundle exec fastlane package
- name: Upload artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: xtool-mac
path: |
@@ -69,9 +74,9 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Download artifact
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
pattern: xtool-*
path: output
@@ -80,3 +85,24 @@ 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 -1
View File
@@ -11,7 +11,7 @@ jobs:
swiftlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Lint
run: |
make lint SWIFTLINT_FLAGS='--reporter=github-actions-logging' | tee swiftlint.log
+10
View File
@@ -1,3 +1,13 @@
{
"swiftlint.path": "./.tmp/swiftlint/swiftlint",
"files.watcherExclude":{
"*/.git/**": true,
"*/.build/**": true,
"*/.tmp/**": true,
},
"search.exclude": {
"*/.git/**": true,
"*/.build/**": true,
"*/.tmp/**": true,
}
}
+16
View File
@@ -0,0 +1,16 @@
# 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.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+8 -21
View File
@@ -4,28 +4,15 @@
We welcome all bug reports and feature requests! Please create a [new issue](https://github.com/xtool-org/xtool/issues/new/choose) via GitHub.
## Documentation
## Code and 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).
External contributions are very welcome. Take a look at [/Documentation/Contributing/README.md](/Documentation/Contributing/README.md) for details regarding the development process.
When editing the DocC bundle, you can preview it with `make docs-preview`.
## AI tool usage
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.
You may use AI tools to assist your contributions. You are fully responsible
for everything you submit.
## 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.
- **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)
+32 -18
View File
@@ -1,7 +1,7 @@
# Note: We use 22.04 since AppImage recommends building on the
# oldest configuration that you support
FROM swift:6.1-jammy AS build-base
FROM swift:6.3-jammy AS build-base
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
@@ -66,23 +66,13 @@ RUN cd libimobiledevice \
&& make install DESTDIR=/prefix
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
FROM build-base AS build-xtool-base
COPY --from=build-limd /prefix/usr /usr
COPY --from=build-xadi /prefix/usr /usr
WORKDIR /xtool
FROM build-xtool-base AS dev
# Docker doesn't support FUSE
ENV APPIMAGE_EXTRACT_AND_RUN=1
@@ -92,6 +82,30 @@ 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
+20
View File
@@ -0,0 +1,20 @@
# 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.
+31
View File
@@ -0,0 +1,31 @@
# 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.
+1
View File
@@ -22,4 +22,5 @@ else
fi
"$docc" "$command" xtool.docc \
--enable-experimental-code-block-annotations \
--experimental-enable-custom-templates
@@ -14,16 +14,22 @@ 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.1 toolchain for your Linux distribution from <https://swift.org/install/linux>.
Install the Swift 6.3 toolchain for your Linux distribution from <https://swift.org/install/linux>.
After following the steps there, confirm that Swift is installed correctly:
```bash
swift --version
# should say something like:
# Swift version 6.1 (swift-6.1-RELEASE)
# Swift version 6.3 (swift-6.3-RELEASE)
```
### usbmuxd
@@ -62,7 +68,7 @@ sudo apt-get install usbmuxd
### Xcode.xip
Download **Xcode 16.3** from <https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_16.3/Xcode_16.3.xip>. Note the path where `Xcode_16.3.xip` is saved.
Download **Xcode 26** from <https://developer.apple.com/download/all/?q=Xcode>. Note the path where `Xcode.xip` is saved.
> Note:
>
+4
View File
@@ -56,6 +56,10 @@ 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
+142 -79
View File
@@ -1,13 +1,13 @@
{
"originHash" : "30ba8b3b894def5b779d979643d77deb698479066658be3b18dad2fb6a193579",
"originHash" : "699acd851f15c2680059dd4a90ef6f0aca240fda0f5bdda5ec4156ff0df44adf",
"pins" : [
{
"identity" : "aexml",
"kind" : "remoteSourceControl",
"location" : "https://github.com/tadija/AEXML.git",
"state" : {
"revision" : "38f7d00b23ecd891e1ee656fa6aeebd6ba04ecc3",
"version" : "4.6.1"
"revision" : "db806756c989760b35108146381535aec231092b",
"version" : "4.7.0"
}
},
{
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/async-http-client.git",
"state" : {
"revision" : "333f51104b75d1a5b94cb3b99e4c58a3b442c9f7",
"version" : "1.25.2"
"revision" : "3a5b74a58782c3b4c1f0bc75e9b67b10c2494e8f",
"version" : "1.33.1"
}
},
{
@@ -24,8 +24,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/attaswift/BigInt",
"state" : {
"revision" : "114343a705df4725dfe7ab8a2a326b8883cfd79c",
"version" : "5.5.1"
"revision" : "e07e00fa1fd435143a2dcf8b7eec9a7710b2fdfe",
"version" : "5.7.0"
}
},
{
@@ -33,8 +33,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/combine-schedulers",
"state" : {
"revision" : "5928286acce13def418ec36d05a001a9641086f2",
"version" : "1.0.3"
"revision" : "dcccb979a2183b8df3334237e3dc1ae2b4116a86",
"version" : "1.2.0"
}
},
{
@@ -51,8 +51,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/mattpolzin/OpenAPIKit",
"state" : {
"revision" : "da7d3a5ddff0dd8e5e9fdb5585d186d645bcc21b",
"version" : "3.5.0"
"revision" : "57b6318128e3f901c93f4fbf98d1c1464ec168d3",
"version" : "6.2.0"
}
},
{
@@ -69,8 +69,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/onevcat/Rainbow.git",
"state" : {
"revision" : "0c627a4f8a39ef37eadec1ceec02e4a7f55561ac",
"version" : "4.1.0"
"revision" : "cdf146ae671b2624917648b61c908d1244b98ca1",
"version" : "4.2.1"
}
},
{
@@ -96,8 +96,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser",
"state" : {
"revision" : "41982a3656a71c768319979febd796c6fd111d5c",
"version" : "1.5.0"
"revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b",
"version" : "1.7.1"
}
},
{
@@ -105,8 +105,17 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "a54383ada6cecde007d374f58f864e29370ba5c3",
"version" : "1.3.2"
"revision" : "eb50cbd14606a9161cbc5d452f18797c90ef0bab",
"version" : "1.7.0"
}
},
{
"identity" : "swift-async-algorithms",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-async-algorithms.git",
"state" : {
"revision" : "9d349bcc328ac3c31ce40e746b5882742a0d1272",
"version" : "1.1.3"
}
},
{
@@ -114,8 +123,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-atomics.git",
"state" : {
"revision" : "cd142fd2f64be2100422d658e7411e39489da985",
"version" : "1.2.0"
"revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7",
"version" : "1.3.0"
}
},
{
@@ -123,8 +132,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-certificates",
"state" : {
"revision" : "999fd70c7803da89f3904d635a6815a2a7cd7585",
"version" : "1.10.0"
"revision" : "bde8ca32a096825dfce37467137c903418c1893d",
"version" : "1.19.1"
}
},
{
@@ -139,10 +148,10 @@
{
"identity" : "swift-collections",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-collections.git",
"location" : "https://github.com/apple/swift-collections",
"state" : {
"revision" : "671108c96644956dddcd89dd59c203dcdb36cec7",
"version" : "1.1.4"
"revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a",
"version" : "1.5.1"
}
},
{
@@ -150,8 +159,17 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-concurrency-extras",
"state" : {
"revision" : "82a4ae7170d98d8538ec77238b7eb8e7199ef2e8",
"version" : "1.3.1"
"revision" : "5a3825302b1a0d744183200915a47b508c828e6f",
"version" : "1.3.2"
}
},
{
"identity" : "swift-configuration",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-configuration.git",
"state" : {
"revision" : "be76c4ad929eb6c4bcaf3351799f2adf9e6848a9",
"version" : "1.2.0"
}
},
{
@@ -159,8 +177,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto",
"state" : {
"revision" : "e8d6eba1fef23ae5b359c46b03f7d94be2f41fed",
"version" : "3.12.3"
"revision" : "1b6b2e274e85105bfa155183145a1dcfd63331f1",
"version" : "4.5.0"
}
},
{
@@ -168,17 +186,26 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-dependencies",
"state" : {
"revision" : "4c90d6b2b9bf0911af87b103bb40f41771891596",
"version" : "1.9.2"
"revision" : "706feb7858a7f6c242879d137b8ee30926aa5b26",
"version" : "1.12.0"
}
},
{
"identity" : "swift-distributed-tracing",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-distributed-tracing.git",
"state" : {
"revision" : "dc4030184203ffafbb2ec614352487235d747fe0",
"version" : "1.4.1"
}
},
{
"identity" : "swift-docc-plugin",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-docc-plugin",
"location" : "https://github.com/swiftlang/swift-docc-plugin",
"state" : {
"revision" : "85e4bb4e1cd62cec64a4b8e769dcefdf0c5b9d64",
"version" : "1.4.3"
"revision" : "647c708be89f834fa6a6d4945442793a77ddf5b6",
"version" : "1.5.0"
}
},
{
@@ -195,8 +222,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-http-structured-headers.git",
"state" : {
"revision" : "f280fc7676b9940ff2c6598642751ea333c6544f",
"version" : "1.2.2"
"revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47",
"version" : "1.7.0"
}
},
{
@@ -204,8 +231,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-http-types",
"state" : {
"revision" : "a0a57e949a8903563aba4615869310c0ebf14c03",
"version" : "1.4.0"
"revision" : "45eb0224913ea070ec4fba17291b9e7ecf4749ca",
"version" : "1.5.1"
}
},
{
@@ -213,8 +240,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log.git",
"state" : {
"revision" : "3d8596ed08bd13520157f0355e35caed215ffbfa",
"version" : "1.6.3"
"revision" : "5073617dac96330a486245e4c0179cb0a6fd2256",
"version" : "1.12.0"
}
},
{
@@ -222,8 +249,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio",
"state" : {
"revision" : "0f54d58bb5db9e064f332e8524150de379d1e51c",
"version" : "2.82.1"
"revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237",
"version" : "2.99.0"
}
},
{
@@ -231,8 +258,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-extras.git",
"state" : {
"revision" : "f1f6f772198bee35d99dd145f1513d8581a54f2c",
"version" : "1.26.0"
"revision" : "5a48717e29f62cb8326d6d42e46b562ca93847a6",
"version" : "1.34.0"
}
},
{
@@ -240,8 +267,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-http2.git",
"state" : {
"revision" : "4281466512f63d1bd530e33f4aa6993ee7864be0",
"version" : "1.36.0"
"revision" : "81cc18264f92cd307ff98430f89372711d4f6fe9",
"version" : "1.43.0"
}
},
{
@@ -249,8 +276,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-ssl.git",
"state" : {
"revision" : "6df102a39c8da5fdc2eae29a0f63546d660866fc",
"version" : "2.30.0"
"revision" : "3f337058ccd7243c4cac7911477d8ad4c598d4da",
"version" : "2.37.0"
}
},
{
@@ -258,8 +285,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-transport-services.git",
"state" : {
"revision" : "cd1e89816d345d2523b11c55654570acd5cd4c56",
"version" : "1.24.0"
"revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5",
"version" : "1.28.0"
}
},
{
@@ -267,8 +294,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-numerics.git",
"state" : {
"revision" : "e0ec0f5f3af6f3e4d5e7a19d2af26b481acb6ba8",
"version" : "1.0.3"
"revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2",
"version" : "1.1.1"
}
},
{
@@ -276,8 +303,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/swift-openapi-async-http-client",
"state" : {
"revision" : "915aeff168625b0f88a5810ee7ab8e9c00af671b",
"version" : "1.1.0"
"revision" : "3681f659d9417652b8119f0adbdf57c04b6cb292",
"version" : "1.5.0"
}
},
{
@@ -285,8 +312,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-generator",
"state" : {
"revision" : "02cab48b66b4b412013827c2938adaf0eb67dc8d",
"version" : "1.7.2"
"revision" : "5dd0da1c7da7bac8f0c458a02a76f69031137a80",
"version" : "1.12.1"
}
},
{
@@ -294,8 +321,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-runtime",
"state" : {
"revision" : "8f33cc5dfe81169fb167da73584b9c72c3e8bc23",
"version" : "1.8.2"
"revision" : "f039fa6d6338aab5164f3d1be16281524c9a8f89",
"version" : "1.11.0"
}
},
{
@@ -303,8 +330,35 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-urlsession",
"state" : {
"revision" : "6fac6f7c428d5feea2639b5f5c8b06ddfb79434b",
"version" : "1.1.0"
"revision" : "576a65b4ffb8c12ddad4950dc21eea2ef071bec2",
"version" : "1.3.0"
}
},
{
"identity" : "swift-service-context",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-service-context.git",
"state" : {
"revision" : "d0997351b0c7779017f88e7a93bc30a1878d7f29",
"version" : "1.3.0"
}
},
{
"identity" : "swift-service-lifecycle",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/swift-service-lifecycle",
"state" : {
"revision" : "9829955b385e5bb88128b73f1b8389e9b9c3191a",
"version" : "2.11.0"
}
},
{
"identity" : "swift-subprocess",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-subprocess",
"state" : {
"revision" : "11633673a41f509f8945f23c96c7acd4adafd679",
"version" : "0.5.0"
}
},
{
@@ -312,8 +366,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-syntax",
"state" : {
"revision" : "f99ae8aa18f0cf0d53481901f88a0991dc3bd4a2",
"version" : "601.0.1"
"revision" : "9de99a78f099e59caf2b2beec65a4c45d54b2081",
"version" : "603.0.1"
}
},
{
@@ -321,8 +375,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-system",
"state" : {
"revision" : "a34201439c74b53f0fd71ef11741af7e7caf01e1",
"version" : "1.4.2"
"revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df",
"version" : "1.6.4"
}
},
{
@@ -348,8 +402,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/saagarjha/unxip",
"state" : {
"revision" : "03c32d6b4e7d8a9fb58747e5f8b83397da8bf5ba",
"version" : "3.2.0"
"revision" : "6c3990517fcc4c1db6952fccf4c562fb14097601",
"version" : "3.3.0"
}
},
{
@@ -357,8 +411,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/mxcl/Version",
"state" : {
"revision" : "303a0f916772545e1e8667d3104f83be708a723c",
"version" : "2.1.0"
"revision" : "3043fcd2a50375db76d89ff206a612471833d1c2",
"version" : "2.2.1"
}
},
{
@@ -366,8 +420,17 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/websocket-kit.git",
"state" : {
"revision" : "014ccd52891b8c098d7e1033d5e72ed76fef7a86",
"version" : "2.16.0"
"revision" : "90bbbdab3ede12c803cfbe91646f291c092517a3",
"version" : "2.16.2"
}
},
{
"identity" : "xadi",
"kind" : "remoteSourceControl",
"location" : "https://github.com/xtool-org/xadi",
"state" : {
"revision" : "831f8ddfc72f7a48d0c2c03ac9c864eee1f8f6b3",
"version" : "0.4.0"
}
},
{
@@ -375,8 +438,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/yonaskolb/XcodeGen",
"state" : {
"revision" : "7193eb447a6f60061f069e07bc1efd32d73c0e19",
"version" : "2.43.0"
"revision" : "8d3d3476a69ae3e5d68e1adccc701c410c05eb36",
"version" : "2.45.4"
}
},
{
@@ -384,8 +447,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/tuist/XcodeProj.git",
"state" : {
"revision" : "dc3b87a4e69f9cd06c6cb16199f5d0472e57ef6b",
"version" : "8.24.3"
"revision" : "01bb77000bc8c23a09ea2058f4954612f03cb705",
"version" : "9.10.1"
}
},
{
@@ -393,8 +456,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/xctest-dynamic-overlay",
"state" : {
"revision" : "39de59b2d47f7ef3ca88a039dff3084688fe27f4",
"version" : "1.5.2"
"revision" : "dfd70507def84cb5fb821278448a262c6ff2bbad",
"version" : "1.9.0"
}
},
{
@@ -411,8 +474,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/jpsim/Yams",
"state" : {
"revision" : "b4b8042411dc7bbb696300a34a4bf3ba1b7ad19b",
"version" : "5.3.1"
"revision" : "3d6871d5b4a5cd519adf233fbb576e0a2af71c17",
"version" : "5.4.0"
}
},
{
@@ -420,8 +483,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/xtool-org/zsign",
"state" : {
"revision" : "fb10d47dd24bb84886532497bac149232e67f07a",
"version" : "1.6.0"
"revision" : "6c4a9f52dd8bf374aa938ef9c17d5f261f2c333a",
"version" : "1.7.0"
}
}
],
+47 -28
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.0
// swift-tools-version:6.2
import PackageDescription
@@ -19,11 +19,19 @@ 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: [
.iOS(.v15),
.macOS(.v12),
.iOS(.v16),
.macOS(.v13),
],
products: [
.library(
@@ -42,18 +50,21 @@ let package = Package(
dependencies: [
.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.6.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"),
.package(url: "https://github.com/apple/swift-certificates", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-crypto", from: "3.9.1"),
.package(url: "https://github.com/apple/swift-crypto", from: "4.5.0"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
.package(url: "https://github.com/apple/swift-openapi-generator", from: "1.6.0"),
.package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-openapi-urlsession", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-nio", from: "2.77.0"),
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"),
.package(url: "https://github.com/swiftlang/swift-subprocess", .upToNextMinor(from: "0.5.0")),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.23.0"),
.package(url: "https://github.com/swift-server/swift-openapi-async-http-client", from: "1.0.0"),
@@ -68,10 +79,9 @@ let package = Package(
.package(url: "https://github.com/saagarjha/unxip", from: "3.2.0"),
// TODO: just depend on tuist/XcodeProj instead
.package(url: "https://github.com/yonaskolb/XcodeGen", from: "2.43.0"),
.package(url: "https://github.com/yonaskolb/XcodeGen", from: "2.45.4"),
],
targets: [
.systemLibrary(name: "XADI"),
.target(
name: "CXKit",
dependencies: [
@@ -88,14 +98,29 @@ let package = Package(
dependencies: [
.product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
],
exclude: ["openapi-generator-config.yaml", "patch.js"]
exclude: ["openapi-generator-config.yaml", "patch.js"],
swiftSettings: swiftSettings,
),
// common utilities shared across xtool targets
.target(
name: "XUtils",
dependencies: [
.product(name: "SystemPackage", package: "swift-system"),
.product(
name: "Subprocess",
package: "swift-subprocess",
condition: .when(platforms: [.linux, .macOS])
),
],
swiftSettings: swiftSettings,
),
.target(
name: "XKit",
dependencies: [
"DeveloperAPI",
"CXKit",
.byName(name: "XADI", condition: .when(platforms: [.linux])),
"XUtils",
.product(name: "XADI", package: "xadi", condition: .when(platforms: [.linux])),
.product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"),
.product(name: "Dependencies", package: "swift-dependencies"),
.product(name: "SwiftyMobileDevice", package: "SwiftyMobileDevice"),
@@ -126,27 +151,16 @@ let package = Package(
condition: .when(platforms: [.linux])
),
],
cSettings: cSettings
cSettings: cSettings,
swiftSettings: swiftSettings,
),
.testTarget(
name: "XToolTests",
dependencies: [
"XToolSupport",
]
),
.testTarget(
name: "XKitTests",
dependencies: [
"XKit",
.product(name: "SuperutilsTestSupport", package: "xtool-core")
"XToolSupport",
],
exclude: [
"config/config-template.json",
],
resources: [
.copy("config/config.json"),
.copy("config/test.app"),
]
swiftSettings: swiftSettings,
),
.target(
name: "XToolSupport",
@@ -160,14 +174,18 @@ let package = Package(
.product(name: "Version", package: "Version"),
.product(name: "libunxip", package: "unxip"),
],
cSettings: cSettings
cSettings: cSettings,
swiftSettings: swiftSettings,
),
.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",
@@ -176,7 +194,8 @@ let package = Package(
"XKit",
"XToolSupport",
],
cSettings: cSettings
cSettings: cSettings,
swiftSettings: swiftSettings,
),
]
)
@@ -575,28 +575,6 @@ public struct DeveloperAPIClient: APIProtocol {
preconditionFailure("bestContentType chose an invalid content type.")
}
return .notFound(.init(body: body))
case 409:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.BundleIdCapabilitiesDeleteInstance.Output.Conflict.Body
let chosenContentType = try converter.bestContentType(
received: contentType,
options: [
"application/json"
]
)
switch chosenContentType {
case "application/json":
body = try await converter.getResponseBodyAsJSON(
Components.Schemas.ErrorResponse.self,
from: responseBody,
transforming: { value in
.json(value)
}
)
default:
preconditionFailure("bestContentType chose an invalid content type.")
}
return .conflict(.init(body: body))
case 429:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.BundleIdCapabilitiesDeleteInstance.Output.TooManyRequests.Body
@@ -1632,28 +1610,6 @@ public struct DeveloperAPIClient: APIProtocol {
preconditionFailure("bestContentType chose an invalid content type.")
}
return .notFound(.init(body: body))
case 409:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.BundleIdsDeleteInstance.Output.Conflict.Body
let chosenContentType = try converter.bestContentType(
received: contentType,
options: [
"application/json"
]
)
switch chosenContentType {
case "application/json":
body = try await converter.getResponseBodyAsJSON(
Components.Schemas.ErrorResponse.self,
from: responseBody,
transforming: { value in
.json(value)
}
)
default:
preconditionFailure("bestContentType chose an invalid content type.")
}
return .conflict(.init(body: body))
case 429:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.BundleIdsDeleteInstance.Output.TooManyRequests.Body
@@ -2626,28 +2582,6 @@ public struct DeveloperAPIClient: APIProtocol {
preconditionFailure("bestContentType chose an invalid content type.")
}
return .notFound(.init(body: body))
case 409:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.CertificatesDeleteInstance.Output.Conflict.Body
let chosenContentType = try converter.bestContentType(
received: contentType,
options: [
"application/json"
]
)
switch chosenContentType {
case "application/json":
body = try await converter.getResponseBodyAsJSON(
Components.Schemas.ErrorResponse.self,
from: responseBody,
transforming: { value in
.json(value)
}
)
default:
preconditionFailure("bestContentType chose an invalid content type.")
}
return .conflict(.init(body: body))
case 429:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.CertificatesDeleteInstance.Output.TooManyRequests.Body
@@ -4254,28 +4188,6 @@ public struct DeveloperAPIClient: APIProtocol {
preconditionFailure("bestContentType chose an invalid content type.")
}
return .notFound(.init(body: body))
case 409:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.ProfilesDeleteInstance.Output.Conflict.Body
let chosenContentType = try converter.bestContentType(
received: contentType,
options: [
"application/json"
]
)
switch chosenContentType {
case "application/json":
body = try await converter.getResponseBodyAsJSON(
Components.Schemas.ErrorResponse.self,
from: responseBody,
transforming: { value in
.json(value)
}
)
default:
preconditionFailure("bestContentType chose an invalid content type.")
}
return .conflict(.init(body: body))
case 429:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Operations.ProfilesDeleteInstance.Output.TooManyRequests.Body
+316 -385
View File
@@ -794,6 +794,50 @@ public enum Components {
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appEncryptionDeclarations`.
public var appEncryptionDeclarations: Components.Schemas.App.RelationshipsPayload.AppEncryptionDeclarationsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon`.
public struct AppStoreIconPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon/data`.
public struct DataPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon/data/type`.
@frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable {
case buildIcons = "buildIcons"
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon/data/type`.
public var _type: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload.DataPayload._TypePayload
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon/data/id`.
public var id: Swift.String
/// Creates a new `DataPayload`.
///
/// - Parameters:
/// - _type:
/// - id:
public init(
_type: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload.DataPayload._TypePayload,
id: Swift.String
) {
self._type = _type
self.id = id
}
public enum CodingKeys: String, CodingKey {
case _type = "type"
case id
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon/data`.
public var data: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload.DataPayload?
/// Creates a new `AppStoreIconPayload`.
///
/// - Parameters:
/// - data:
public init(data: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload.DataPayload? = nil) {
self.data = data
}
public enum CodingKeys: String, CodingKey {
case data
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreIcon`.
public var appStoreIcon: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/ciProduct`.
public struct CiProductPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/ciProduct/links`.
@@ -983,6 +1027,23 @@ public enum Components {
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appStoreVersions`.
public var appStoreVersions: Components.Schemas.App.RelationshipsPayload.AppStoreVersionsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/appTags`.
public struct AppTagsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/appTags/links`.
public var links: Components.Schemas.RelationshipLinks?
/// Creates a new `AppTagsPayload`.
///
/// - Parameters:
/// - links:
public init(links: Components.Schemas.RelationshipLinks? = nil) {
self.links = links
}
public enum CodingKeys: String, CodingKey {
case links
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/appTags`.
public var appTags: Components.Schemas.App.RelationshipsPayload.AppTagsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/preReleaseVersions`.
public struct PreReleaseVersionsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/preReleaseVersions/links`.
@@ -2236,6 +2297,23 @@ public enum Components {
}
/// - Remark: Generated from `#/components/schemas/App/relationships/marketplaceSearchDetail`.
public var marketplaceSearchDetail: Components.Schemas.App.RelationshipsPayload.MarketplaceSearchDetailPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/buildUploads`.
public struct BuildUploadsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/buildUploads/links`.
public var links: Components.Schemas.RelationshipLinks?
/// Creates a new `BuildUploadsPayload`.
///
/// - Parameters:
/// - links:
public init(links: Components.Schemas.RelationshipLinks? = nil) {
self.links = links
}
public enum CodingKeys: String, CodingKey {
case links
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/buildUploads`.
public var buildUploads: Components.Schemas.App.RelationshipsPayload.BuildUploadsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/backgroundAssets`.
public struct BackgroundAssetsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/backgroundAssets/links`.
@@ -2287,6 +2365,23 @@ public enum Components {
}
/// - Remark: Generated from `#/components/schemas/App/relationships/betaFeedbackCrashSubmissions`.
public var betaFeedbackCrashSubmissions: Components.Schemas.App.RelationshipsPayload.BetaFeedbackCrashSubmissionsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/searchKeywords`.
public struct SearchKeywordsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/searchKeywords/links`.
public var links: Components.Schemas.RelationshipLinks?
/// Creates a new `SearchKeywordsPayload`.
///
/// - Parameters:
/// - links:
public init(links: Components.Schemas.RelationshipLinks? = nil) {
self.links = links
}
public enum CodingKeys: String, CodingKey {
case links
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/searchKeywords`.
public var searchKeywords: Components.Schemas.App.RelationshipsPayload.SearchKeywordsPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/webhooks`.
public struct WebhooksPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/webhooks/links`.
@@ -2304,15 +2399,77 @@ public enum Components {
}
/// - Remark: Generated from `#/components/schemas/App/relationships/webhooks`.
public var webhooks: Components.Schemas.App.RelationshipsPayload.WebhooksPayload?
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails`.
public struct AndroidToIosAppMappingDetailsPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/links`.
public var links: Components.Schemas.RelationshipLinks?
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/meta`.
public var meta: Components.Schemas.PagingInformation?
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/DataPayload`.
public struct DataPayloadPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/DataPayload/type`.
@frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable {
case androidToIosAppMappingDetails = "androidToIosAppMappingDetails"
}
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/DataPayload/type`.
public var _type: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload.DataPayloadPayload._TypePayload
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/DataPayload/id`.
public var id: Swift.String
/// Creates a new `DataPayloadPayload`.
///
/// - Parameters:
/// - _type:
/// - id:
public init(
_type: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload.DataPayloadPayload._TypePayload,
id: Swift.String
) {
self._type = _type
self.id = id
}
public enum CodingKeys: String, CodingKey {
case _type = "type"
case id
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/data`.
public typealias DataPayload = [Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload.DataPayloadPayload]
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails/data`.
public var data: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload.DataPayload?
/// Creates a new `AndroidToIosAppMappingDetailsPayload`.
///
/// - Parameters:
/// - links:
/// - meta:
/// - data:
public init(
links: Components.Schemas.RelationshipLinks? = nil,
meta: Components.Schemas.PagingInformation? = nil,
data: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload.DataPayload? = nil
) {
self.links = links
self.meta = meta
self.data = data
}
public enum CodingKeys: String, CodingKey {
case links
case meta
case data
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships/androidToIosAppMappingDetails`.
public var androidToIosAppMappingDetails: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload?
/// Creates a new `RelationshipsPayload`.
///
/// - Parameters:
/// - accessibilityDeclarations:
/// - appEncryptionDeclarations:
/// - appStoreIcon:
/// - ciProduct:
/// - betaTesters:
/// - betaGroups:
/// - appStoreVersions:
/// - appTags:
/// - preReleaseVersions:
/// - betaAppLocalizations:
/// - builds:
@@ -2341,17 +2498,22 @@ public enum Components {
/// - alternativeDistributionKey:
/// - analyticsReportRequests:
/// - marketplaceSearchDetail:
/// - buildUploads:
/// - backgroundAssets:
/// - betaFeedbackScreenshotSubmissions:
/// - betaFeedbackCrashSubmissions:
/// - searchKeywords:
/// - webhooks:
/// - androidToIosAppMappingDetails:
public init(
accessibilityDeclarations: Components.Schemas.App.RelationshipsPayload.AccessibilityDeclarationsPayload? = nil,
appEncryptionDeclarations: Components.Schemas.App.RelationshipsPayload.AppEncryptionDeclarationsPayload? = nil,
appStoreIcon: Components.Schemas.App.RelationshipsPayload.AppStoreIconPayload? = nil,
ciProduct: Components.Schemas.App.RelationshipsPayload.CiProductPayload? = nil,
betaTesters: Components.Schemas.App.RelationshipsPayload.BetaTestersPayload? = nil,
betaGroups: Components.Schemas.App.RelationshipsPayload.BetaGroupsPayload? = nil,
appStoreVersions: Components.Schemas.App.RelationshipsPayload.AppStoreVersionsPayload? = nil,
appTags: Components.Schemas.App.RelationshipsPayload.AppTagsPayload? = nil,
preReleaseVersions: Components.Schemas.App.RelationshipsPayload.PreReleaseVersionsPayload? = nil,
betaAppLocalizations: Components.Schemas.App.RelationshipsPayload.BetaAppLocalizationsPayload? = nil,
builds: Components.Schemas.App.RelationshipsPayload.BuildsPayload? = nil,
@@ -2380,17 +2542,22 @@ public enum Components {
alternativeDistributionKey: Components.Schemas.App.RelationshipsPayload.AlternativeDistributionKeyPayload? = nil,
analyticsReportRequests: Components.Schemas.App.RelationshipsPayload.AnalyticsReportRequestsPayload? = nil,
marketplaceSearchDetail: Components.Schemas.App.RelationshipsPayload.MarketplaceSearchDetailPayload? = nil,
buildUploads: Components.Schemas.App.RelationshipsPayload.BuildUploadsPayload? = nil,
backgroundAssets: Components.Schemas.App.RelationshipsPayload.BackgroundAssetsPayload? = nil,
betaFeedbackScreenshotSubmissions: Components.Schemas.App.RelationshipsPayload.BetaFeedbackScreenshotSubmissionsPayload? = nil,
betaFeedbackCrashSubmissions: Components.Schemas.App.RelationshipsPayload.BetaFeedbackCrashSubmissionsPayload? = nil,
webhooks: Components.Schemas.App.RelationshipsPayload.WebhooksPayload? = nil
searchKeywords: Components.Schemas.App.RelationshipsPayload.SearchKeywordsPayload? = nil,
webhooks: Components.Schemas.App.RelationshipsPayload.WebhooksPayload? = nil,
androidToIosAppMappingDetails: Components.Schemas.App.RelationshipsPayload.AndroidToIosAppMappingDetailsPayload? = nil
) {
self.accessibilityDeclarations = accessibilityDeclarations
self.appEncryptionDeclarations = appEncryptionDeclarations
self.appStoreIcon = appStoreIcon
self.ciProduct = ciProduct
self.betaTesters = betaTesters
self.betaGroups = betaGroups
self.appStoreVersions = appStoreVersions
self.appTags = appTags
self.preReleaseVersions = preReleaseVersions
self.betaAppLocalizations = betaAppLocalizations
self.builds = builds
@@ -2419,18 +2586,23 @@ public enum Components {
self.alternativeDistributionKey = alternativeDistributionKey
self.analyticsReportRequests = analyticsReportRequests
self.marketplaceSearchDetail = marketplaceSearchDetail
self.buildUploads = buildUploads
self.backgroundAssets = backgroundAssets
self.betaFeedbackScreenshotSubmissions = betaFeedbackScreenshotSubmissions
self.betaFeedbackCrashSubmissions = betaFeedbackCrashSubmissions
self.searchKeywords = searchKeywords
self.webhooks = webhooks
self.androidToIosAppMappingDetails = androidToIosAppMappingDetails
}
public enum CodingKeys: String, CodingKey {
case accessibilityDeclarations
case appEncryptionDeclarations
case appStoreIcon
case ciProduct
case betaTesters
case betaGroups
case appStoreVersions
case appTags
case preReleaseVersions
case betaAppLocalizations
case builds
@@ -2459,10 +2631,13 @@ public enum Components {
case alternativeDistributionKey
case analyticsReportRequests
case marketplaceSearchDetail
case buildUploads
case backgroundAssets
case betaFeedbackScreenshotSubmissions
case betaFeedbackCrashSubmissions
case searchKeywords
case webhooks
case androidToIosAppMappingDetails
}
}
/// - Remark: Generated from `#/components/schemas/App/relationships`.
@@ -2707,7 +2882,7 @@ public enum Components {
}
}
/// - Remark: Generated from `#/components/schemas/BundleIdCapabilityCreateRequest/data/relationships/capability`.
public var capability: Components.Schemas.BundleIdCapabilityCreateRequest.DataPayload.RelationshipsPayload.CapabilityPayload
public var capability: Components.Schemas.BundleIdCapabilityCreateRequest.DataPayload.RelationshipsPayload.CapabilityPayload?
/// Creates a new `RelationshipsPayload`.
///
/// - Parameters:
@@ -2715,7 +2890,7 @@ public enum Components {
/// - capability:
public init(
bundleId: Components.Schemas.BundleIdCapabilityCreateRequest.DataPayload.RelationshipsPayload.BundleIdPayload,
capability: Components.Schemas.BundleIdCapabilityCreateRequest.DataPayload.RelationshipsPayload.CapabilityPayload
capability: Components.Schemas.BundleIdCapabilityCreateRequest.DataPayload.RelationshipsPayload.CapabilityPayload? = nil
) {
self.bundleId = bundleId
self.capability = capability
@@ -3113,45 +3288,43 @@ public enum Components {
public var data: [Components.Schemas.BundleId]
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload`.
@frozen public enum IncludedPayloadPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/case1`.
case Profile(Components.Schemas.Profile)
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/case2`.
case BundleIdCapability(Components.Schemas.BundleIdCapability)
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/case3`.
case App(Components.Schemas.App)
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/App`.
case apps(Components.Schemas.App)
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/BundleIdCapability`.
case bundleIdCapabilities(Components.Schemas.BundleIdCapability)
/// - Remark: Generated from `#/components/schemas/BundleIdsResponse/IncludedPayload/Profile`.
case profiles(Components.Schemas.Profile)
public enum CodingKeys: String, CodingKey {
case _type = "type"
}
public init(from decoder: any Decoder) throws {
var errors: [any Error] = []
do {
self = .Profile(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .BundleIdCapability(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .App(try .init(from: decoder))
return
} catch {
errors.append(error)
}
throw Swift.DecodingError.failedToDecodeOneOfSchema(
type: Self.self,
codingPath: decoder.codingPath,
errors: errors
let container = try decoder.container(keyedBy: CodingKeys.self)
let discriminator = try container.decode(
Swift.String.self,
forKey: ._type
)
switch discriminator {
case "apps":
self = .apps(try .init(from: decoder))
case "bundleIdCapabilities":
self = .bundleIdCapabilities(try .init(from: decoder))
case "profiles":
self = .profiles(try .init(from: decoder))
default:
throw Swift.DecodingError.unknownOneOfDiscriminator(
discriminatorKey: CodingKeys._type,
discriminatorValue: discriminator,
codingPath: decoder.codingPath
)
}
}
public func encode(to encoder: any Encoder) throws {
switch self {
case let .Profile(value):
case let .apps(value):
try value.encode(to: encoder)
case let .BundleIdCapability(value):
case let .bundleIdCapabilities(value):
try value.encode(to: encoder)
case let .App(value):
case let .profiles(value):
try value.encode(to: encoder)
}
}
@@ -3195,45 +3368,43 @@ public enum Components {
public var data: Components.Schemas.BundleId
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload`.
@frozen public enum IncludedPayloadPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/case1`.
case Profile(Components.Schemas.Profile)
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/case2`.
case BundleIdCapability(Components.Schemas.BundleIdCapability)
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/case3`.
case App(Components.Schemas.App)
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/App`.
case apps(Components.Schemas.App)
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/BundleIdCapability`.
case bundleIdCapabilities(Components.Schemas.BundleIdCapability)
/// - Remark: Generated from `#/components/schemas/BundleIdResponse/IncludedPayload/Profile`.
case profiles(Components.Schemas.Profile)
public enum CodingKeys: String, CodingKey {
case _type = "type"
}
public init(from decoder: any Decoder) throws {
var errors: [any Error] = []
do {
self = .Profile(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .BundleIdCapability(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .App(try .init(from: decoder))
return
} catch {
errors.append(error)
}
throw Swift.DecodingError.failedToDecodeOneOfSchema(
type: Self.self,
codingPath: decoder.codingPath,
errors: errors
let container = try decoder.container(keyedBy: CodingKeys.self)
let discriminator = try container.decode(
Swift.String.self,
forKey: ._type
)
switch discriminator {
case "apps":
self = .apps(try .init(from: decoder))
case "bundleIdCapabilities":
self = .bundleIdCapabilities(try .init(from: decoder))
case "profiles":
self = .profiles(try .init(from: decoder))
default:
throw Swift.DecodingError.unknownOneOfDiscriminator(
discriminatorKey: CodingKeys._type,
discriminatorValue: discriminator,
codingPath: decoder.codingPath
)
}
}
public func encode(to encoder: any Encoder) throws {
switch self {
case let .Profile(value):
case let .apps(value):
try value.encode(to: encoder)
case let .BundleIdCapability(value):
case let .bundleIdCapabilities(value):
try value.encode(to: encoder)
case let .App(value):
case let .profiles(value):
try value.encode(to: encoder)
}
}
@@ -4220,56 +4391,9 @@ public enum Components {
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/name`.
public var name: Swift.String?
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/status`.
public struct StatusPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/status/value1`.
@frozen public enum Value1Payload: String, Codable, Hashable, Sendable, CaseIterable {
case enabled = "ENABLED"
case disabled = "DISABLED"
}
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/status/value1`.
public var value1: Components.Schemas.DeviceUpdateRequest.DataPayload.AttributesPayload.StatusPayload.Value1Payload?
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/status/value2`.
public var value2: Swift.String?
/// Creates a new `StatusPayload`.
///
/// - Parameters:
/// - value1:
/// - value2:
public init(
value1: Components.Schemas.DeviceUpdateRequest.DataPayload.AttributesPayload.StatusPayload.Value1Payload? = nil,
value2: Swift.String? = nil
) {
self.value1 = value1
self.value2 = value2
}
public init(from decoder: any Decoder) throws {
var errors: [any Error] = []
do {
self.value1 = try decoder.decodeFromSingleValueContainer()
} catch {
errors.append(error)
}
do {
self.value2 = try decoder.decodeFromSingleValueContainer()
} catch {
errors.append(error)
}
try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil(
[
self.value1,
self.value2
],
type: Self.self,
codingPath: decoder.codingPath,
errors: errors
)
}
public func encode(to encoder: any Encoder) throws {
try encoder.encodeFirstNonNilValueToSingleValueContainer([
self.value1,
self.value2
])
}
@frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable {
case enabled = "ENABLED"
case disabled = "DISABLED"
}
/// - Remark: Generated from `#/components/schemas/DeviceUpdateRequest/data/attributes/status`.
public var status: Components.Schemas.DeviceUpdateRequest.DataPayload.AttributesPayload.StatusPayload?
@@ -4917,45 +5041,43 @@ public enum Components {
public var data: [Components.Schemas.Profile]
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload`.
@frozen public enum IncludedPayloadPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/case1`.
case BundleId(Components.Schemas.BundleId)
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/case2`.
case Device(Components.Schemas.Device)
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/case3`.
case Certificate(Components.Schemas.Certificate)
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/BundleId`.
case bundleIds(Components.Schemas.BundleId)
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/Certificate`.
case certificates(Components.Schemas.Certificate)
/// - Remark: Generated from `#/components/schemas/ProfilesResponse/IncludedPayload/Device`.
case devices(Components.Schemas.Device)
public enum CodingKeys: String, CodingKey {
case _type = "type"
}
public init(from decoder: any Decoder) throws {
var errors: [any Error] = []
do {
self = .BundleId(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .Device(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .Certificate(try .init(from: decoder))
return
} catch {
errors.append(error)
}
throw Swift.DecodingError.failedToDecodeOneOfSchema(
type: Self.self,
codingPath: decoder.codingPath,
errors: errors
let container = try decoder.container(keyedBy: CodingKeys.self)
let discriminator = try container.decode(
Swift.String.self,
forKey: ._type
)
switch discriminator {
case "bundleIds":
self = .bundleIds(try .init(from: decoder))
case "certificates":
self = .certificates(try .init(from: decoder))
case "devices":
self = .devices(try .init(from: decoder))
default:
throw Swift.DecodingError.unknownOneOfDiscriminator(
discriminatorKey: CodingKeys._type,
discriminatorValue: discriminator,
codingPath: decoder.codingPath
)
}
}
public func encode(to encoder: any Encoder) throws {
switch self {
case let .BundleId(value):
case let .bundleIds(value):
try value.encode(to: encoder)
case let .Device(value):
case let .certificates(value):
try value.encode(to: encoder)
case let .Certificate(value):
case let .devices(value):
try value.encode(to: encoder)
}
}
@@ -4999,45 +5121,43 @@ public enum Components {
public var data: Components.Schemas.Profile
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload`.
@frozen public enum IncludedPayloadPayload: Codable, Hashable, Sendable {
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/case1`.
case BundleId(Components.Schemas.BundleId)
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/case2`.
case Device(Components.Schemas.Device)
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/case3`.
case Certificate(Components.Schemas.Certificate)
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/BundleId`.
case bundleIds(Components.Schemas.BundleId)
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/Certificate`.
case certificates(Components.Schemas.Certificate)
/// - Remark: Generated from `#/components/schemas/ProfileResponse/IncludedPayload/Device`.
case devices(Components.Schemas.Device)
public enum CodingKeys: String, CodingKey {
case _type = "type"
}
public init(from decoder: any Decoder) throws {
var errors: [any Error] = []
do {
self = .BundleId(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .Device(try .init(from: decoder))
return
} catch {
errors.append(error)
}
do {
self = .Certificate(try .init(from: decoder))
return
} catch {
errors.append(error)
}
throw Swift.DecodingError.failedToDecodeOneOfSchema(
type: Self.self,
codingPath: decoder.codingPath,
errors: errors
let container = try decoder.container(keyedBy: CodingKeys.self)
let discriminator = try container.decode(
Swift.String.self,
forKey: ._type
)
switch discriminator {
case "bundleIds":
self = .bundleIds(try .init(from: decoder))
case "certificates":
self = .certificates(try .init(from: decoder))
case "devices":
self = .devices(try .init(from: decoder))
default:
throw Swift.DecodingError.unknownOneOfDiscriminator(
discriminatorKey: CodingKeys._type,
discriminatorValue: discriminator,
codingPath: decoder.codingPath
)
}
}
public func encode(to encoder: any Encoder) throws {
switch self {
case let .BundleId(value):
case let .bundleIds(value):
try value.encode(to: encoder)
case let .Device(value):
case let .certificates(value):
try value.encode(to: encoder)
case let .Certificate(value):
case let .devices(value):
try value.encode(to: encoder)
}
}
@@ -8024,57 +8144,6 @@ public enum Operations {
}
}
}
public struct Conflict: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIdCapabilities/{id}/DELETE/responses/409/content`.
@frozen public enum Body: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIdCapabilities/{id}/DELETE/responses/409/content/application\/json`.
case json(Components.Schemas.ErrorResponse)
/// The associated value of the enum case if `self` is `.json`.
///
/// - Throws: An error if `self` is not `.json`.
/// - SeeAlso: `.json`.
public var json: Components.Schemas.ErrorResponse {
get throws {
switch self {
case let .json(body):
return body
}
}
}
}
/// Received HTTP response body
public var body: Operations.BundleIdCapabilitiesDeleteInstance.Output.Conflict.Body
/// Creates a new `Conflict`.
///
/// - Parameters:
/// - body: Received HTTP response body
public init(body: Operations.BundleIdCapabilitiesDeleteInstance.Output.Conflict.Body) {
self.body = body
}
}
/// Request entity error(s)
///
/// - Remark: Generated from `#/paths//v1/bundleIdCapabilities/{id}/delete(bundleIdCapabilities_deleteInstance)/responses/409`.
///
/// HTTP response code: `409 conflict`.
case conflict(Operations.BundleIdCapabilitiesDeleteInstance.Output.Conflict)
/// The associated value of the enum case if `self` is `.conflict`.
///
/// - Throws: An error if `self` is not `.conflict`.
/// - SeeAlso: `.conflict`.
public var conflict: Operations.BundleIdCapabilitiesDeleteInstance.Output.Conflict {
get throws {
switch self {
case let .conflict(response):
return response
default:
try throwUnexpectedResponseStatus(
expectedStatus: "conflict",
response: self
)
}
}
}
public struct TooManyRequests: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIdCapabilities/{id}/DELETE/responses/429/content`.
@frozen public enum Body: Sendable, Hashable {
@@ -8274,10 +8343,12 @@ public enum Operations {
case streamlinedPurchasingEnabled = "streamlinedPurchasingEnabled"
case accessibilityDeclarations = "accessibilityDeclarations"
case appEncryptionDeclarations = "appEncryptionDeclarations"
case appStoreIcon = "appStoreIcon"
case ciProduct = "ciProduct"
case betaTesters = "betaTesters"
case betaGroups = "betaGroups"
case appStoreVersions = "appStoreVersions"
case appTags = "appTags"
case preReleaseVersions = "preReleaseVersions"
case betaAppLocalizations = "betaAppLocalizations"
case builds = "builds"
@@ -8306,10 +8377,13 @@ public enum Operations {
case alternativeDistributionKey = "alternativeDistributionKey"
case analyticsReportRequests = "analyticsReportRequests"
case marketplaceSearchDetail = "marketplaceSearchDetail"
case buildUploads = "buildUploads"
case backgroundAssets = "backgroundAssets"
case betaFeedbackScreenshotSubmissions = "betaFeedbackScreenshotSubmissions"
case betaFeedbackCrashSubmissions = "betaFeedbackCrashSubmissions"
case searchKeywords = "searchKeywords"
case webhooks = "webhooks"
case androidToIosAppMappingDetails = "androidToIosAppMappingDetails"
}
/// - Remark: Generated from `#/paths/v1/bundleIds/GET/query/fields[apps]`.
public typealias Fields_lbrack_apps_rbrack_Payload = [Operations.BundleIdsGetCollection.Input.Query.FieldsLbrackAppsRbrackPayloadPayload]
@@ -9213,10 +9287,12 @@ public enum Operations {
case streamlinedPurchasingEnabled = "streamlinedPurchasingEnabled"
case accessibilityDeclarations = "accessibilityDeclarations"
case appEncryptionDeclarations = "appEncryptionDeclarations"
case appStoreIcon = "appStoreIcon"
case ciProduct = "ciProduct"
case betaTesters = "betaTesters"
case betaGroups = "betaGroups"
case appStoreVersions = "appStoreVersions"
case appTags = "appTags"
case preReleaseVersions = "preReleaseVersions"
case betaAppLocalizations = "betaAppLocalizations"
case builds = "builds"
@@ -9245,10 +9321,13 @@ public enum Operations {
case alternativeDistributionKey = "alternativeDistributionKey"
case analyticsReportRequests = "analyticsReportRequests"
case marketplaceSearchDetail = "marketplaceSearchDetail"
case buildUploads = "buildUploads"
case backgroundAssets = "backgroundAssets"
case betaFeedbackScreenshotSubmissions = "betaFeedbackScreenshotSubmissions"
case betaFeedbackCrashSubmissions = "betaFeedbackCrashSubmissions"
case searchKeywords = "searchKeywords"
case webhooks = "webhooks"
case androidToIosAppMappingDetails = "androidToIosAppMappingDetails"
}
/// - Remark: Generated from `#/paths/v1/bundleIds/{id}/GET/query/fields[apps]`.
public typealias Fields_lbrack_apps_rbrack_Payload = [Operations.BundleIdsGetInstance.Input.Query.FieldsLbrackAppsRbrackPayloadPayload]
@@ -10450,57 +10529,6 @@ public enum Operations {
}
}
}
public struct Conflict: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIds/{id}/DELETE/responses/409/content`.
@frozen public enum Body: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIds/{id}/DELETE/responses/409/content/application\/json`.
case json(Components.Schemas.ErrorResponse)
/// The associated value of the enum case if `self` is `.json`.
///
/// - Throws: An error if `self` is not `.json`.
/// - SeeAlso: `.json`.
public var json: Components.Schemas.ErrorResponse {
get throws {
switch self {
case let .json(body):
return body
}
}
}
}
/// Received HTTP response body
public var body: Operations.BundleIdsDeleteInstance.Output.Conflict.Body
/// Creates a new `Conflict`.
///
/// - Parameters:
/// - body: Received HTTP response body
public init(body: Operations.BundleIdsDeleteInstance.Output.Conflict.Body) {
self.body = body
}
}
/// Request entity error(s)
///
/// - Remark: Generated from `#/paths//v1/bundleIds/{id}/delete(bundleIds_deleteInstance)/responses/409`.
///
/// HTTP response code: `409 conflict`.
case conflict(Operations.BundleIdsDeleteInstance.Output.Conflict)
/// The associated value of the enum case if `self` is `.conflict`.
///
/// - Throws: An error if `self` is not `.conflict`.
/// - SeeAlso: `.conflict`.
public var conflict: Operations.BundleIdsDeleteInstance.Output.Conflict {
get throws {
switch self {
case let .conflict(response):
return response
default:
try throwUnexpectedResponseStatus(
expectedStatus: "conflict",
response: self
)
}
}
}
public struct TooManyRequests: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/bundleIds/{id}/DELETE/responses/429/content`.
@frozen public enum Body: Sendable, Hashable {
@@ -12686,57 +12714,6 @@ public enum Operations {
}
}
}
public struct Conflict: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/certificates/{id}/DELETE/responses/409/content`.
@frozen public enum Body: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/certificates/{id}/DELETE/responses/409/content/application\/json`.
case json(Components.Schemas.ErrorResponse)
/// The associated value of the enum case if `self` is `.json`.
///
/// - Throws: An error if `self` is not `.json`.
/// - SeeAlso: `.json`.
public var json: Components.Schemas.ErrorResponse {
get throws {
switch self {
case let .json(body):
return body
}
}
}
}
/// Received HTTP response body
public var body: Operations.CertificatesDeleteInstance.Output.Conflict.Body
/// Creates a new `Conflict`.
///
/// - Parameters:
/// - body: Received HTTP response body
public init(body: Operations.CertificatesDeleteInstance.Output.Conflict.Body) {
self.body = body
}
}
/// Request entity error(s)
///
/// - Remark: Generated from `#/paths//v1/certificates/{id}/delete(certificates_deleteInstance)/responses/409`.
///
/// HTTP response code: `409 conflict`.
case conflict(Operations.CertificatesDeleteInstance.Output.Conflict)
/// The associated value of the enum case if `self` is `.conflict`.
///
/// - Throws: An error if `self` is not `.conflict`.
/// - SeeAlso: `.conflict`.
public var conflict: Operations.CertificatesDeleteInstance.Output.Conflict {
get throws {
switch self {
case let .conflict(response):
return response
default:
try throwUnexpectedResponseStatus(
expectedStatus: "conflict",
response: self
)
}
}
}
public struct TooManyRequests: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/certificates/{id}/DELETE/responses/429/content`.
@frozen public enum Body: Sendable, Hashable {
@@ -16312,57 +16289,6 @@ public enum Operations {
}
}
}
public struct Conflict: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/profiles/{id}/DELETE/responses/409/content`.
@frozen public enum Body: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/profiles/{id}/DELETE/responses/409/content/application\/json`.
case json(Components.Schemas.ErrorResponse)
/// The associated value of the enum case if `self` is `.json`.
///
/// - Throws: An error if `self` is not `.json`.
/// - SeeAlso: `.json`.
public var json: Components.Schemas.ErrorResponse {
get throws {
switch self {
case let .json(body):
return body
}
}
}
}
/// Received HTTP response body
public var body: Operations.ProfilesDeleteInstance.Output.Conflict.Body
/// Creates a new `Conflict`.
///
/// - Parameters:
/// - body: Received HTTP response body
public init(body: Operations.ProfilesDeleteInstance.Output.Conflict.Body) {
self.body = body
}
}
/// Request entity error(s)
///
/// - Remark: Generated from `#/paths//v1/profiles/{id}/delete(profiles_deleteInstance)/responses/409`.
///
/// HTTP response code: `409 conflict`.
case conflict(Operations.ProfilesDeleteInstance.Output.Conflict)
/// The associated value of the enum case if `self` is `.conflict`.
///
/// - Throws: An error if `self` is not `.conflict`.
/// - SeeAlso: `.conflict`.
public var conflict: Operations.ProfilesDeleteInstance.Output.Conflict {
get throws {
switch self {
case let .conflict(response):
return response
default:
try throwUnexpectedResponseStatus(
expectedStatus: "conflict",
response: self
)
}
}
}
public struct TooManyRequests: Sendable, Hashable {
/// - Remark: Generated from `#/paths/v1/profiles/{id}/DELETE/responses/429/content`.
@frozen public enum Body: Sendable, Hashable {
@@ -16866,10 +16792,12 @@ public enum Operations {
case streamlinedPurchasingEnabled = "streamlinedPurchasingEnabled"
case accessibilityDeclarations = "accessibilityDeclarations"
case appEncryptionDeclarations = "appEncryptionDeclarations"
case appStoreIcon = "appStoreIcon"
case ciProduct = "ciProduct"
case betaTesters = "betaTesters"
case betaGroups = "betaGroups"
case appStoreVersions = "appStoreVersions"
case appTags = "appTags"
case preReleaseVersions = "preReleaseVersions"
case betaAppLocalizations = "betaAppLocalizations"
case builds = "builds"
@@ -16898,10 +16826,13 @@ public enum Operations {
case alternativeDistributionKey = "alternativeDistributionKey"
case analyticsReportRequests = "analyticsReportRequests"
case marketplaceSearchDetail = "marketplaceSearchDetail"
case buildUploads = "buildUploads"
case backgroundAssets = "backgroundAssets"
case betaFeedbackScreenshotSubmissions = "betaFeedbackScreenshotSubmissions"
case betaFeedbackCrashSubmissions = "betaFeedbackCrashSubmissions"
case searchKeywords = "searchKeywords"
case webhooks = "webhooks"
case androidToIosAppMappingDetails = "androidToIosAppMappingDetails"
}
/// - Remark: Generated from `#/paths/v1/bundleIds/{id}/app/GET/query/fields[apps]`.
public typealias Fields_lbrack_apps_rbrack_Payload = [Operations.BundleIdsAppGetToOneRelated.Input.Query.FieldsLbrackAppsRbrackPayloadPayload]
+1 -2
View File
@@ -65,7 +65,7 @@ function openAll(schema, path = []) {
function patch(schema) {
const schemas = schema.components.schemas;
// this field is required when using the private Xcode API
// this field is required iff using the private Xcode API
update(schemas.BundleIdCapabilityCreateRequest.properties.data.properties.relationships, {
properties: {
capability: {
@@ -86,7 +86,6 @@ function patch(schema) {
required: ['data'],
}
},
required: ['capability'],
})
// we don't use this but it triggers a deprecation warning. see:
+27 -21
View File
@@ -1,9 +1,11 @@
import Foundation
import Subprocess
import XUtils
public struct BuildSettings: Sendable {
private static let customBinDir =
// this is the same option used by SwiftPM itself for dev builds
ProcessInfo.processInfo.environment["SWIFTPM_CUSTOM_BIN_DIR"].map { URL(fileURLWithPath: $0) }
ProcessInfo.processInfo.environment["SWIFTPM_CUSTOM_BIN_DIR"].map { FilePath($0) }
private static let envURL = URL(fileURLWithPath: "/usr/bin/env")
@@ -34,18 +36,16 @@ public struct BuildSettings: Sendable {
#if os(macOS)
private static func xcrun(_ arguments: [String]) async throws -> String {
let xcrun = Process()
let pipe = Pipe()
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
xcrun.arguments = arguments
xcrun.standardOutput = pipe
try await xcrun.runUntilExit()
return String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
.trimmingCharacters(in: .whitespacesAndNewlines)
let result = try await Subprocess.run(
.path("/usr/bin/xcrun"),
arguments: .init(arguments),
output: .string(limit: .max)
).checkSuccess()
return result.standardOutput?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
}
private static let swiftURL = Task {
try await URL(fileURLWithPath: xcrun(["-f", "swift"]))
try await FilePath(xcrun(["-f", "swift"]))
}
#endif
@@ -53,12 +53,11 @@ public struct BuildSettings: Sendable {
forTool tool: String,
arguments: [String],
packagePathOverride: String? = nil
) async throws -> Process {
let process = Process()
) async throws -> Subprocess.Configuration {
let executable: Executable
let baseArguments: [String]
if let customBinDir = Self.customBinDir {
process.executableURL = customBinDir.appendingPathComponent("swift-\(tool)")
executable = .path(customBinDir.appending("swift-\(tool)"))
baseArguments = []
} else {
#if os(macOS)
@@ -67,9 +66,9 @@ public struct BuildSettings: Sendable {
// 1) invoking the real swift executable (located with `xcrun -f`) and
// 2) explicitly removing SDKROOT from the env, as it may be inherited
// through the `swift run pack` invocation.
process.executableURL = try await Self.swiftURL.value
executable = .path(try await Self.swiftURL.value)
#else
process.executableURL = try await ToolRegistry.locate("swift")
executable = .name("swift")
#endif
baseArguments = [tool]
}
@@ -79,11 +78,18 @@ public struct BuildSettings: Sendable {
"--configuration", configuration.rawValue,
]
var env = ProcessInfo.processInfo.environment
env.removeValue(forKey: "SDKROOT")
process.environment = env
process.arguments = baseArguments + extraArguments + sdkOptions + options + arguments
return process
var rawEnv = ProcessInfo.processInfo.environment
rawEnv.removeValue(forKey: "SDKROOT")
let env = Dictionary(uniqueKeysWithValues: rawEnv.map {
(Environment.Key(rawValue: $0)!, $1)
})
return Configuration(
executable,
arguments: .init(baseArguments + extraArguments + sdkOptions + options + arguments),
environment: .custom(env),
platformOptions: .withGracefulShutDown,
)
}
}
+123
View File
@@ -0,0 +1,123 @@
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)
}
}
-56
View File
@@ -1,56 +0,0 @@
import Foundation
package struct TemporaryDirectory: ~Copyable {
private var shouldDelete = true
package let url: URL
package init(name: String) throws {
self.url = FileManager.default.temporaryDirectory.appendingPathComponent(name, isDirectory: true)
_delete()
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
}
private func _delete() {
try? FileManager.default.removeItem(at: url)
}
package consuming func persist() -> URL {
shouldDelete = false
return url
}
package consuming func persist(at location: URL) throws {
try FileManager.default.moveItem(at: url, to: location)
// we do this after moving, so that if the move fails we clean up
shouldDelete = false
}
deinit {
if shouldDelete { _delete() }
}
}
extension Data {
// AsyncBytes is Darwin-only :/
package init(reading fileHandle: FileHandle) async throws {
#if canImport(Darwin)
self = try await fileHandle.bytes.reduce(into: Data()) { $0.append($1) }
#else
self = try fileHandle.readToEnd() ?? Data()
#endif
}
package init(reading file: URL) async throws {
#if canImport(Darwin)
self = try await file.resourceBytes.reduce(into: Data()) { $0.append($1) }
#else
try self.init(contentsOf: file)
#endif
}
}
package func stderrPrint(_ message: String, terminator: String = "\n") {
try? FileHandle.standardError.write(contentsOf: Data("\(message)\(terminator)".utf8))
}
+1
View File
@@ -1,5 +1,6 @@
import Foundation
import Yams
import XUtils
public struct PackSchemaBase: Codable, Sendable {
public enum Version: Int, Codable, Sendable {
+14 -4
View File
@@ -1,4 +1,6 @@
import Foundation
import XUtils
import Subprocess
public struct Packer: Sendable {
public let buildSettings: BuildSettings
@@ -53,7 +55,7 @@ public struct Packer: Sendable {
try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false))
}
let builder = try await buildSettings.swiftPMInvocation(
let buildConfig = try await buildSettings.swiftPMInvocation(
forTool: "build",
arguments: [
"--package-path", packageDir.path,
@@ -67,8 +69,12 @@ public struct Packer: Sendable {
"--disable-automatic-resolution",
]
)
builder.standardOutput = FileHandle.standardError
try await builder.runUntilExit()
try await Subprocess.run(
buildConfig,
output: .currentStandardError,
error: .currentStandardError,
)
.checkSuccess()
}
public func pack() async throws -> URL {
@@ -146,7 +152,11 @@ public struct Packer: Sendable {
let src = URL(fileURLWithPath: "\(name).framework/\(name)", relativeTo: binDir)
let magic = Data("!<arch>\n".utf8)
let thinMagic = Data("!<thin>\n".utf8)
let bytes = try FileHandle(forReadingFrom: src).read(upToCount: magic.count)
guard let bytes = try? FileHandle(forReadingFrom: src).read(upToCount: magic.count) else {
// if we can't find the binary, it might be a static framework that SwiftPM
// did not copy into the .build directory. we don't need to pack it anyway.
break
}
// if the magic matches one of these it's a static archive; don't embed it.
// https://github.com/apple/llvm-project/blob/e716ff14c46490d2da6b240806c04e2beef01f40/llvm/include/llvm/Object/Archive.h#L33
// swiftlint:disable:previous line_length
+11 -7
View File
@@ -1,4 +1,6 @@
import Foundation
import XUtils
import Subprocess
public struct Planner: Sendable {
public var buildSettings: BuildSettings
@@ -213,7 +215,7 @@ public struct Planner: Sendable {
}
private func dumpDependencies() async throws -> PackageDependency {
let tempDir = try TemporaryDirectory(name: "xtool-dump-\(UUID().uuidString)")
let tempDir = try TemporaryDirectory(name: "xtool-dump")
let tempFileURL = tempDir.url.appendingPathComponent("dump.json")
// SwiftPM sometimes prints extraneous data to stdout, so ask
@@ -242,16 +244,18 @@ public struct Planner: Sendable {
}
private func _dumpAction(arguments: [String], path: String) async throws -> Data {
let dump = try await buildSettings.swiftPMInvocation(
let dumpConfig = try await buildSettings.swiftPMInvocation(
forTool: "package",
arguments: arguments,
packagePathOverride: path
)
let pipe = Pipe()
dump.standardOutput = pipe
async let task = Data(reading: pipe.fileHandleForReading)
try await dump.runUntilExit()
return try await task
return try await Subprocess.run(
dumpConfig,
output: .data(limit: .max),
error: .currentStandardError,
)
.checkSuccess()
.standardOutput
}
private func selectLibrary(
-63
View File
@@ -1,63 +0,0 @@
import Foundation
extension Process {
/// Launches the process and suspends until the receiver is finished.
///
/// - Parameter onCancel: The action to take if the current
/// task is cancelled.
public func runUntilExit(onCancel: TaskCancelAction = .interrupt) async throws {
try Task.checkCancellation()
let (terminationStream, terminationContinuation) = AsyncStream<Never>.makeStream()
terminationHandler = { _ in
terminationContinuation.finish()
}
do {
try run()
} catch {
terminationContinuation.finish()
throw error
}
await withTaskCancellationHandler {
for await _ in terminationStream {}
} onCancel: {
switch onCancel {
case .interrupt:
interrupt()
case .terminate:
terminate()
case .ignore:
break
}
}
try Task.checkCancellation()
switch terminationReason {
case .exit where terminationStatus == 0:
break
case .exit:
throw Failure.exit(terminationStatus)
case .uncaughtSignal:
throw Failure.uncaughtSignal(terminationStatus)
@unknown default:
break
}
}
public enum Failure: Error {
case exit(CInt)
case uncaughtSignal(CInt)
}
public enum TaskCancelAction: Sendable {
/// Sends `SIGINT` to the process.
case interrupt
/// Sends `SIGTERM` to the process.
case terminate
/// Don't participate in cooperative cancellation.
case ignore
}
}
+5 -19
View File
@@ -1,4 +1,5 @@
import Foundation
import Subprocess
package enum ToolRegistry {
package enum Errors: Error, CustomStringConvertible {
@@ -16,11 +17,6 @@ package enum ToolRegistry {
/// Obtain the full path to a tool in the user's `PATH`.
///
/// This effectively invokes `/bin/sh -c "command -v '$tool'"`.
///
/// - Warning: Make sure you trust/sanitize the `tool` parameter. If it
/// contains a single quote, it can be used in a shell escape.
///
/// - Throws: `Errors.toolNotFound` if the tool could not be located.
package static func locate(_ tool: String) async throws -> URL {
try await cache.locate(tool: tool)
@@ -30,20 +26,10 @@ package enum ToolRegistry {
private var cache: [String: Task<URL, Error>] = [:]
private func _locate(tool: String) async throws -> URL {
let pipe = Pipe()
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/bin/sh")
proc.arguments = ["-c", "command -v '\(tool)'"]
proc.standardOutput = pipe
async let bytes = pipe.fileHandleForReading.readToEnd()
do {
try await proc.runUntilExit()
} catch is Process.Failure {
throw Errors.toolNotFound(tool)
}
let path = String(decoding: try await bytes ?? Data(), as: UTF8.self)
.trimmingCharacters(in: .whitespacesAndNewlines)
return URL(fileURLWithPath: path)
guard let path = try? await Executable.name(tool).resolveExecutablePath(in: .inherit),
let url = URL(filePath: path)
else { throw Errors.toolNotFound(tool) }
return url
}
func locate(tool: String) async throws -> URL {
+4 -4
View File
@@ -49,9 +49,9 @@ public struct XcodePacker {
let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
try infoPath.write(encodedPlist)
var buildSettings: [String: Any] = [
"PRODUCT_BUNDLE_IDENTIFIER": product.bundleID,
"TARGETED_DEVICE_FAMILY": families.map { "\($0)" }.joined(separator: ","),
var buildSettings: [String: BuildSetting] = [
"PRODUCT_BUNDLE_IDENTIFIER": .string(product.bundleID),
"TARGETED_DEVICE_FAMILY": .string(families.map { "\($0)" }.joined(separator: ",")),
]
if product.type == .appExtension {
@@ -59,7 +59,7 @@ public struct XcodePacker {
}
if let entitlementsPath = product.entitlementsPath {
buildSettings["CODE_SIGN_ENTITLEMENTS"] = fromProjectToRoot + Path(entitlementsPath)
buildSettings["CODE_SIGN_ENTITLEMENTS"] = .string((fromProjectToRoot + Path(entitlementsPath)).string)
}
let additionalDependencies: [Dependency] = if product.type == .application {
-4
View File
@@ -1,4 +0,0 @@
module XADI [extern_c] {
header "xadi.h"
link "xadi"
}
-13
View File
@@ -1,13 +0,0 @@
#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);
@@ -137,8 +137,8 @@ public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
id: appID.id
)
),
// not public but required when using ds2 API
capability: .init(
// not public but required iff using ds2 API
capability: context.auth.isPublicAPI ? nil : .init(
data: .init(
_type: .capabilities,
id: typ
@@ -23,6 +23,16 @@ public struct DeveloperServicesCapability: Sendable, Hashable {
self.isFree = isFree
self.settings = settings
}
public init(
rawName: String,
isFree: Bool,
settings: [Components.Schemas.CapabilitySetting]? = nil
) {
self.capabilityType = .init(value2: rawName)
self.isFree = isFree
self.settings = settings
}
}
protocol EntitlementWithCapability: Entitlement {
@@ -128,3 +138,9 @@ extension WirelessAccessoryEntitlement: EntitlementWithCapability {
DeveloperServicesCapability(.wirelessAccessoryConfiguration, isFree: true)
}
}
extension WiFiAwareEntitlement: EntitlementWithCapability {
var capability: DeveloperServicesCapability {
DeveloperServicesCapability(rawName: "WIFI_AWARE", isFree: false)
}
}
@@ -73,6 +73,13 @@ public enum DeveloperAPIAuthData: Sendable {
}
}
public var isPublicAPI: Bool {
switch self {
case .appStoreConnect: true
case .xcode: false
}
}
// A unique ID tied to this token
public var identityID: String {
switch self {
@@ -133,12 +140,10 @@ public struct DeveloperAPIXcodeAuthMiddleware: ClientMiddleware {
// Xcode-specific
request.headerFields[.userAgent] = "Xcode"
request.headerFields[.init(DeviceInfo.xcodeVersionKey)!] = "16.2 (16C5031c)"
request.headerFields[.init(DeviceInfo.xcodeVersionKey)!] = DeviceInfo.xcodeVersion
// MobileMe identity
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.clientInfoKey)!] = 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 os(Linux)
#if canImport(XADI)
return XADIProvider()
#else
return OmnisetteADIProvider()
@@ -174,7 +174,7 @@ public struct ADIDataProvider: AnisetteDataProvider {
.acceptLanguage: "en_US",
.init(AnisetteData.localUserIDKey)!: self.localUserID,
]
request.headerFields[.init("X-MMe-Country")!] = Locale.current.regionCode
request.headerFields[.init("X-MMe-Country")!] = Locale.current.region?.identifier
request.headerFields[.init(DeviceInfo.clientInfoKey)!] = try await clientInfo()
request.headerFields[.init(DeviceInfo.deviceIDKey)!] = self.localUserUID.uuidString
@@ -54,7 +54,8 @@ public struct AnisetteData {
var dictionary: [String: String] {
// GSA doesn't like "en_US@rg=..."; it has to be just "en_US".
let localeIdentifier = if let language = locale.languageCode, let region = locale.regionCode {
let localeIdentifier = if let language = locale.language.languageCode?.identifier,
let region = locale.region?.identifier {
"\(language)_\(region)"
} else {
"en_US"
@@ -56,13 +56,14 @@ extension DeviceInfo {
private static func fetchHardwareModel() -> String? {
var modelSize = 0
guard sysctlbyname("hw.model", nil, &modelSize, nil, 0) == 0 else { return nil }
guard let rawString = malloc(modelSize) else { return nil }
guard sysctlbyname("hw.model", rawString, &modelSize, nil, 0) == 0 else {
free(rawString)
return nil
guard sysctlbyname("hw.model", nil, &modelSize, nil, 0) == 0,
modelSize > 0 else { return nil }
return String(unsafeUninitializedCapacity: modelSize) { buf in
var len = modelSize
guard sysctlbyname("hw.model", buf.baseAddress, &len, nil, 0) == 0,
len == modelSize else { return 0 }
return len - 1 // exclude NUL
}
return String(bytesNoCopy: rawString, length: modelSize - 1, encoding: .utf8, freeWhenDone: true)
}
public static func current() -> DeviceInfo? {
@@ -91,7 +92,7 @@ extension DeviceInfo {
romAddress: "94f6a300e9a0",
mlbSerialNumber: "C02520301W0GF2D1U",
serialNumber: "C02PQKRJG8WP",
modelID: "MacBookPro11,5"
modelID: "Mac16,1"
)
}
}
@@ -14,29 +14,19 @@ public struct DeviceInfo: Codable, Sendable {
/// `X-Xcode-Version`
static let xcodeVersionKey = "X-Xcode-Version"
/// Not included in `dictionary`
public static let xcodeVersion = "14.2 (14C18)"
public static let xcodeVersion = "26.5 (17F42)"
public struct ClientInfo: Codable {
public static let macOSVersion = "10.14.6"
public static let macOSBuild = "18G103"
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)> <Mac OS X;\(Self.macOSVersion);\(Self.macOSBuild)> \
<com.apple.AuthKit/\(Self.authKitVersion) (com.apple.akd/\(Self.akdVersion))>
<\(modelID)> <macOS;27.0;26A5378j> <com.apple.AuthKit/1 (com.apple.akd/1.0)>
"""
}
var userAgent: String {
"akd/\(Self.akdVersion) CFNetwork/\(Self.cfNetworkVersion) Darwin/\(Self.darwinVersion)"
"AuthKit/1 (Macintosh; OS X 27.0) (com.apple.dt.Xcode/26.5)"
}
public init(modelID: String) {
@@ -8,6 +8,8 @@
#if false
// For reference: https://github.com/xtool-org/xtool/issues/196
import Foundation
/// Creates a socket connected to `ip` on `port`.
@@ -1,8 +1,9 @@
#if os(Linux)
#if canImport(XADI)
import Foundation
import XADI
import Dependencies
import Subprocess
public actor XADIProvider: RawADIProvider {
@MainActor private static var loadTask: Task<Void, Error>?
@@ -45,17 +46,17 @@ public actor XADIProvider: RawADIProvider {
let archDir = "lib/\(arch)"
// TODO: Use ZIPFoundation
let proc = Process()
proc.executableURL = URL(filePath: "/usr/bin/env")
proc.arguments = [
"unzip", "-q",
applemusic.path(),
"\(archDir)/libCoreADI.so",
"\(archDir)/libstoreservicescore.so",
"-d", tmp.path()
]
try proc.run()
proc.waitUntilExit()
try await Subprocess.run(
.name("unzip"),
arguments: [
"-q",
applemusic.path,
"\(archDir)/libCoreADI.so",
"\(archDir)/libstoreservicescore.so",
"-d", tmp.path
],
output: .discarded
).checkSuccess()
try FileManager.default.moveItem(
at: tmp.appending(path: archDir),
to: libDir
+5 -1
View File
@@ -41,7 +41,11 @@ struct GrandSlamClient: Sendable {
}
request.configure(request: &httpRequest, deviceInfo: deviceInfo, anisetteData: anisetteData)
let resp = try await httpClient.makeRequest(httpRequest, body: body)
// 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)
}
return try R.Decoder.decode(data: resp.body)
}
@@ -39,13 +39,14 @@ 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,
.init(AnisetteData.timeZoneKey)!: TimeZone.current.identifier,
.init("X-Apple-I-TimeZone-Offset")!: "\(TimeZone.current.secondsFromGMT())"
]
request.headerFields[.init("X-MMe-Country")!] = Locale.current.regionCode
request.headerFields[.init("X-MMe-Country")!] = Locale.current.region?.identifier
let (_, body) = try await httpClient.makeRequest(request)
@@ -18,23 +18,47 @@ import OpenAPIAsyncHTTPClient
import Dependencies
extension HTTPClientDependencyKey: DependencyKey {
public static let liveValue: HTTPClientProtocol = {
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 = {
// 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: tlsConfiguration,
tlsConfiguration: Self.tlsConfiguration,
proxy: Self.proxyConfiguration,
decompression: .enabled(limit: .none)
)
config.timeout.connect = .seconds(60)
return HTTPClient(configuration: config)
}()
}
self.client = HTTPClient(configuration: config)
}
extension HTTPClient: HTTPClientProtocol {
public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
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
@@ -42,7 +66,7 @@ extension HTTPClient: 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: eventLoopGroup) {
let future = WebSocket.connect(to: url, on: client.eventLoopGroup) {
continuation.yield(WebSocketSessionWrapper(webSocket: $0))
}
try await future.get()
@@ -56,8 +80,17 @@ extension HTTPClient: HTTPClientProtocol {
case connectFailed
}
public var asOpenAPITransport: any ClientTransport {
AsyncHTTPClientTransport(configuration: .init(client: self))
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()
}
}
@@ -18,6 +18,10 @@ 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 {
@@ -41,28 +45,72 @@ 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, body) = try await send(request, body: body.map { HTTPBody($0) })
guard let body else {
return (response, Data())
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)
)
}
switch body.length {
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 {
case .unknown:
return (response, try await body.reduce(into: Data()) { $0 += $1 })
return try await self.reduce(into: Data()) { $0 += $1 }
case .known(let length):
var data = Data(capacity: Int(length))
let total = Double(length)
for try await chunk in body {
for try await chunk in self {
data += chunk
await onProgress(min(Double(data.count) / total, 1))
await onProgress(Swift.min(Double(data.count) / total, 1))
}
return (response, data)
return 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 }
@@ -84,6 +132,12 @@ 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,6 +40,18 @@ 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()
@@ -56,6 +68,15 @@ 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()
@@ -2,6 +2,7 @@ import Foundation
import SwiftyMobileDevice
import ConcurrencyExtras
import Dependencies
import XUtils
extension LockdownClient {
static let installerLabel = "xtool"
@@ -44,19 +45,13 @@ public actor IntegratedInstaller {
case unlockDevice
}
let udid: String
let lookupMode: LookupMode
let auth: DeveloperAPIAuthData
let configureDevice: Bool
public weak var delegate: IntegratedInstallerDelegate?
@Dependency(\.zipCompressor) private var compressor
private var appInstaller: AppInstaller?
private let tempDir = FileManager.default.temporaryDirectoryShim
.appendingPathComponent("sh.xtool.Staging")
private var stage: String?
private nonisolated let updateTask = LockIsolated<Task<Void, Never>?>(nil)
@@ -104,16 +99,10 @@ public actor IntegratedInstaller {
}
public init(
udid: String,
lookupMode: LookupMode,
auth: DeveloperAPIAuthData,
configureDevice: Bool,
delegate: IntegratedInstallerDelegate
) {
self.udid = udid
self.lookupMode = lookupMode
self.auth = auth
self.configureDevice = configureDevice
self.delegate = delegate
}
@@ -146,7 +135,7 @@ public actor IntegratedInstaller {
}
}
private func fetchPairingKeys(with lockdownClient: LockdownClient) async throws -> Data {
private func fetchPairingKeys(with lockdownClient: LockdownClient, udid: String) async throws -> Data {
try lockdownClient.setValue(udid, forDomain: "com.apple.mobile.wireless_lockdown", key: "WirelessBuddyID")
try lockdownClient.setValue(true, forDomain: "com.apple.mobile.wireless_lockdown", key: "EnableWifiConnections")
@@ -203,15 +192,17 @@ public actor IntegratedInstaller {
}
@discardableResult
public func install(app: URL) async throws -> String {
public func install(
app: URL,
udid: String,
lookupMode: LookupMode,
configureDevice: Bool,
) async throws -> String {
try await self.updateStage(to: "Unpacking app", initialProgress: nil)
if FileManager.default.fileExists(atPath: tempDir.path) {
try? FileManager.default.removeItem(at: tempDir)
}
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: tempDir) }
let _tempDir = try TemporaryDirectory(name: "staging")
let tempDir = _tempDir.url
defer { withExtendedLifetime(_tempDir) {} }
switch app.pathExtension {
case "ipa":
@@ -235,7 +226,7 @@ public actor IntegratedInstaller {
try await self.updateProgress(to: 1)
let payload = self.tempDir.appendingPathComponent("Payload")
let payload = tempDir.appendingPathComponent("Payload")
guard let appDir = payload.implicitContents.first(where: { $0.pathExtension == "app" })
else { throw Error.appExtractionFailed }
@@ -259,7 +250,7 @@ public actor IntegratedInstaller {
let deviceName = try lockdownClient.deviceName()
let pairingKeys: Data? = if configureDevice {
try await fetchPairingKeys(with: lockdownClient)
try await fetchPairingKeys(with: lockdownClient, udid: udid)
} else {
nil
}
@@ -267,30 +258,9 @@ public actor IntegratedInstaller {
try await updateProgress(to: 1)
let context = try SigningContext(
auth: auth,
targetDevice: .init(udid: udid, name: deviceName)
)
let signer = AutoSigner(context: context) { certs in
await self.delegate?.confirmRevocation(of: certs) ?? false
}
let bundleID = try await signer.sign(
let bundleID = try await signInPlace(
app: appDir,
status: { @Sendable status in
self.queueUpdateTask {
$0.updateStageIgnoringCancellation(to: status)
}
},
progress: { progress in
self.queueUpdateTask {
$0.updateProgressIgnoringCancellation(to: progress)
}
},
didProvision: { @Sendable [self] in
// TODO: reintroduce Superconfig
_ = self
}
targetDevice: .init(udid: udid, name: deviceName),
)
try await self.updateStage(to: "Packaging", initialProgress: nil)
@@ -319,6 +289,39 @@ public actor IntegratedInstaller {
return bundleID
}
@discardableResult
public func signInPlace(
app: URL,
targetDevice: SigningContext.TargetDevice? = nil,
) async throws -> String {
let context = try SigningContext(
auth: auth,
targetDevice: targetDevice,
)
let signer = AutoSigner(context: context) { certs in
await self.delegate?.confirmRevocation(of: certs) ?? false
}
return try await signer.sign(
app: app,
status: { @Sendable status in
self.queueUpdateTask {
$0.updateStageIgnoringCancellation(to: status)
}
},
progress: { progress in
self.queueUpdateTask {
$0.updateProgressIgnoringCancellation(to: progress)
}
},
didProvision: { @Sendable [self] in
// TODO: reintroduce Superconfig
_ = self
}
)
}
}
#endif
@@ -26,6 +26,7 @@ extension EntitlementContainer {
SiriKitEntitlement.self,
InterAppAudioEntitlement.self,
WirelessAccessoryEntitlement.self,
WiFiAwareEntitlement.self,
HomeKitEntitlement.self,
HealthKitEntitlement.self,
]
@@ -33,7 +34,6 @@ extension EntitlementContainer {
public struct ApplicationIdentifierEntitlement: Entitlement, RawRepresentable {
public static let identifier = "application-identifier"
public static let isFree = true
public var rawValue: String
public init(rawValue: String) { self.rawValue = rawValue }
@@ -41,7 +41,6 @@ public struct ApplicationIdentifierEntitlement: Entitlement, RawRepresentable {
public struct TeamIdentifierEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.team-identifier"
public static let isFree = true
public var rawValue: String
public init(rawValue: String) { self.rawValue = rawValue }
@@ -49,7 +48,6 @@ public struct TeamIdentifierEntitlement: Entitlement, RawRepresentable {
public struct KeychainAccessGroupsEntitlement: Entitlement, RawRepresentable {
public static let identifier = "keychain-access-groups"
public static let isFree = true
public var rawValue: [String]
public init(rawValue: [String]) { self.rawValue = rawValue }
@@ -66,10 +64,6 @@ public struct KeychainAccessGroupsEntitlement: Entitlement, RawRepresentable {
public struct AppGroupEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.security.application-groups"
// FIXME: Enable app groups on free accounts
// but first we need to fix the bug where it only assigns one
// app group even if the ents say there are multiple
public static let isFree = false
public var rawValue: [DeveloperServicesAppGroup.GroupID]
public init(rawValue: [DeveloperServicesAppGroup.GroupID]) { self.rawValue = rawValue }
@@ -85,7 +79,6 @@ public struct AppGroupEntitlement: Entitlement, RawRepresentable {
public struct GetTaskAllowEntitlement: Entitlement, RawRepresentable {
public static let identifier = "get-task-allow"
public static let isFree = true
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -93,7 +86,6 @@ public struct GetTaskAllowEntitlement: Entitlement, RawRepresentable {
public struct AssociatedDomainsEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.associated-domains"
public static let isFree = false
public var rawValue: [String]
public init(rawValue: [String]) { self.rawValue = rawValue }
@@ -109,7 +101,6 @@ public struct AssociatedDomainsEntitlement: Entitlement, RawRepresentable {
public enum APSEnvironmentEntitlement: String, Entitlement {
public static let identifier = "aps-environment"
public static let isFree = false
case development
case production
@@ -117,7 +108,6 @@ public enum APSEnvironmentEntitlement: String, Entitlement {
public enum DataProtectionEntitlement: String, Entitlement {
public static let identifier = "com.apple.developer.default-data-protection"
public static let isFree = true
case complete = "NSFileProtectionComplete"
case unlessOpen = "NSFileProtectionCompleteUnlessOpen"
@@ -126,7 +116,6 @@ public enum DataProtectionEntitlement: String, Entitlement {
public struct NetworkExtensionEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.networking.networkextension"
public static let isFree = false
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -134,7 +123,6 @@ public struct NetworkExtensionEntitlement: Entitlement, RawRepresentable {
public struct MultipathEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.networking.multipath"
public static let isFree = false
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -142,7 +130,6 @@ public struct MultipathEntitlement: Entitlement, RawRepresentable {
public struct VPNConfigurationEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.networking.vpn.configuration"
public static let isFree = false
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -150,7 +137,6 @@ public struct VPNConfigurationEntitlement: Entitlement, RawRepresentable {
public struct SiriKitEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.siri"
public static let isFree = false
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -158,7 +144,6 @@ public struct SiriKitEntitlement: Entitlement, RawRepresentable {
public struct InterAppAudioEntitlement: Entitlement, RawRepresentable {
public static let identifier = "inter-app-audio"
public static let isFree = true
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -166,15 +151,28 @@ public struct InterAppAudioEntitlement: Entitlement, RawRepresentable {
public struct WirelessAccessoryEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.external-accessory.wireless-configuration"
public static let isFree = true
public var rawValue: Bool
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"
public static let isFree = true
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
@@ -182,7 +180,6 @@ public struct HomeKitEntitlement: Entitlement, RawRepresentable {
public struct HealthKitEntitlement: Entitlement, RawRepresentable {
public static let identifier = "com.apple.developer.healthkit"
public static let isFree = true
public var rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
+2 -4
View File
@@ -138,11 +138,9 @@ public struct KeychainStorage: KeyValueStorage {
private func makeQuery(forKey key: String, _ parameters: [CFString: Any]) -> CFDictionary {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: key
kSecAttrAccount: key,
kSecUseDataProtectionKeychain: true,
]
if #available(macOS 10.15, *) {
query[kSecUseDataProtectionKeychain] = true
}
query[kSecAttrService] = service
query.merge(parameters) { _, b in b }
return query as CFDictionary
+9 -2
View File
@@ -48,9 +48,16 @@ extension AuthToken {
private static let decoder = JSONDecoder()
static func saved() throws -> Self {
guard let data = try storage.data(forKey: "XTLAuthToken") else {
guard let token = try savedIfPresent() else {
throw Console.Error("Please log in with `xtool auth` before running this command.")
}
return token
}
static func savedIfPresent() throws -> Self? {
guard let data = try storage.data(forKey: "XTLAuthToken") else {
return nil
}
return try decoder.decode(AuthToken.self, from: data)
}
@@ -63,7 +70,7 @@ extension AuthToken {
try Self.storage.setData(data, forKey: "XTLAuthToken")
}
func authData() throws -> DeveloperAPIAuthData {
func authData() -> DeveloperAPIAuthData {
switch self {
case .appStoreConnect(let data):
return .appStoreConnect(.init(id: data.id, issuerID: data.issuerID, pem: data.pem))
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
import XKit
import SystemPackage
import XUtils
import NIOPosix
import NIOCore
@@ -22,7 +22,7 @@ struct DSTeamsListCommand: AsyncParsableCommand {
func run() async throws {
let token = try AuthToken.saved()
guard case let .xcode(authData) = try token.authData() else {
guard case let .xcode(authData) = token.authData() else {
throw Console.Error("This command requires password-based authentication")
}
let client = DeveloperServicesClient(authData: authData)
+54 -16
View File
@@ -3,6 +3,7 @@ import ArgumentParser
import PackLib
import XKit
import Dependencies
import XUtils
struct PackOperation {
struct BuildOptions: ParsableArguments {
@@ -26,6 +27,8 @@ struct PackOperation {
@discardableResult
func run() async throws -> URL {
try await EnsureSDKOperation(quiet: true).run()
print("Planning...")
let schema: PackSchema
@@ -79,7 +82,7 @@ struct PackOperation {
}
return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
}
print("Pseudo-signing...")
print("Applying entitlements...")
try await Signer.first().sign(
app: bundle,
identity: .adhoc,
@@ -116,6 +119,12 @@ struct DevBuildCommand: AsyncParsableCommand {
@OptionGroup var packOptions: PackOperation.BuildOptions
@Flag(
name: .shortAndLong,
help: "Codesign the built app",
) var sign = false
@Flag(
name: .shortAndLong,
help: "Output a .ipa file instead of a .app"
) var ipa = false
@@ -127,21 +136,44 @@ struct DevBuildCommand: AsyncParsableCommand {
) var triple: String?
func run() async throws {
let signingAuthToken: AuthToken?
if sign {
guard let token = try AuthToken.savedIfPresent() else {
throw Console.Error("`build --sign` requires logging in with `xtool auth`")
}
signingAuthToken = token
} else {
signingAuthToken = nil
}
let url = try await PackOperation(
triple: triple,
buildOptions: packOptions
).run()
if let signingAuthToken {
let installDelegate = XToolInstallerDelegate()
let installer = IntegratedInstaller(
auth: signingAuthToken.authData(),
delegate: installDelegate
)
do {
defer { print() }
try await installer.signInPlace(app: url)
} catch let error as CancellationError {
throw error
} catch {
print("Error: \(error)")
throw ExitCode.failure
}
}
let finalURL: URL
if ipa {
@Dependency(\.zipCompressor) var compressor
finalURL = url.deletingPathExtension().appendingPathExtension("ipa")
let tmpDir = try TemporaryDirectory(name: "sh.xtool.tmp")
let payloadDir = tmpDir.url.appendingPathComponent("Payload", isDirectory: true)
try FileManager.default.createDirectory(
at: payloadDir,
withIntermediateDirectories: true
)
let tmpDir = try TemporaryDirectory(name: "Payload")
let payloadDir = tmpDir.url
try FileManager.default.moveItem(at: url, to: payloadDir.appendingPathComponent(url.lastPathComponent))
let ipaURL = try await compressor.compress(directory: payloadDir) { progress in
if let progress {
@@ -214,17 +246,19 @@ struct DevRunCommand: AsyncParsableCommand {
let installDelegate = XToolInstallerDelegate()
let installer = IntegratedInstaller(
udid: client.udid,
lookupMode: .only(client.connectionType),
auth: try token.authData(),
configureDevice: false,
auth: token.authData(),
delegate: installDelegate
)
defer { print() }
do {
try await installer.install(app: output)
try await installer.install(
app: output,
udid: client.udid,
lookupMode: .only(client.connectionType),
configureDevice: false,
)
} catch let error as CancellationError {
throw error
} catch {
@@ -250,6 +284,8 @@ struct DevCommand: AsyncParsableCommand {
extension BuildConfiguration: ExpressibleByArgument {}
#if os(macOS)
import Subprocess
struct SimInstallOperation {
var path: URL
@@ -257,10 +293,12 @@ struct SimInstallOperation {
var simulator = "booted"
func run() async throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
process.arguments = ["simctl", "install", simulator, path.path]
try await process.runUntilExit()
try await Subprocess.run(
.path("/usr/bin/xcrun"),
arguments: ["simctl", "install", simulator, path.path],
output: .discarded
)
.checkSuccess()
print("Installed to simulator")
}
}
+7 -5
View File
@@ -24,15 +24,17 @@ struct InstallCommand: AsyncParsableCommand {
let installDelegate = XToolInstallerDelegate()
let installer = IntegratedInstaller(
udid: client.udid,
lookupMode: .only(client.connectionType),
auth: try token.authData(),
configureDevice: false,
auth: token.authData(),
delegate: installDelegate
)
do {
try await installer.install(app: URL(fileURLWithPath: path))
try await installer.install(
app: URL(fileURLWithPath: path),
udid: client.udid,
lookupMode: .only(client.connectionType),
configureDevice: false,
)
print("\nSuccessfully installed!")
} catch let error as CancellationError {
throw error
@@ -2,6 +2,8 @@ import Foundation
import XKit
import Dependencies
import PackLib
import Subprocess
import XUtils
extension ZIPCompressor: DependencyKey {
// TODO: Use `powershell Compress-Archive` and `powershell Expand-Archive` on Windows
@@ -12,20 +14,23 @@ extension ZIPCompressor: DependencyKey {
let dest = dir.deletingLastPathComponent().appendingPathComponent("app.ipa")
let zip = Process()
zip.executableURL = try await ToolRegistry.locate("zip")
zip.currentDirectoryURL = dir.deletingLastPathComponent()
zip.arguments = ["-yqru0", dest.path, dir.lastPathComponent]
try await zip.runUntilExit()
try await Subprocess.run(
.name("zip"),
arguments: ["-yqru0", dest.path, dir.lastPathComponent],
workingDirectory: FilePath(dir.deletingLastPathComponent()),
output: .discarded,
).checkSuccess()
return dest
},
decompress: { ipa, directory, progress in
progress(nil)
let unzip = Process()
unzip.executableURL = try await ToolRegistry.locate("unzip")
unzip.arguments = ["-q", ipa.path, "-d", directory.path]
try await unzip.runUntilExit()
try await Subprocess.run(
.name("unzip"),
arguments: ["-q", ipa.path, "-d", directory.path],
output: .discarded,
).checkSuccess()
}
)
}
+122 -53
View File
@@ -1,9 +1,9 @@
import Foundation
import Dependencies
import SystemPackage
import libunxip
import Subprocess
import XKit // HTTPClient, stdoutSafe
import PackLib // ToolRegistry
import XUtils // System.File{Path,Descriptor}
struct SDKBuilder {
enum Arch: String {
@@ -18,7 +18,10 @@ struct SDKBuilder {
init(path: String) throws {
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: path, isDirectory: &isDir) else {
throw Console.Error("Could not read file or directory at path '\(path)'")
throw Console.Error("""
Could not read file or directory at path '\(path)'.
See 'xtool help sdk' for usage.
""")
}
let url = URL(fileURLWithPath: path)
@@ -49,17 +52,42 @@ 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 outputPath: String
let output: URL
let arch: Arch
let mode: Mode
@discardableResult
func buildSDK() async throws -> String {
// TODO: store relevant info for staleness check
let sdkVersion = "develop"
// bump this when the sdk builder logic changes
static let sdkEpoch = 1
let output = URL(fileURLWithPath: outputPath, isDirectory: true)
.appendingPathComponent("darwin.artifactbundle")
// 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
try? FileManager.default.removeItem(at: output)
try FileManager.default.createDirectory(
@@ -139,6 +167,7 @@ struct SDKBuilder {
},
"swiftCompiler": {
"extraCLIOptions": [
"-Xfrontend", "-enable-cross-import-overlays",
"-use-ld=lld"
]
}
@@ -167,14 +196,9 @@ struct SDKBuilder {
try Data("\(sdkVersion)\n".utf8)
.write(to: output.appendingPathComponent("darwin-sdk-version.txt"))
return output.path
}
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(
@@ -182,18 +206,10 @@ struct SDKBuilder {
withIntermediateDirectories: false
)
let pipe = Pipe()
let untar = Process()
untar.currentDirectoryURL = toolsetDir
untar.executableURL = try await ToolRegistry.locate("tar")
untar.arguments = ["xzf", "-"]
untar.standardInput = pipe.fileHandleForReading
async let tarExit: Void = untar.runUntilExit()
@Dependency(\.httpClient) var httpClient
let url = URL(string: """
https://github.com/xtool-org/darwin-tools-linux-llvm/releases/download/\
v\(darwinToolsVersion)/toolset-\(arch.rawValue).tar.gz
v\(Self.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") }
@@ -201,45 +217,52 @@ struct SDKBuilder {
case .known(let known): known
case .unknown: nil
}
let writer = pipe.fileHandleForWriting
var written: Int64 = 0
do {
defer { try? writer.close() }
defer { print() }
try await Subprocess.run(
.name("tar"),
arguments: ["xzf", "-"],
workingDirectory: FilePath(toolsetDir),
input: .inputWriter,
output: .discarded,
error: .discarded,
) { execution in
var totalWritten: Int64 = 0
for try await chunk in body {
try writer.write(contentsOf: chunk)
written += Int64(chunk.count)
if let length {
let progress = Int(Double(written) / Double(length) * 100)
var remaining = chunk
while !remaining.isEmpty {
let written = try await execution.standardInputWriter.write(Array(remaining))
remaining = remaining.dropFirst(written)
totalWritten += Int64(written)
guard let length else { continue }
let progress = Int(Double(totalWritten) / Double(length) * 100)
print("\r[Downloading toolset] \(progress)%", terminator: "")
fflush(stdoutSafe)
}
}
try await execution.standardInputWriter.finish()
}
print()
try await tarExit
.checkSuccess()
}
// swiftlint:disable:next cyclomatic_complexity
// swiftlint:disable:next cyclomatic_complexity function_body_length
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 {
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
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)
try Task.checkCancellation()
let contents = try FileManager.default.contentsOfDirectory(
at: devStage,
at: stage,
includingPropertiesForKeys: nil
)
let apps = contents.filter { $0.pathExtension == "app" }
@@ -251,12 +274,39 @@ struct SDKBuilder {
default:
throw Console.Error("Unrecognized xip layout (multiple apps found)")
}
cleanupStageDir = devStage
case .app(let appPath):
wanted = nil
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):
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)
@@ -279,7 +329,7 @@ struct SDKBuilder {
}
if count % 100 == 0 {
if wanted == nil {
print("\r[Installing SDKs] Copied \(count) files", terminator: "")
print("\r[Installing SDKs] Installed \(count) files", terminator: "")
fflush(stdoutSafe)
}
await Task.yield()
@@ -292,7 +342,11 @@ 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)
}
}
@@ -304,9 +358,9 @@ struct SDKBuilder {
}
print()
print("[Cleaning up]")
if let cleanupStageDir {
try? FileManager.default.removeItem(at: cleanupStageDir)
print("[Cleaning up]")
try FileManager.default.removeItem(at: cleanupStageDir)
}
print("[Finalizing SDKs]")
@@ -349,12 +403,27 @@ 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")
)
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() }
+164 -106
View File
@@ -4,6 +4,8 @@ import Version
import ArgumentParser
import Dependencies
import PackLib
import XUtils
import Subprocess
struct SDKCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
@@ -11,6 +13,7 @@ struct SDKCommand: AsyncParsableCommand {
abstract: "Manage the Darwin Swift SDK",
subcommands: [
DevSDKInstallCommand.self,
DevSDKUpdateCommand.self,
DevSDKRemoveCommand.self,
DevSDKBuildCommand.self,
DevSDKStatusCommand.self,
@@ -46,9 +49,10 @@ struct DevSDKBuildCommand: AsyncParsableCommand {
func run() async throws {
let builderArch = try arch.sdkBuilderArch
let input = try SDKBuilder.Input(path: path)
let builder = SDKBuilder(input: input, outputPath: outputDir, arch: builderArch)
let sdkPath = try await builder.buildSDK()
print("Built SDK at \(sdkPath)")
let output = URL(fileURLWithPath: outputDir, isDirectory: true).appending(path: "darwin.xtoolsdk")
let builder = SDKBuilder(input: input, output: output, arch: builderArch, mode: .buildSlim)
try await builder.buildSDK()
print("Built SDK at \(output.path). You can install it with `xtool sdk install`.")
}
}
@@ -82,13 +86,29 @@ struct DevSDKInstallCommand: AsyncParsableCommand {
)
@Argument(
help: "Path to Xcode.xip or Xcode.app",
completion: .file(extensions: ["xip", "app"])
help: "Path to Xcode.xip, Xcode.app, or darwin.xtoolsdk",
completion: .file(extensions: ["xip", "app", "xtoolsdk"])
)
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).run()
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()
}
}
@@ -99,7 +119,7 @@ struct DevSDKRemoveCommand: AsyncParsableCommand {
)
func run() async throws {
guard let sdk = try await DarwinSDK.current() else {
guard let sdk = try DarwinSDK.current() else {
throw Console.Error("Cannot remove SDK: no Darwin SDK installed")
}
try sdk.remove()
@@ -114,109 +134,39 @@ struct DevSDKStatusCommand: AsyncParsableCommand {
)
func run() async throws {
if let sdk = try await DarwinSDK.current() {
print("Installed at \(sdk.bundle.path)")
if let sdk = try DarwinSDK.current() {
print("Darwin SDK is installed")
print(" Path: \(sdk.bundle.path)")
print(" Flavor: \(sdk.flavor)")
print(" Version: \(sdk.version)")
} else {
print("Not installed")
}
}
}
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 bundle.lastPathComponent == "darwin.artifactbundle" {
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)'")}
let process = Process()
process.executableURL = try await ToolRegistry.locate("swift")
process.arguments = ["sdk", "install", url.path]
try await process.runUntilExit()
}
static func current() async throws -> DarwinSDK? {
let output = Pipe()
let process = Process()
process.executableURL = try await ToolRegistry.locate("swift")
process.arguments = ["sdk", "configure", "darwin", "arm64-apple-ios", "--show-configuration"]
process.standardOutput = output
process.standardError = FileHandle.nullDevice
async let outputData = Data(reading: output.fileHandleForReading)
do {
try await process.runUntilExit()
} catch Process.Failure.exit {
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: "
let outputString = String(decoding: try await outputData, as: UTF8.self)
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)
}
extension DarwinSDK {
func isUpToDate() -> Bool {
true
}
func remove() throws {
try FileManager.default.removeItem(at: bundle)
version == SDKBuilder.currentSDKVersion
}
}
private enum SwiftVersion {}
extension SwiftVersion {
static func current() async throws -> Version {
let outPipe = Pipe()
let errPipe = Pipe()
let swift = Process()
swift.executableURL = try await ToolRegistry.locate("swift")
swift.arguments = ["--version"]
swift.standardOutput = outPipe
swift.standardError = errPipe
async let outputTask = outPipe.fileHandleForReading.readToEnd()
let outputString: String?
do {
try await swift.runUntilExit()
} catch is Process.Failure {
outputString = try await Subprocess.run(
.name("swift"),
arguments: ["--version"],
output: .string(limit: .max)
)
.checkSuccess()
.standardOutput
} catch {
throw Console.Error("Failed to obtain Swift version")
}
let outputData = try await outputTask
var output = String(decoding: outputData ?? Data(), as: UTF8.self)[...]
var output = outputString?[...] ?? ""
if output.hasPrefix("Apple ") {
output = output.dropFirst("Apple ".count)
}
@@ -235,29 +185,137 @@ 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
if let sdk = try await DarwinSDK.current() {
let temporaryBundle = try DarwinSDK.prepareTemporaryBundle()
if path.hasSuffix(".xtoolsdk") {
print("Installing prebuilt SDK...")
try await FileManager.default.copyItem(at: URL(filePath: path), to: temporaryBundle.url, preserveOwner: false)
} 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)
try await builder.buildSDK()
}
if let sdk = try DarwinSDK.current() {
print("Removing existing SDK...")
try sdk.remove()
}
let input = try SDKBuilder.Input(path: path)
let arch = try ArchSelection.auto.sdkBuilderArch
let tempDir = try TemporaryDirectory(name: "DarwinSDKBuild")
let builder = SDKBuilder(input: input, outputPath: tempDir.url.path, arch: arch)
let sdkPath = try await builder.buildSDK()
try await DarwinSDK.install(from: sdkPath)
// don't destroy tempDir before this point
withExtendedLifetime(tempDir) {}
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")
#endif
}
}
+2 -31
View File
@@ -1,6 +1,7 @@
import ArgumentParser
import Foundation
import XKit
import PackLib
struct SetupCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
@@ -23,36 +24,6 @@ struct SetupOperation {
func run() async throws {
try await AuthOperation(logoutFromExisting: false, 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
try await EnsureSDKOperation(quiet: quiet).run()
}
}
+6
View File
@@ -1,9 +1,11 @@
import Foundation
import XKit
import ArgumentParser
import XUtils
public enum XTool {
public static func run(arguments: [String]? = nil) async throws {
TemporaryDirectory.prepare()
await XToolCommand.cancellableMain(arguments)
}
}
@@ -64,6 +66,10 @@ extension ParsableCommand where Self: SendableMetatype {
print("Cancelled.")
self.exit()
} catch {
if ProcessInfo.processInfo.environment["XTL_DEBUG_ERRORS"] != nil {
print("ERROR DETAILS:")
print(String(reflecting: error))
}
self.exit(withError: error)
}
}
+59
View File
@@ -0,0 +1,59 @@
import Foundation
#if canImport(Subprocess)
import Subprocess
#endif
extension Data {
// AsyncBytes is Darwin-only :/
package init(reading fileHandle: FileHandle) async throws {
#if canImport(Darwin)
self = try await fileHandle.bytes.reduce(into: Data()) { $0.append($1) }
#else
self = try fileHandle.readToEnd() ?? Data()
#endif
}
package init(reading file: URL) async throws {
#if canImport(Darwin)
self = try await file.resourceBytes.reduce(into: Data()) { $0.append($1) }
#else
try self.init(contentsOf: file)
#endif
}
}
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))
}
+57
View File
@@ -0,0 +1,57 @@
#if canImport(Subprocess)
import Subprocess
import Foundation
extension ExecutionResult {
@discardableResult
public func checkSuccess() throws(SubprocessFailure) -> Self {
try terminationStatus.checkSuccess()
return self
}
}
extension TerminationStatus {
fileprivate func checkSuccess() throws(SubprocessFailure) {
if let failure { throw failure }
}
private var failure: SubprocessFailure? {
if isSuccess { return nil }
switch self {
case .exited(let code): return .exited(code)
case .signaled(let code): return .signaled(code)
}
}
}
public enum SubprocessFailure: Error {
case exited(TerminationStatus.Code)
case signaled(TerminationStatus.Code)
}
extension PlatformOptions {
public static var withGracefulShutDown: Self {
.init().withGracefulShutDown
}
public var withGracefulShutDown: Self {
var copy = self
copy.teardownSequence = [
.gracefulShutDown(
allowedDurationToNextStep: .milliseconds(500)
)
]
return copy
}
}
extension Environment {
public static func currentMap() -> [Environment.Key: String] {
Dictionary(
uniqueKeysWithValues: ProcessInfo.processInfo.environment.map {
(Environment.Key(rawValue: $0)!, $1)
}
)
}
}
#endif
+53
View File
@@ -0,0 +1,53 @@
import Foundation
#if canImport(System)
import System
public typealias FilePath = System.FilePath
public typealias FileDescriptor = System.FileDescriptor
public typealias Errno = System.Errno
#else
import SystemPackage
public typealias FilePath = SystemPackage.FilePath
public typealias FileDescriptor = SystemPackage.FileDescriptor
public typealias Errno = SystemPackage.Errno
extension URL {
public init?(filePath: FilePath) {
self.init(filePath: filePath.string)
}
}
extension FilePath {
public init?(_ url: URL) {
guard url.isFileURL else { return nil }
self.init(url.path)
}
}
#endif
extension FileDescriptor {
enum LockMode {
case shared
case exclusive
fileprivate var raw: CInt {
switch self {
case .shared: LOCK_SH
case .exclusive: LOCK_EX
}
}
}
func tryLock(mode: LockMode) throws -> Bool {
if flock(rawValue, mode.raw | LOCK_NB) == 0 {
return true
}
let err = errno
if err == EWOULDBLOCK {
return false
}
throw Errno(rawValue: err)
}
}
+184
View File
@@ -0,0 +1,184 @@
import Foundation
package struct TemporaryDirectory: ~Copyable {
private static let debugTmp = ProcessInfo.processInfo.environment["XTL_DEBUG_TMP"] != nil
private var shouldDelete: Bool
private let base: URL
package let url: URL
/// Prepares a fresh tmpdir root.
///
/// Optional, but try calling this at launch to clean up old resources.
package static func prepare() {
_ = TemporaryDirectoryRoot.shared
}
/// Creates a temporary directory where `lastPathComponent` is exactly `name`.
///
/// The directory is deleted on deinit or (if the object never deinits) on next launch.
/// To save the contents, move them elsewhere with ``persist(at:)``.
package init(name: String) throws {
do {
let basename = name
.replacingOccurrences(of: ".", with: "_")
.replacingOccurrences(of: "/", with: "_")
.prefix(32)
self.base = try TemporaryDirectoryRoot.shared.url
// ensures uniqueness
.appendingPathComponent("dir-\(basename)-\(UUID().uuidString)")
self.url = base.appendingPathComponent(name, isDirectory: true)
self.shouldDelete = true
} catch {
// non-copyable types can't be partially initialized so we need a stub value
self.base = URL(fileURLWithPath: "")
self.url = base
self.shouldDelete = false
throw error
}
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
if Self.debugTmp {
stderrPrint("Created TemporaryDirectory: \(url.path)")
}
}
private func _delete() {
guard !Self.debugTmp else { return }
try? FileManager.default.removeItem(at: base)
}
package consuming func persist(at location: URL) throws {
try FileManager.default.moveItem(at: url, to: location)
_delete()
// we do this after moving, so that if the move fails we clean up
shouldDelete = false
}
deinit {
if shouldDelete { _delete() }
}
}
private struct TemporaryDirectoryRoot {
static let shared = TemporaryDirectoryRoot()
private let _url: Result<URL, Errors>
var url: URL {
get throws(Errors) {
try _url.get()
}
}
private init() {
let url: URL
let env = ProcessInfo.processInfo.environment
if let tmpdir = env["XTL_TMPDIR"] ?? env["TMPDIR"] {
url = URL(fileURLWithPath: tmpdir).appendingPathComponent("sh.xtool")
} else {
#if os(Linux)
// On Linux, /tmp is commonly a tmpfs mount while ~/.swiftpm lives on ext4.
// Foundation's FileManager.copyItem uses sendfile(2) internally, which returns
// EINVAL when copying between different filesystem types (e.g. tmpfs → ext4).
// This causes `swift sdk install` to fail on distros like Linux Mint (#181).
// Using a cache dir on the home filesystem avoids the cross-fs copy entirely.
let xdgCache = env["XDG_CACHE_HOME"].map { URL(fileURLWithPath: $0) }
?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".cache")
url = xdgCache.appendingPathComponent("xtool")
#else
url = FileManager.default.temporaryDirectory.appendingPathComponent("sh.xtool")
#endif
}
Self.pruneOrphans(in: url)
self._url = Result {
let childDir = try Self.claimDirectory(in: url)
try FileManager.default.createDirectory(at: childDir, withIntermediateDirectories: true)
return childDir
}
.mapError { $0 as? Errors ?? .tmpdirCreationFailed(url, $0) }
}
private static func claimDirectory(in url: URL) throws -> URL {
// create a lockfile + tmpdir. while we hold the lock, other instaces of
// xtool will not delete the directory during their prune step.
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
let pid = ProcessInfo.processInfo.processIdentifier
for i in 0..<10 {
let random = "pid-\(pid)-\(i == 0 ? "0" : UUID().uuidString)"
let lockFile = url.appending(path: "\(random).lock")
#if os(macOS)
let fd = try FileDescriptor.open(
FilePath(lockFile.path),
.writeOnly,
options: [.create, .exclusiveLock],
permissions: [.ownerReadWrite, .groupRead, .otherRead],
)
#else
let fd = try FileDescriptor.open(
FilePath(lockFile.path),
.writeOnly,
options: [.create],
permissions: [.ownerReadWrite, .groupRead, .otherRead],
)
guard try fd.tryLock(mode: .exclusive) else {
// someone else raced us and claimed the right to prune between when we created the file and
// when we tried to lock it
continue
}
#endif
// leak the file descriptor so that the lock is held until the process exits
return url.appending(path: random)
}
throw Errors.tmpdirClaimFailed(url)
}
private static func pruneOrphans(in url: URL) {
guard let children = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
else { return }
for lock in children {
do {
let basename = lock.lastPathComponent
if basename.hasPrefix("tmp-") {
// legacy tmpdir, remove it
try? FileManager.default.removeItem(at: lock)
continue
}
guard basename.hasPrefix("pid-") && basename.hasSuffix(".lock") else { continue }
let lockFD = try FileDescriptor.open(FilePath(lock.path), .readWrite)
defer { try? lockFD.close() }
if try lockFD.tryLock(mode: .exclusive) {
// we must remove the directory first. if we instead removed the lock first,
// we could be killed after the lock was removed but before the dir was
// removed and therefore leave it hanging around.
do {
try FileManager.default.removeItem(at: lock.deletingPathExtension())
} catch CocoaError.fileNoSuchFile {
// pass
}
try FileManager.default.removeItem(at: lock)
}
} catch {
// continue
}
}
}
enum Errors: Error, CustomStringConvertible {
case tmpdirCreationFailed(URL, Error)
case tmpdirClaimFailed(URL)
var description: String {
switch self {
case let .tmpdirCreationFailed(url, error):
"Could not create temporary directory in '\(url.path)': \(error)"
case let .tmpdirClaimFailed(url):
"Could not claim temporary directory in '\(url.path)'"
}
}
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import Dependencies
enum XToolMain {
static func main() async throws {
prepareDependencies { _ in
#warning("Improve persistence mechanism")
// TODO: 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,71 +0,0 @@
//
// XKitDeveloperServicesTests.swift
// XKitTests
//
// Created by Kabir Oberai on 30/10/19.
// Copyright © 2019 Kabir Oberai. All rights reserved.
//
import XCTest
import SuperutilsTestSupport
import XKit
// swiftlint:disable force_try
class XKitDeveloperServicesTests: XCTestCase {
var storage: KeyValueStorage!
var client: DeveloperServicesClient!
override func setUp() {
super.setUp()
_ = addMockSigner
storage = MemoryKeyValueStorage()
client = try! .test(storage: storage)
}
override func tearDown() {
super.tearDown()
client = nil
}
// integration test for provisioning
@MainActor func testProvisioningIntegration() async throws {
let listTeams = DeveloperServicesListTeamsRequest()
let teams = try await client.send(listTeams)
let team = teams.first { $0.status == "active" && $0.memberships.contains { $0.platform == .iOS } }!
let source = try XCTUnwrap(Bundle.module.url(forResource: "test", withExtension: "app"))
let context = try XCTTry(SigningContext(
udid: Config.current.udid,
deviceName: SigningContext.hostName,
teamID: team.id,
client: client,
signingInfoManager: MemoryBackedSigningInfoManager()
))
let response = try await DeveloperServicesProvisioningOperation(
context: context,
app: source,
confirmRevocation: { _ in true },
progress: { _ in }
).perform()
print(response)
}
func testListTeams() async throws {
let listTeams = DeveloperServicesListTeamsRequest()
let teams = try await client.send(listTeams)
XCTAssertFalse(teams.isEmpty, "No teams found")
let team = try XCTUnwrap(
teams.first { $0.id.rawValue == Config.current.preferredTeam },
"Could not find preferred team"
)
XCTAssertEqual(team.status, "active", "Expected team status active. Got: \(team.status)")
XCTAssert(team.memberships.contains { $0.platform == .iOS }, "Team does not have iOS membership")
}
}
@@ -1,67 +0,0 @@
//
// XKitGrandSlamTests.swift
// XKitTests
//
// Created by Kabir Oberai on 10/04/20.
// Copyright © 2020 Kabir Oberai. All rights reserved.
//
// swiftlint:disable force_try
import XCTest
import SuperutilsTestSupport
@testable import XKit
final class TwoFactorAuthenticator: TwoFactorAuthDelegate {
func fetchCode() async -> String? {
print("Code: ", terminator: "")
return readLine() ?? ""
}
}
class XKitGrandSlamTests: XCTestCase {
var authenticator: TwoFactorAuthenticator!
var storage: KeyValueStorage!
var client: GrandSlamClient!
override func setUp() {
super.setUp()
_ = addMockSigner
storage = MemoryKeyValueStorage()
client = try! .test(storage: storage)
authenticator = TwoFactorAuthenticator()
}
override func tearDown() {
super.tearDown()
client = nil
authenticator = nil
}
func testAuthentication() async throws {
let loginData = try await GrandSlamAuthenticateOperation(
client: client,
username: Config.current.appleID.username,
password: Config.current.appleID.password,
twoFactorDelegate: authenticator
).authenticate()
XCTAssertFalse(loginData.adsid.isEmpty)
XCTAssertFalse(loginData.cookie.isEmpty)
XCTAssertFalse(loginData.identityToken.isEmpty)
XCTAssertFalse(loginData.idmsToken.isEmpty)
XCTAssertFalse(loginData.sk.isEmpty)
let now = Date() // *before* the actual request is made
let tokens = try await GrandSlamFetchAppTokensOperation(
client: client,
apps: [.xcode],
loginData: loginData
).perform()
let token = try XCTUnwrap(tokens[.xcode], "Xcode token absent from response")
XCTAssertGreaterThanOrEqual(token.expiry, now)
XCTAssertFalse(token.value.isEmpty)
}
}
@@ -1,90 +0,0 @@
//
// XKitSigningTests.swift
// XKitTests
//
// Created by Kabir Oberai on 06/11/19.
// Copyright © 2019 Kabir Oberai. All rights reserved.
//
// TODO: Test using mock signer
#if false
import XCTest
import SuperutilsTestSupport
import XKit
class XKitSigningTests: XCTestCase {
var client: DeveloperServicesClient!
var signerImpl: SignerImpl!
var app: URL!
// swiftlint:disable force_try
override func setUp() {
super.setUp()
_ = addMockSigner
client = .test()
signerImpl = try! SignerImpl.first()
let source = try! XCTUnwrap(Bundle.module.url(forResource: "test", withExtension: "app"))
let tmp = FileManager.default.temporaryDirectory
app = tmp.appendingPathComponent(source.lastPathComponent)
if FileManager.default.fileExists(atPath: app.path) {
try! FileManager.default.removeItem(at: app)
}
try! FileManager.default.copyItem(at: source, to: app)
}
override func tearDown() {
super.tearDown()
client = nil
signerImpl = nil
try! FileManager.default.removeItem(at: app)
app = nil
}
// swiftlint:enable force_try
// integration test for signing
@MainActor func testSigningIntegration() throws {
let listTeams = DeveloperServicesListTeamsRequest()
let teams = try XCTTry(client.sendTest(listTeams))
let team = teams.first { $0.status == "active" && $0.memberships.contains { $0.platform == .iOS } }!
let context = try XCTTry(SigningContext(
udid: Config.current.udid,
deviceName: SigningContext.hostName,
teamID: team.id,
client: client,
signingInfoManager: MemoryBackedSigningInfoManager(),
signerImpl: signerImpl
))
let signer = Signer(context: context)
let signingWaiter = ResultWaiter<()>(description: "Failed to sign app")
signer.sign(app: app, status: { _ in }, progress: { _ in }, completion: signingWaiter.completion)
try XCTTry(signingWaiter.wait(timeout: 10000))
// TODO: Ensure entitlements are correct in new app, also codesign -vvvv
}
func testAnalyze() throws {
let infoURL = app.appendingPathComponent("Info.plist")
let info = try XCTUnwrap(NSDictionary(contentsOf: infoURL))
let execName = try XCTUnwrap(info[kCFBundleExecutableKey as String] as? String)
let exec = app.appendingPathComponent(execName)
let ents = try XCTUnwrap(signerImpl.analyze(executable: exec))
let entsPlist = try XCTTry(PropertyListDecoder().decode(Entitlements.self, from: ents))
XCTAssertFalse(try XCTTry(entsPlist.entitlements().isEmpty))
}
func testSign() throws {
let signingWaiter = ResultWaiter<()>(description: "Failed to sign app")
// TODO: Get cert, key, ents from fixtures
}
}
#endif
-32
View File
@@ -1,32 +0,0 @@
//
// Config.swift
// XKitTests
//
// Created by Kabir Oberai on 05/11/19.
// Copyright © 2019 Kabir Oberai. All rights reserved.
//
import Foundation
import XKit
struct Config: Decodable {
struct AppleID: Decodable {
let username: String
let password: String
/// for non-login tests, just provide a token already
let token: DeveloperServicesLoginToken
}
let appleID: AppleID
let deviceInfo: DeviceInfo
let preferredTeam: String
let udid: String
static let current: Config = {
let url = Bundle.module.url(forResource: "config", withExtension: "json")!
// swiftlint:disable:next force_try
let data = try! Data(contentsOf: url)
// swiftlint:disable:next force_try
return try! JSONDecoder().decode(Config.self, from: data)
}()
}
@@ -1,62 +0,0 @@
//
// DeveloperServicesTestClient.swift
// XKitTests
//
// Created by Kabir Oberai on 06/11/19.
// Copyright © 2019 Kabir Oberai. All rights reserved.
//
import Foundation
import XCTest
@testable import XKit
#if false
extension TCPAnisetteDataProvider {
static func test() -> TCPAnisetteDataProvider {
TCPAnisetteDataProvider(localPort: 4321)
}
}
extension NetcatAnisetteDataProvider {
static func test() -> NetcatAnisetteDataProvider {
NetcatAnisetteDataProvider(localPort: 4322, deviceInfo: Config.current.deviceInfo)
}
}
#endif
extension ADIDataProvider {
static func test(storage: KeyValueStorage) throws -> ADIDataProvider {
try adiProvider(deviceInfo: Config.current.deviceInfo, storage: storage)
}
}
extension GrandSlamClient {
static func test(storage: KeyValueStorage) throws -> GrandSlamClient {
try GrandSlamClient(
deviceInfo: Config.current.deviceInfo,
anisetteProvider: ADIDataProvider.test(storage: storage)
)
}
}
extension DeveloperServicesClient {
static func test(storage: KeyValueStorage) throws -> DeveloperServicesClient {
try DeveloperServicesClient(
loginToken: Config.current.appleID.token,
deviceInfo: Config.current.deviceInfo,
anisetteProvider: ADIDataProvider.test(storage: storage)
)
}
}
@@ -1,16 +0,0 @@
import Foundation
import SignerSupport
let addMockSigner: () = {
add_signer(
"MockSigner",
{ _, _, _, _, _, _, _, _, _, exception in
exception.initialize(to: strdup("Mock signer not implemented"))
return 1
},
{ _, _, exception in
exception.initialize(to: strdup("Mock analyzer not implemented"))
return nil
}
)
}()
@@ -1,32 +0,0 @@
{
"appleID": {
"username": "",
"password": "",
"token": {
"adsid": "",
"token": "",
"expiry": 0
}
},
"deviceInfo": {
"clientInfo": {
"macOSBuild": "",
"darwinVersion": "",
"macOSVersion": "",
"akdVersion": "",
"cfNetworkVersion": "",
"authKitVersion": "",
"modelID": "",
},
"xcodeInfo": {
"version": "",
"build": ""
},
"deviceID": "",
"mlbSerialNumber": "",
"romAddress": "",
"serialNumber": ""
},
"preferredTeam": "",
"udid": "",
}
+55
View File
@@ -0,0 +1,55 @@
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))
}
+64
View File
@@ -0,0 +1,64 @@
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()
}
}
@@ -0,0 +1,39 @@
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"])
}
+11
View File
@@ -0,0 +1,11 @@
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)"
)
}
+7 -2
View File
@@ -2,8 +2,10 @@ services:
xtool:
build:
context: .
target: dev
volumes:
- .:/xtool
- .build/linux:/xtool/.build
container_name: xtool
stdin_open: true
tty: true
@@ -13,6 +15,9 @@ 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
+49
View File
@@ -0,0 +1,49 @@
#!/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"
+21
View File
@@ -0,0 +1,21 @@
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"
}
+5 -1
View File
@@ -1,4 +1,8 @@
/XToolMac.xcodeproj
/XToolMac.xcodeproj/*
!/XToolMac.xcodeproj/project.xcworkspace
/XToolMac.xcodeproj/project.xcworkspace/*
!/XToolMac.xcodeproj/project.xcworkspace/xcshareddata
Private*.xcconfig
/fastlane/README.md
-5
View File
@@ -2,8 +2,3 @@ source 'https://rubygems.org'
gem 'fastlane'
gem 'fastlane-plugin-xcodegen'
# https://github.com/fastlane/fastlane/issues/29183#issuecomment-2567093826
gem "abbrev"
gem "mutex_m"
gem "ostruct"
+68 -62
View File
@@ -1,40 +1,41 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.7)
base64
nkf
rexml
CFPropertyList (3.0.8)
abbrev (0.1.2)
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
addressable (2.9.0)
public_suffix (>= 2.0.2, < 8.0)
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1118.0)
aws-sdk-core (3.226.0)
aws-partitions (1.1249.0)
aws-sdk-core (3.247.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
base64
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.105.0)
aws-sdk-core (~> 3, >= 3.225.0)
aws-sdk-kms (1.125.0)
aws-sdk-core (~> 3, >= 3.247.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.190.0)
aws-sdk-core (~> 3, >= 3.225.0)
aws-sdk-s3 (1.222.0)
aws-sdk-core (~> 3, >= 3.247.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.3.0)
benchmark (0.5.0)
bigdecimal (4.1.2)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
csv (3.3.5)
declarative (0.0.20)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
@@ -42,7 +43,7 @@ GEM
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.4)
faraday (1.10.5)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
@@ -54,32 +55,36 @@ GEM
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.7)
faraday-cookie_jar (0.0.8)
faraday (>= 0.8.0)
http-cookie (~> 1.0.0)
http-cookie (>= 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.1)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-multipart (1.1.1)
faraday-multipart (1.2.0)
multipart-post (~> 2.0)
faraday-net_http (1.0.2)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday-retry (1.0.4)
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.4.0)
fastlane (2.228.0)
CFPropertyList (>= 2.3, < 4.0.0)
fastimage (2.4.1)
fastlane (2.234.0)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
base64 (~> 0.2)
benchmark (>= 0.1.0)
bundler (>= 1.17.3, < 5.0.0)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
@@ -87,20 +92,24 @@ GEM
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.0.0)
fastlane-sirp (>= 1.1.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.0.0)
google-cloud-env (>= 1.6.0, <= 2.1.1)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
logger (>= 1.6, < 2.0)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3)
naturally (~> 2.2)
nkf (~> 0.2)
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
@@ -116,41 +125,42 @@ GEM
fastlane-plugin-brew (0.1.1)
fastlane-plugin-xcodegen (1.1.0)
fastlane-plugin-brew (~> 0.1.1)
fastlane-sirp (1.0.0)
sysrandom (~> 1.0)
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
google-apis-androidpublisher_v3 (0.100.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
mini_mime (~> 1.0)
mutex_m
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.31.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-iamcredentials_v1 (0.27.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.17.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.62.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.8.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.5.0)
google-cloud-storage (1.47.0)
google-cloud-env (2.1.1)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.6.0)
google-cloud-storage (1.60.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.31.0)
google-apis-core (>= 0.18, < 2)
google-apis-iamcredentials_v1 (~> 0.18)
google-apis-storage_v1 (>= 0.42)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
googleauth (~> 1.9)
mini_mime (~> 1.0)
googleauth (1.8.1)
faraday (>= 0.17.3, < 3.a)
googleauth (1.11.2)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.1)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
@@ -161,43 +171,42 @@ GEM
httpclient (2.9.0)
mutex_m
jmespath (1.6.2)
json (2.12.2)
jwt (2.10.1)
json (2.19.5)
jwt (2.10.2)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.15.0)
multi_json (1.21.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.3.0)
nkf (0.2.0)
optparse (0.6.0)
optparse (0.8.1)
os (1.1.4)
ostruct (0.6.2)
ostruct (0.6.3)
plist (3.7.2)
public_suffix (6.0.2)
rake (13.3.0)
public_suffix (7.0.5)
rake (13.4.2)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.4.1)
retriable (3.4.1)
rexml (3.4.4)
rouge (3.28.0)
ruby2_keywords (0.0.5)
rubyzip (2.4.1)
security (0.1.5)
signet (0.20.0)
signet (0.21.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 3.0)
jwt (>= 1.5, < 4.0)
multi_json (~> 1.10)
simctl (1.6.10)
CFPropertyList
naturally
sysrandom (1.0.5)
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
@@ -226,11 +235,8 @@ PLATFORMS
ruby
DEPENDENCIES
abbrev
fastlane
fastlane-plugin-xcodegen
mutex_m
ostruct
BUNDLED WITH
2.6.7
@@ -0,0 +1 @@
../../../../Package.resolved
+1 -11
View File
@@ -5,7 +5,7 @@ struct XToolMacUI: App {
WindowGroup {
ContentView()
}
.disableWindowResizingIfPossible()
.windowResizability(.contentSize)
}
}
@@ -64,16 +64,6 @@ private struct StepView<Content: View>: View {
}
}
extension Scene {
fileprivate func disableWindowResizingIfPossible() -> some Scene {
if #available(macOS 13, *) {
return self.windowResizability(.contentSize)
} else {
return self
}
}
}
#Preview {
ContentView()
}
-2
View File
@@ -1,5 +1,3 @@
require_relative "spaceship_patch"
default_platform(:mac)
ENV["FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT"] = "120"
-16
View File
@@ -1,16 +0,0 @@
require "spaceship"
# the ASC API has started (June 2025) throwing a fit when it
# sees DEVELOPER_ID_APPLICATION_G2 in the certificate types filter.
# so we patch Spaceship to filter locally instead of via the API.
# c.f. https://github.com/fastlane/fastlane/pull/29588
class << Spaceship::ConnectAPI::Certificate
alias_method :all_orig, :all
def all(**args)
types = args[:filter]&.delete(:certificateType)&.split(",")
certs = all_orig(**args)
types ? certs.select { |cert| types.include?(cert.certificate_type) } : certs
end
end
+1 -1
View File
@@ -11,7 +11,7 @@ targets:
XToolMac:
type: application
platform: macOS
deploymentTarget: "12.0"
deploymentTarget: "13.0"
sources:
- path: XToolMac
- path: Resources/xtool
+1 -1
View File
@@ -5,7 +5,7 @@
base = "Documentation/"
publish = "xtool.docc/.docc-build"
command = "./build.sh"
environment = { SWIFT_VERSION = "6.1" }
environment = { SWIFT_VERSION = "6.3" }
ignore = "git -C .. diff --quiet $CACHED_COMMIT_REF $COMMIT_REF -- Documentation netlify.toml"
[[redirects]]