Compare commits

..

9 Commits

  • wip: hot reloading
    Discriminate with module name
    
    Fully working
    
    Changes
    
    Fix linux
    
    changes
    
    allow customizing xload path
    
    Lint
    
    Command
  • build: use SwiftBuild for xtool workspace LSP (#282)
    ## What does this PR do?
    
    Configure SourceKit-LSP to use SwiftBuild when working on xtool itself.
    The legacy build system has trouble with xcframeworks.
    
    ## How was it tested?
    
    Confirmed that it fixes highlighting of error diagnostics
    
    ## 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. -->
  • package: bump deps (#281)
    ## What does this PR do?
    
    Bumps pointfree deps and explicitly disables OpenCombine so that we
    don't have different dependency graphs when building xtool on Darwin vs
    Linux hosts.
    
    ## How was it tested?
    
    A bunch of `swift package resolve`s
    
    ## 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. -->
    
    
    <!-- This is an auto-generated comment: release notes by coderabbit.ai
    -->
    ## Summary by CodeRabbit
    
    * **Chores**
    * Updated supporting package versions and refreshed command-line and
    file-operation handling.
    * These changes do not add or remove app features or alter its public
    interface. No action is needed to continue using the app.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • sdk: prune Xcode when installing from xip (#280)
    ## What does this PR do?
    
    We only need `Xcode.app/Contents/{Info.plist,version.plist,Developer}`
    for the SDK (and expect that to continue being the case). We already
    delete other directories when using `xtool sdk install Xcode.app` but we
    weren't doing this on `xtool sdk install Xcode.xip`. Prune on the xip
    path as well.
    
    Also prune on update (and bump the SDK epoch) so that existing users
    benefit from this.
    
    ## How was it tested?
    
    - [x] Install SDK from xip, confirm `Xcode.app/Contents` only contains
    those three things
    - [x] Install SDK from app, confirm `Xcode.app/Contents` only contains
    those three things + we don't modify the original app
    - [x] Build SDK from app (`xtool sdk build Xcode.app`), confirm we don't
    clobber the input Xcode app
    - [x] Update SDK, confirm that extra contents are removed
    - [x] SDK auto-updates after updating xtool binary
    
    ## 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. -->
    
    
    <!-- This is an auto-generated comment: release notes by coderabbit.ai
    -->
    
    ## Summary by CodeRabbit
    
    * **Bug Fixes**
    * SDK builds from Xcode app and XIP inputs now check for required Xcode
    components before installation. Missing components produce an error.
    * Extra direct items in Xcode’s `Contents` folder are removed during XIP
    builds and app updates. Slim builds remain unchanged.
    
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • package: bump Darwin deployment targets to Fall2023 (#277)
    ## What does this PR do?
    
    Bumps Darwin deployment targets.
    
    In order to better integrate with SwiftBuild we need to pull in
    swift-tools-protocols which
    [requires](https://github.com/swiftlang/swift-tools-protocols/blob/4345e69c5572ec3d1f737fba90bca024b32da5cf/Package.swift#L210)
    macOS 14 / iOS 17.
    
    ## How was it tested?
    
    - [x] CI
    - [x] Did a local smoke test to ensure `xtool` still runs
    
    ## 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. -->
    
    
    <!-- This is an auto-generated comment: release notes by coderabbit.ai
    -->
    
    ## Summary by CodeRabbit
    
    * **Chores**
      * Updated minimum supported versions to iOS 17 and macOS 14.
      * macOS project configuration now requires macOS 14 or later.
    
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • fastlane: update Ruby and gems (#278)
    ## What does this PR do?
    
    Updates Ruby and gems
    
    ## How was it tested?
    
    - [x] `bundle exec fastlane package`
    
    ## 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. -->
    
    
    <!-- This is an auto-generated comment: release notes by coderabbit.ai
    -->
    
    ## Summary by CodeRabbit
    
    - **Chores**
    - Updated the macOS environment to use Ruby 4.0.7, keeping local
    development and maintenance workflows aligned with the supported runtime
    version.
    
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • zsign: update to v1.9.0 (#271)
    ## What does this PR do?
    
    Updates to zsign 1.9.0 which incorporates the latest upstream changes
    
    ## How was it tested?
    
    Built and ran an app on my phone
    
    ## 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. -->
  • docker: add SWIFT_VERSION arg (#276)
    ## What does this PR do?
    
    Adds a `SWIFT_VERSION` arg to the Dockerfile
    
    ## How was it tested?
    
    Ran on macOS
    
    ## 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. -->
    
    
    <!-- This is an auto-generated comment: release notes by coderabbit.ai
    -->
    
    ## Summary by CodeRabbit
    
    * **Chores**
    * Updated the build and runtime environments to use Swift 6.3.3
    consistently.
    
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • docs: update remaining reference of Xcode 26 -> 27 (#275)
    ## What does this PR do?
    
    Forgot to update one spot that still says Xcode 26
    
    ## How was it tested?
    
    N/A
    
    ## 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. -->
25 changed files with 2128 additions and 238 deletions
+7
View File
@@ -0,0 +1,7 @@
{
"swiftPM": {
"buildSystem": "swiftbuild",
"scratchPath": ".build/index-build"
},
"backgroundIndexing": true
}
+4 -2
View File
@@ -1,7 +1,9 @@
# Note: We use 22.04 since AppImage recommends building on the
# oldest configuration that you support
FROM swift:6.3-jammy AS build-base
ARG SWIFT_VERSION=6.3.3
FROM swift:${SWIFT_VERSION}-jammy AS build-base
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
@@ -102,7 +104,7 @@ RUN swift package resolve
ADD . /xtool
RUN ./Linux/build.sh
FROM swift:6.3 AS xtool
FROM swift:${SWIFT_VERSION} AS xtool
COPY --from=build-xtool /xtool/Linux/packages/xtool-*.AppImage /xtool/xtool.AppImage
RUN (cd /xtool && ./xtool.AppImage --appimage-extract) \
+86 -77
View File
@@ -1,5 +1,5 @@
{
"originHash" : "70ed310397f7785149edfd3c75ea1be84b43c694430c1a7d8a48d1da0809d3b5",
"originHash" : "c7a8ecfa1983b2d2cd303da1fc360a5329a8fe77440411341561bb35dd3c197a",
"pins" : [
{
"identity" : "aexml",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/async-http-client.git",
"state" : {
"revision" : "3a5b74a58782c3b4c1f0bc75e9b67b10c2494e8f",
"version" : "1.33.1"
"revision" : "f95c908967e98c68c5ce3fd61a7974e7e869e303",
"version" : "1.36.1"
}
},
{
@@ -24,8 +24,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/attaswift/BigInt",
"state" : {
"revision" : "e07e00fa1fd435143a2dcf8b7eec9a7710b2fdfe",
"version" : "5.7.0"
"revision" : "63feef7820abb1a8fb08587d7da56bb0b7db8751",
"version" : "6.0.1"
}
},
{
@@ -33,8 +33,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/combine-schedulers",
"state" : {
"revision" : "dcccb979a2183b8df3334237e3dc1ae2b4116a86",
"version" : "1.2.0"
"revision" : "114354e8c1667a2edc4993700fb9fa4f90157b56",
"version" : "1.2.2"
}
},
{
@@ -51,8 +51,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/mattpolzin/OpenAPIKit",
"state" : {
"revision" : "57b6318128e3f901c93f4fbf98d1c1464ec168d3",
"version" : "6.2.0"
"revision" : "5b72eb9a6b23b1fec439d9a0bf38f115400421f9",
"version" : "6.4.0"
}
},
{
@@ -69,8 +69,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/onevcat/Rainbow.git",
"state" : {
"revision" : "cdf146ae671b2624917648b61c908d1244b98ca1",
"version" : "4.2.1"
"revision" : "711ca908ca19d16e577d575c8d0a48151a16bb1b",
"version" : "4.2.2"
}
},
{
@@ -85,7 +85,7 @@
{
"identity" : "swift-algorithms",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-algorithms.git",
"location" : "https://github.com/apple/swift-algorithms",
"state" : {
"revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023",
"version" : "1.2.1"
@@ -96,8 +96,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-argument-parser",
"state" : {
"revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b",
"version" : "1.7.1"
"revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
"version" : "1.8.2"
}
},
{
@@ -105,8 +105,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "eb50cbd14606a9161cbc5d452f18797c90ef0bab",
"version" : "1.7.0"
"revision" : "3b6410f7dee09eb33cdd26260c5fd47fda19b0e2",
"version" : "1.7.3"
}
},
{
@@ -114,8 +114,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-async-algorithms.git",
"state" : {
"revision" : "9d349bcc328ac3c31ce40e746b5882742a0d1272",
"version" : "1.1.3"
"revision" : "3da39bbc4e687d4192af7c9cf4eab805745a0b9c",
"version" : "1.1.5"
}
},
{
@@ -123,8 +123,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-atomics.git",
"state" : {
"revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7",
"version" : "1.3.0"
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
"version" : "1.3.1"
}
},
{
@@ -132,8 +132,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-certificates",
"state" : {
"revision" : "bde8ca32a096825dfce37467137c903418c1893d",
"version" : "1.19.1"
"revision" : "ff86b924ead66f853b8baf91f3c41926a8f36177",
"version" : "1.21.0"
}
},
{
@@ -141,8 +141,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-clocks",
"state" : {
"revision" : "cc46202b53476d64e824e0b6612da09d84ffde8e",
"version" : "1.0.6"
"revision" : "82440fa0a8b1c381a6d1e8e0fc7bbba53ec63204",
"version" : "1.1.1"
}
},
{
@@ -150,8 +150,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-collections",
"state" : {
"revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a",
"version" : "1.5.1"
"revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",
"version" : "1.6.0"
}
},
{
@@ -159,8 +159,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-concurrency-extras",
"state" : {
"revision" : "5a3825302b1a0d744183200915a47b508c828e6f",
"version" : "1.3.2"
"revision" : "5fa253428866f2360c3754e88537f700ed2656b5",
"version" : "1.4.1"
}
},
{
@@ -168,8 +168,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-configuration.git",
"state" : {
"revision" : "be76c4ad929eb6c4bcaf3351799f2adf9e6848a9",
"version" : "1.2.0"
"revision" : "3533f65d3e36dcdffc91ce34ef4d3c9c1887fd4b",
"version" : "1.2.1"
}
},
{
@@ -177,8 +177,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto",
"state" : {
"revision" : "1b6b2e274e85105bfa155183145a1dcfd63331f1",
"version" : "4.5.0"
"revision" : "a9d1d5ab8951ada40cafff8c8e2b551dfde4f390",
"version" : "5.0.0"
}
},
{
@@ -186,8 +186,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-dependencies",
"state" : {
"revision" : "706feb7858a7f6c242879d137b8ee30926aa5b26",
"version" : "1.12.0"
"revision" : "b476cc5761057d8d857de063fe7ac8daecf5c06b",
"version" : "1.17.1"
}
},
{
@@ -195,8 +195,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-distributed-tracing.git",
"state" : {
"revision" : "dc4030184203ffafbb2ec614352487235d747fe0",
"version" : "1.4.1"
"revision" : "cc504a45f6ce73ce6067837d7ac19fa67b229a56",
"version" : "1.5.0"
}
},
{
@@ -231,8 +231,17 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-http-types",
"state" : {
"revision" : "45eb0224913ea070ec4fba17291b9e7ecf4749ca",
"version" : "1.5.1"
"revision" : "bff4b6903cdc99dda49649dd52f46c11cfd3ed50",
"version" : "1.8.0"
}
},
{
"identity" : "swift-issue-reporting",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/swift-issue-reporting",
"state" : {
"revision" : "75b000cea2ca6d7527a57e1b9cc0bdf21a9abe9f",
"version" : "2.1.1"
}
},
{
@@ -240,8 +249,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log.git",
"state" : {
"revision" : "5073617dac96330a486245e4c0179cb0a6fd2256",
"version" : "1.12.0"
"revision" : "9c6fb14227f55d8f711ce3847dc2f419fb0ecacb",
"version" : "1.15.1"
}
},
{
@@ -249,8 +258,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio",
"state" : {
"revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237",
"version" : "2.99.0"
"revision" : "21de5f08c1a166a6dd293d0e587ad977bf8dac5d",
"version" : "2.103.0"
}
},
{
@@ -258,8 +267,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-extras.git",
"state" : {
"revision" : "5a48717e29f62cb8326d6d42e46b562ca93847a6",
"version" : "1.34.0"
"revision" : "41449336c8ecfadac6b4b5be75f9c3c306e61ced",
"version" : "1.35.1"
}
},
{
@@ -267,8 +276,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-http2.git",
"state" : {
"revision" : "81cc18264f92cd307ff98430f89372711d4f6fe9",
"version" : "1.43.0"
"revision" : "0f3e54e29c944c2e835ad52159da7d9e1c94ac69",
"version" : "1.46.0"
}
},
{
@@ -276,8 +285,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-ssl.git",
"state" : {
"revision" : "3f337058ccd7243c4cac7911477d8ad4c598d4da",
"version" : "2.37.0"
"revision" : "322f3c2a4a21df31c84ca416bf65ee5e9059e440",
"version" : "2.37.5"
}
},
{
@@ -312,8 +321,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-generator",
"state" : {
"revision" : "5dd0da1c7da7bac8f0c458a02a76f69031137a80",
"version" : "1.12.1"
"revision" : "39d49cf22abab58a07f02bb76808b5d2839b294a",
"version" : "1.13.1"
}
},
{
@@ -321,8 +330,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-runtime",
"state" : {
"revision" : "f039fa6d6338aab5164f3d1be16281524c9a8f89",
"version" : "1.11.0"
"revision" : "9e53df53e043b53046a371b31aaf0a1e26eef946",
"version" : "1.12.1"
}
},
{
@@ -330,8 +339,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-openapi-urlsession",
"state" : {
"revision" : "576a65b4ffb8c12ddad4950dc21eea2ef071bec2",
"version" : "1.3.0"
"revision" : "08796d36c99ad2318929bfa1d1e40f82194b65cc",
"version" : "1.3.1"
}
},
{
@@ -348,8 +357,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/swift-service-lifecycle",
"state" : {
"revision" : "9829955b385e5bb88128b73f1b8389e9b9c3191a",
"version" : "2.11.0"
"revision" : "7f9326b0326ff86e3646295ea6e891f68c471c5e",
"version" : "2.12.0"
}
},
{
@@ -357,8 +366,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-subprocess",
"state" : {
"revision" : "11633673a41f509f8945f23c96c7acd4adafd679",
"version" : "0.5.0"
"revision" : "b3937ab85dd32f6e9435914599c1519074769c1a",
"version" : "1.0.0"
}
},
{
@@ -366,8 +375,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-syntax",
"state" : {
"revision" : "9de99a78f099e59caf2b2beec65a4c45d54b2081",
"version" : "603.0.1"
"revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf",
"version" : "604.0.0"
}
},
{
@@ -375,8 +384,17 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-system",
"state" : {
"revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df",
"version" : "1.6.4"
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
"version" : "1.8.1"
}
},
{
"identity" : "swift-tools-protocols",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-tools-protocols",
"state" : {
"revision" : "d81024558da3bcd53748c4cfdaba10a49242442e",
"version" : "0.0.10"
}
},
{
@@ -438,8 +456,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/yonaskolb/XcodeGen",
"state" : {
"revision" : "8d3d3476a69ae3e5d68e1adccc701c410c05eb36",
"version" : "2.45.4"
"revision" : "8445e778451c7e44237b90281bde622d764b0084",
"version" : "2.46.0"
}
},
{
@@ -447,17 +465,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/tuist/XcodeProj.git",
"state" : {
"revision" : "01bb77000bc8c23a09ea2058f4954612f03cb705",
"version" : "9.10.1"
}
},
{
"identity" : "xctest-dynamic-overlay",
"kind" : "remoteSourceControl",
"location" : "https://github.com/pointfreeco/xctest-dynamic-overlay",
"state" : {
"revision" : "dfd70507def84cb5fb821278448a262c6ff2bbad",
"version" : "1.9.0"
"revision" : "eb001108f64467b0cc7e8cbf90b3b4aaa1822cbb",
"version" : "9.14.0"
}
},
{
@@ -483,8 +492,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/xtool-org/zsign",
"state" : {
"revision" : "19aab76b3f1388966a3ed4fc11b357f95aafc70b",
"version" : "1.8.0"
"revision" : "f6158be9e62a5ce2a53d72b1a6d880880da956c8",
"version" : "1.9.0"
}
}
],
+12 -7
View File
@@ -30,8 +30,8 @@ let swiftSettings: [SwiftSetting] = {
let package = Package(
name: "xtool",
platforms: [
.iOS(.v16),
.macOS(.v13),
.iOS(.v17),
.macOS(.v14),
],
products: [
.library(
@@ -50,21 +50,25 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/xtool-org/xtool-core", .upToNextMinor(from: "1.5.0")),
.package(url: "https://github.com/xtool-org/SwiftyMobileDevice", .upToNextMinor(from: "1.7.0")),
.package(url: "https://github.com/xtool-org/zsign", .upToNextMinor(from: "1.8.0")),
.package(url: "https://github.com/xtool-org/zsign", .upToNextMinor(from: "1.9.0")),
.package(url: "https://github.com/xtool-org/xadi", .upToNextMinor(from: "0.4.1")),
.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: "4.5.0"),
.package(url: "https://github.com/apple/swift-crypto", from: "5.0.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"),
// v1.7.0 has a crash on old OSes: https://github.com/apple/swift-collections/issues/733.
// pin 1.6.0 until 1.7.1 is released.
.package(url: "https://github.com/apple/swift-collections", exact: "1.6.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/swiftlang/swift-subprocess", from: "1.0.0"),
.package(url: "https://github.com/swiftlang/swift-tools-protocols", exact: "0.0.10"),
.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"),
@@ -73,7 +77,7 @@ let package = Package(
.package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.3.0"),
.package(url: "https://github.com/pointfreeco/swift-dependencies", from: "1.6.2"),
.package(url: "https://github.com/attaswift/BigInt", from: "5.5.0"),
.package(url: "https://github.com/attaswift/BigInt", from: "6.0.0"),
.package(url: "https://github.com/mxcl/Version", from: "2.1.0"),
.package(url: "https://github.com/jpsim/Yams", from: "5.1.3"),
.package(url: "https://github.com/saagarjha/unxip", from: "3.2.0"),
@@ -129,7 +133,7 @@ let package = Package(
.product(name: "ProtoCodable", package: "xtool-core"),
.product(name: "Superutils", package: "xtool-core"),
.product(name: "Crypto", package: "swift-crypto"),
.product(name: "_CryptoExtras", package: "swift-crypto"),
.product(name: "CryptoExtras", package: "swift-crypto"),
.product(name: "X509", package: "swift-certificates"),
.product(name: "BigInt", package: "BigInt"),
.product(name: "HTTPTypes", package: "swift-http-types"),
@@ -173,6 +177,7 @@ let package = Package(
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "Version", package: "Version"),
.product(name: "libunxip", package: "unxip"),
.product(name: "LanguageServerProtocolTransport", package: "swift-tools-protocols"),
],
cSettings: cSettings,
swiftSettings: swiftSettings,
+4
View File
@@ -0,0 +1,4 @@
#include "inotify_shim.h"
#include "stdout_shim.h"
#include "version.h"
#include "mobileprovision.h"
+21
View File
@@ -0,0 +1,21 @@
#ifndef CINOTIFY_SHIMS_H
#define CINOTIFY_SHIMS_H
#ifdef __linux__
#include <stdio.h>
#include <stdint.h>
#include <sys/inotify.h>
static inline const char *cin_event_name(const struct inotify_event *event) {
if (event->len)
return event->name;
else
return NULL;
}
static const uint32_t cin_all_events = IN_ALL_EVENTS;
#endif
#endif /* CINOTIFY_SHIMS_H */
+2 -2
View File
@@ -79,7 +79,7 @@ public struct BuildSettings: Sendable {
arguments: .init(arguments),
output: .string(limit: .max)
).checkSuccess()
return result.standardOutput?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return result.standardOutput.trimmingCharacters(in: .whitespacesAndNewlines)
}
private static let _swiftURL = Task {
@@ -137,7 +137,7 @@ public struct BuildSettings: Sendable {
}
return Configuration(
executable,
executable: executable,
arguments: .init(baseArguments + resolvedBaseOptions + arguments),
environment: .inherit.updating(sdkEnvironment),
platformOptions: .withGracefulShutDown,
@@ -8,7 +8,7 @@
import Foundation
import Crypto
import _CryptoExtras
import CryptoExtras
import BigInt
struct SRPClient {
+1 -1
View File
@@ -9,7 +9,7 @@
import Foundation
import Crypto
import X509
import _CryptoExtras
import CryptoExtras
public struct PrivateKey: Codable, Sendable {
// pem encoded
+5
View File
@@ -67,6 +67,11 @@ public actor Signer {
) throws {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
var entitlementMapping = entitlementMapping
if entitlementMapping.isEmpty {
// zsign_sign requires at least one entitlements_data_t
entitlementMapping[app] = try Entitlements(entitlements: [])
}
let entsArray: [entitlements_data_t] = try entitlementMapping.map { url, ents in
try url.withUnsafeFileSystemRepresentation { bundlePath in
guard let bundlePath = bundlePath else { throw Error.badFilePath }
+1 -1
View File
@@ -23,7 +23,7 @@ struct DevBSPCommand: AsyncParsableCommand {
)
try await Subprocess.run(
settings.buildServerInvocation(),
input: .standardInput,
input: .currentStandardInput,
output: .currentStandardOutput,
error: .currentStandardError,
)
+70 -49
View File
@@ -23,10 +23,30 @@ struct PackOperation {
var triple: String?
var buildOptions = BuildOptions(configuration: .debug)
var extraOptions: [String] = []
var watchMode = false
var xcode = false
func buildSettings() async throws -> BuildSettings {
try await BuildSettings(
configuration: buildOptions.configuration,
triple: triple ?? Self.defaultTriple,
options: extraOptions + (
watchMode
? [
"-Xlinker", "-interposable",
// https://kyleye.top/posts/debugreplaceableview-multiple-type-erasers/
"-Xswiftc", "-enable-experimental-feature", "-Xswiftc", "OpaqueTypeErasure",
// https://www.guardsquare.com/blog/behind-swiftui-previews
"-Xswiftc", "-Xfrontend", "-Xswiftc", "-enable-private-imports",
]
: []
)
)
}
@discardableResult
func run() async throws -> URL {
func run() async throws -> (Plan, URL) {
// TODO: support running inside a child directory
let contents = try FileManager.default.contentsOfDirectory(atPath: ".")
@@ -54,11 +74,7 @@ struct PackOperation {
await LSPConfig.tryEnsure(using: schema)
let buildSettings = try await BuildSettings(
configuration: buildOptions.configuration,
triple: triple ?? Self.defaultTriple,
options: []
)
let buildSettings = try await buildSettings()
let planner = Planner(
buildSettings: buildSettings,
@@ -68,7 +84,8 @@ struct PackOperation {
#if os(macOS)
if xcode {
return try await XcodePacker(plan: plan).createProject()
let url = try await XcodePacker(plan: plan).createProject()
return (plan, url)
}
#endif
@@ -81,28 +98,26 @@ struct PackOperation {
let productsWithEntitlements = plan
.allProducts
.compactMap { p in p.entitlementsPath.map { (p, $0) } }
if !productsWithEntitlements.isEmpty {
let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements).self) { group in
for (product, path) in productsWithEntitlements {
group.addTask {
let data = try await Data(reading: URL(fileURLWithPath: path))
let decoder = PropertyListDecoder()
let entitlements = try decoder.decode(Entitlements.self, from: data)
return (product.directory(inApp: bundle), entitlements)
}
let mapping = try await withThrowingTaskGroup(of: (URL, Entitlements?).self) { group in
for (product, path) in productsWithEntitlements {
group.addTask {
let data = try await Data(reading: URL(fileURLWithPath: path))
let decoder = PropertyListDecoder()
let entitlements = try decoder.decode(Entitlements.self, from: data)
return (product.directory(inApp: bundle), entitlements)
}
return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
}
print("Applying entitlements...")
try await Signer.first().sign(
app: bundle,
identity: .adhoc,
entitlementMapping: mapping,
progress: { _ in }
)
return try await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
}
print("Applying entitlements...")
try await Signer.first().sign(
app: bundle,
identity: .adhoc,
entitlementMapping: mapping,
progress: { _ in }
)
return bundle
return (plan, bundle)
}
}
@@ -157,7 +172,7 @@ struct DevBuildCommand: AsyncParsableCommand {
signingAuthToken = nil
}
let url = try await PackOperation(
let (_, url) = try await PackOperation(
triple: triple,
buildOptions: packOptions
).run()
@@ -222,6 +237,13 @@ struct DevRunCommand: AsyncParsableCommand {
help: "Target the iOS Simulator"
) var simulator = false
@Flag(
name: .shortAndLong,
help: "Hot reload files on change. Requires simulator."
) var watch = false
@Option var xloadPath: String?
var triple: String? {
if simulator {
#if arch(arm64)
@@ -235,17 +257,37 @@ struct DevRunCommand: AsyncParsableCommand {
return nil
}
#else
var watch: Bool { false }
var triple: String? { nil }
#endif
@OptionGroup var connectionOptions: ConnectionOptions
func validate() throws {
#if os(macOS)
if watch && !simulator {
throw ValidationError("--watch requires --simulator")
}
#endif
}
func run() async throws {
let output = try await PackOperation(triple: triple, buildOptions: packOptions).run()
let operation = PackOperation(
triple: triple,
buildOptions: packOptions,
watchMode: watch,
)
let (plan, output) = try await operation.run()
#if os(macOS)
if simulator {
try await SimInstallOperation(path: output).run()
try await SimInstallOperation(
operation: operation,
plan: plan,
path: output,
watch: watch,
xLoadLibrary: xloadPath,
).run()
return
}
#endif
@@ -294,24 +336,3 @@ struct DevCommand: AsyncParsableCommand {
}
extension BuildConfiguration: ExpressibleByArgument {}
#if os(macOS)
import Subprocess
struct SimInstallOperation {
var path: URL
// TODO: allow customizing this
var simulator = "booted"
func run() async throws {
try await Subprocess.run(
.path("/usr/bin/xcrun"),
arguments: ["simctl", "install", simulator, path.path],
output: .discarded
)
.checkSuccess()
print("Installed to simulator")
}
}
#endif
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
#if os(macOS)
import Foundation
import ArgumentParser
import PackLib
import XUtils
import Subprocess
struct HotReloadCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "hot-reload",
abstract: "Run an app with support for hot reloading",
)
@Flag(
help: "Use the SwiftPM build system to determine compile commands"
) var swiftpm = false
@Option(
help: .init(
"Use the specified Build Server to determine compile commands",
discussion: """
The file at the specified path should correspond to the BSP \
Connection Details specification. See:
https://build-server-protocol.github.io/docs/overview/server-discovery
""",
)
) var buildServerPath: String?
@Option(
help: "The directory in which to store scratch files"
) var scratchDirectory: String?
@Option(
help: "String to prepend to all env var names"
) var envPrefix: String = ""
@Option(
help: .hidden
) var xloadLibrary: String?
@Argument(
help: .init(
"The command to run with hot reloading",
discussion: """
xtool spawns the provided process with env vars set to enable hot reloading.
"""
)
) var command: [String]
func run() async throws {
let configuration: BuildServerConfiguration
switch (swiftpm, buildServerPath) {
case (true, _?):
throw ValidationError("Both --swiftpm or --build-server-path were provided; please only provide one.")
case (true, nil):
configuration = try await .swiftPM(settings: BuildSettings(configuration: .debug, triple: "arm64-apple-ios-simulator"))
case (false, let serverPath?):
configuration = try await .external(definition: URL(filePath: serverPath))
case (false, nil):
if let discovered = try await BuildServerConfiguration.discover(in: URL(filePath: ".")) {
configuration = discovered
} else {
throw ValidationError("Could not guess build system. Please specify one with --swiftpm or --build-server-path")
}
}
let reloader = try await HotReloader(
configuration: configuration,
scratchDirectory: scratchDirectory.map { FilePath($0) },
xLoadLibrary: xloadLibrary
)
let watchTask = Task {
do {
try await reloader.watch()
} catch {
print("Error: watcher failed: \(error)")
}
}
var arguments = command
let executable = arguments.removeFirst()
try await Subprocess.run(
.name(executable),
arguments: Arguments(arguments),
environment: .inherit.updating(reloader.subprocessEnvironment(prefix: envPrefix)),
platformOptions: .withGracefulShutDown,
output: .currentStandardOutput,
error: .currentStandardError,
)
.checkSuccess()
watchTask.cancel()
await watchTask.value
}
}
#endif
+111
View File
@@ -0,0 +1,111 @@
#if os(macOS)
import Subprocess
import PackLib
import Foundation
import XUtils
import Dependencies
import XKit
actor HotReloader {
var configuration: BuildServerConfiguration
var scratchDirectory: FilePath
var xLoadLibrary: String?
private let scratchTemporaryDirectory: TemporaryDirectory?
private let xLoadPath: String
private let buildDirectory: FilePath
private let outDirectory: FilePath
init(
configuration: BuildServerConfiguration,
scratchDirectory: FilePath? = nil,
xLoadLibrary: String? = nil,
) async throws {
self.configuration = configuration
if let scratchDirectory {
self.scratchDirectory = FilePath(URL(filePath: scratchDirectory.string).absoluteURL.path)
self.scratchTemporaryDirectory = nil
} else {
let scratchTemporaryDirectory = try TemporaryDirectory(name: "scratch")
self.scratchDirectory = FilePath(scratchTemporaryDirectory.url.path)
self.scratchTemporaryDirectory = consume scratchTemporaryDirectory
}
self.xLoadLibrary = xLoadLibrary
xLoadPath = if let xLoadLibrary {
URL(filePath: xLoadLibrary).absoluteURL.path
} else {
try await Self.getXLoad(platform: "iphonesimulator").path
}
buildDirectory = self.scratchDirectory.appending("build")
try FileManager.default.createDirectory(at: URL(filePath: buildDirectory)!, withIntermediateDirectories: true)
outDirectory = self.scratchDirectory.appending("out")
try FileManager.default.createDirectory(at: URL(filePath: outDirectory)!, withIntermediateDirectories: true)
}
nonisolated func environment(prefix: String = "SIMCTL_CHILD_") -> [String: String] {
[
"\(prefix)DYLD_INSERT_LIBRARIES": xLoadPath,
"\(prefix)XLOAD_WATCH_DIR": outDirectory.string,
"\(prefix)XLOAD_INTERCEPT": "1",
]
}
nonisolated func subprocessEnvironment(prefix: String = "SIMCTL_CHILD_") -> [Environment.Key: String] {
Dictionary(uniqueKeysWithValues: environment(prefix: prefix).map {
(Environment.Key(rawValue: $0)!, $1)
})
}
func watch() async throws {
let workspace = try await SwiftWorkspace(
configuration: configuration,
buildDirectory: buildDirectory,
outDirectory: outDirectory,
)
@Dependency(\.fileSystemMonitor) var fileSystemMonitor
let events = try await fileSystemMonitor.watch(FilePath(FileManager.default.currentDirectoryPath))
for await event in events {
do {
try await workspace.fileDidChange(event.file)
} catch {
print("Reload failed: \(error)")
}
}
}
private static func getXLoad(platform: String) async throws -> URL {
let version = "0.3.0"
let remote = URL(string: "https://github.com/xtool-org/xload/releases/download/v\(version)/libXLoad.\(platform).dylib")!
@Dependency(\.httpClient) var httpClient
@Dependency(\.persistentDirectory) var persistentDirectory
let platformDir = persistentDirectory.appending(path: "xload/\(platform)")
let versionDir = platformDir.appending(path: version)
let local = versionDir.appending(path: "libXLoad.dylib")
if local.exists { return local }
print("Downloading xload...")
try? FileManager.default.removeItem(at: platformDir)
try FileManager.default.createDirectory(at: versionDir, withIntermediateDirectories: true)
let data = try await httpClient.makeRequest(HTTPRequest(url: remote))
guard data.response.status.kind == .successful else {
throw StringError("Failed to download xload: got HTTP \(data.response.status)")
}
try data.body.write(to: local)
return local
}
}
#endif
+35 -3
View File
@@ -76,7 +76,7 @@ struct SDKBuilder {
let mode: Mode
// bump this when the sdk builder logic changes
static let sdkEpoch = 2
static let sdkEpoch = 3
// tag from https://github.com/xtool-org/darwin-tools-linux-llvm
static let darwinToolsVersion = "1.1.0"
@@ -425,6 +425,8 @@ struct SDKBuilder {
print()
}
private static let expectedXcodeChildren = ["Info.plist", "version.plist", "Developer"]
// swiftlint:disable:next cyclomatic_complexity function_body_length
private func installDeveloper(in output: URL) async throws -> URL {
let dev = output.appendingPathComponent("Developer")
@@ -458,19 +460,25 @@ struct SDKBuilder {
wanted = try await extractXIP(inputPath: inputPath, outDir: output.path)
appDir = expectedAppDir
cleanupStageDir = nil
try cleanUpXcode(appDir)
case (.xip, .update):
throw Console.Error("Can't update with xip input")
case (.app(let appPath), .buildSlim), (.app(let appPath), .update):
case (.app(let appPath), .buildSlim):
appDir = URL(fileURLWithPath: appPath)
wanted = nil
cleanupStageDir = nil
case (.app(let appPath), .update):
appDir = URL(fileURLWithPath: appPath)
wanted = nil
cleanupStageDir = nil
try cleanUpXcode(appDir)
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"] {
for child in Self.expectedXcodeChildren {
let expectedFile = expectedContentsDir.appendingPathComponent(child)
let sourceFile = sourceContentsDir.appendingPathComponent(child)
guard FileManager.default.fileExists(atPath: sourceFile.path) else {
@@ -630,6 +638,30 @@ struct SDKBuilder {
return dev
}
/// Removes unneeded files from a copy of Xcode.app that's owned by xtool.
///
/// This is conservative: we keep anything that we expect _might_ be necessary
/// even in a future update of xtool, so that SDK self-updates work. We only
/// delete files that we're relatively confident won't be needed.
///
/// - Important: ONLY call this if we own appDir, lest we delete files from the user's Xcode.
private func cleanUpXcode(_ appDir: URL) throws {
let contentsDir = appDir.appendingPathComponent("Contents")
let contents = try FileManager.default.contentsOfDirectory(
at: contentsDir,
includingPropertiesForKeys: nil
)
let expectedChildren = Set(Self.expectedXcodeChildren)
let missingChildren = expectedChildren.subtracting(contents.map(\.lastPathComponent))
guard missingChildren.isEmpty else {
let missing = missingChildren.sorted().joined(separator: ", ")
throw Console.Error("Unrecognized xip layout: missing \(missing)")
}
for child in contents where !expectedChildren.contains(child.lastPathComponent) {
try FileManager.default.removeItem(at: child)
}
}
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
@@ -0,0 +1,81 @@
#if os(macOS)
import Subprocess
import PackLib
import Foundation
import XUtils
import Dependencies
import XKit
struct SimInstallOperation {
var operation: PackOperation
var plan: Plan
var path: URL
var watch = false
var xLoadLibrary: String?
// TODO: allow customizing this
var simulator = "booted"
func run() async throws {
try await Subprocess.run(
.path("/usr/bin/xcrun"),
arguments: ["simctl", "install", simulator, path.path],
output: .discarded
)
.checkSuccess()
print("Installed to simulator")
let tmp = URL(filePath: FileManager.default.currentDirectoryPath)
.appending(path: "xtool/.xload")
try? FileManager.default.removeItem(at: tmp)
defer { try? FileManager.default.removeItem(at: tmp) }
let watchTask: Task<Void, Error>?
let envVars: [Environment.Key: String?]
if watch {
try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
guard let temporaryDirectoryPath = FilePath(tmp) else {
throw Console.Error("Bad temporaryDirectory path")
}
let hotReloader = try await HotReloader(
configuration: .swiftPM(settings: operation.buildSettings()),
scratchDirectory: temporaryDirectoryPath,
xLoadLibrary: xLoadLibrary
)
watchTask = Task {
do {
try await hotReloader.watch()
} catch {
print("Error: watch task failed: \(error)")
}
}
envVars = hotReloader.subprocessEnvironment()
} else {
watchTask = nil
envVars = [:]
}
try await Subprocess.run(
.path("/usr/bin/xcrun"),
arguments: [
"simctl", "launch",
"--console-pty",
simulator, plan.app.bundleID,
],
environment: .inherit.updating(envVars),
platformOptions: .withGracefulShutDown,
output: .currentStandardOutput,
error: .currentStandardError,
)
.checkSuccess()
watchTask?.cancel()
try await watchTask?.value
}
}
#endif
+397
View File
@@ -0,0 +1,397 @@
import Foundation
import XUtils
import PackLib
import BuildServerProtocol
import LanguageServerProtocol
import LanguageServerProtocolTransport
import Subprocess
import Dependencies
actor SwiftWorkspace {
private let connection: JSONRPCConnection
private let buildDirectory: FilePath
private let outDirectory: FilePath
private var counter = 0
struct FileInfo {
let file: FilePath
let target: BuildTarget
let sources: SourcesItem
let source: SourceItem
init?(target: BuildTarget, sources: SourcesItem, source: SourceItem) {
guard let path = FilePath(source.uri.arbitrarySchemeURL) else { return nil }
self.file = path
self.target = target
self.sources = sources
self.source = source
}
}
private var filesToWatch: [FilePath: [FileInfo]] = [:]
private var sources: [(BuildTarget, SourcesItem)] {
didSet { updateFilesToWatch() }
}
private var cachedCommands: [FilePath: FrontendCommand] = [:]
struct FrontendCommand {
let commandLine: CommandInvocation
let output: FilePath
let module: String
}
init(
configuration: BuildServerConfiguration,
buildDirectory: FilePath,
outDirectory: FilePath,
) async throws {
self.buildDirectory = buildDirectory
self.outDirectory = outDirectory
let handler = StreamingMessageHandler()
let (connection, _) = try JSONRPCConnection.start(
executable: configuration.executable,
arguments: configuration.arguments,
name: "xtool",
protocol: .bspProtocol,
stderrLoggingCategory: "xtool-error",
client: handler,
terminationHandler: { print("Terminated: \($0)") }
)
self.connection = connection
_ = try await connection.send(InitializeBuildRequest(
displayName: "xtool",
version: "1.0.0",
bspVersion: "2.2.0",
rootUri: .init(URL(filePath: FileManager.default.currentDirectoryPath)),
capabilities: BuildClientCapabilities(
languageIds: [.swift, .c, .cpp, .objective_c, .objective_cpp],
)
))
connection.send(OnBuildInitializedNotification())
// some BSP servers (eg SourceKit-Bazel-BSP) require an initial build targets request
// before they send OnBuildTargetDidChange
_ = try await connection.send(WorkspaceBuildTargetsRequest())
for await case _ as OnBuildTargetDidChangeNotification in handler.notifications { break }
let result = try await connection.send(WorkspaceBuildTargetsRequest())
let targets = Dictionary(uniqueKeysWithValues: result.targets.map { ($0.id, $0) })
let targetInfos = try await connection.send(BuildTargetSourcesRequest(
targets: result.targets.map(\.id)
))
sources = targetInfos.items.compactMap {
guard let target = targets[$0.target] else { return nil }
return (target, $0)
}
updateFilesToWatch()
}
deinit {
connection.close()
}
func updateFilesToWatch() {
filesToWatch = Dictionary(
grouping: sources.flatMap { target, sources in
sources.sources.compactMap { source in
// guard !target.id.uri.stringValue.contains("&targetGUID=PACKAGE-TARGET:") else { return nil }
FileInfo(target: target, sources: sources, source: source)
}
},
by: \.file
)
}
func fileDidChange(_ path: FilePath) async throws {
guard filesToWatch[path] != nil else { return }
print("Reloading \(path)")
_ = try await rebuild(path: path)
}
@discardableResult
func rebuild(path: FilePath) async throws -> FilePath {
let command = try await frontendCommand(for: path)
try await Subprocess.run(
.path(FilePath(String(command.commandLine.command))),
arguments: .init(command.commandLine.arguments.map { String($0) }),
output: .currentStandardOutput,
error: .currentStandardError,
)
.checkSuccess()
let sdk = try command.commandLine.value(for: "-sdk")
.orThrow(Console.Error("Could not find -sdk"))
let target = try command.commandLine.value(for: "-target")
.orThrow(Console.Error("Could not find -target"))
counter += 1
let outputFile = outDirectory
.appending("lib\(path.lastComponent!.stem).\(counter).dylib")
// link
try await Subprocess.run(
.path(try await BuildSettings.swiftcURL()),
arguments: [
command.output.string,
"-emit-library",
"-sdk", sdk, "-target", target,
"-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup",
"-o", outputFile.string
],
output: .currentStandardOutput,
error: .currentStandardError,
)
.checkSuccess()
return outputFile
}
func frontendCommand(for path: FilePath) async throws -> FrontendCommand {
if let cached = cachedCommands[path] {
return cached
}
let targets = filesToWatch[path] ?? []
let target: FileInfo
switch targets.count {
case 0:
throw Console.Error("No targets for file")
case 1:
target = targets[0]
default:
print("warning: multiple targets contain this file: \(targets.map(\.target.id.uri))")
target = targets[0]
}
guard let fileURL = URL(filePath: path)?.absoluteURL, let lastComponent = path.lastComponent else {
throw Console.Error("Bad file path \(path.string)")
}
let options = try await connection.send(TextDocumentSourceKitOptionsRequest(
textDocument: .init(target.source.uri),
target: target.target.id,
language: .swift,
))
.orThrow(Console.Error("No options"))
guard let moduleNameIndex = options.compilerArguments.firstIndex(of: "-module-name"),
moduleNameIndex < options.compilerArguments.count - 2 else {
throw Console.Error("Could not determine module name for file at \(path)")
}
let moduleName = options.compilerArguments[moduleNameIndex + 1]
let moduleBuildDirectory = buildDirectory.appending(moduleName)
let moduleBuildDirectoryURL = try URL(filePath: moduleBuildDirectory).orThrow(Console.Error("Bad module name"))
try? FileManager.default.createDirectory(at: moduleBuildDirectoryURL, withIntermediateDirectories: true)
let swiftcOutput = try await Subprocess.run(
.path(try await BuildSettings.swiftcURL()),
arguments: .init(
["-c", "-driver-print-jobs"]
+ options.compilerArguments
+ ["-working-directory", moduleBuildDirectory.string]
),
output: .string(limit: .max),
error: .currentStandardError
).checkSuccess()
let frontendCommands = (swiftcOutput.standardOutput ?? "").split(separator: "\n")
guard let invocation = frontendCommands.lazy.compactMap({ line -> CommandInvocation? in
guard let invocation = CommandInvocation(line) else { return nil }
guard invocation.value(for: "-primary-file") == fileURL.path else { return nil }
return invocation
}).first else { throw Console.Error("Could not find frontend command") }
let command = FrontendCommand(
commandLine: invocation,
output: moduleBuildDirectory.appending("\(lastComponent.stem).o"),
module: moduleName,
)
cachedCommands[path] = command
return command
}
private final class StreamingMessageHandler: MessageHandler {
private let (_notifications, onNotification) = AsyncStream<NotificationType>.makeStream()
var notifications: AsyncStream<NotificationType> { _notifications }
deinit { onNotification.finish() }
func handle(_ notification: some NotificationType) {
onNotification.yield(notification)
}
func handle<Request: RequestType>(
_ request: Request,
id: LanguageServerProtocol.RequestID,
reply: @escaping @Sendable (LanguageServerProtocol.LSPResult<Request.Response>) -> Void
) {
fatalError("Can't handle request \(Request.method)")
}
}
}
// https://github.com/swiftlang/sourcekit-lsp/blob/3278ca0e3/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift#L66
struct BuildServerConfiguration {
var executable: URL
var arguments: [String]
}
// https://build-server-protocol.github.io/docs/overview/server-discovery#the-bsp-connection-details
struct BuildServerDefinition: Codable {
var name: String
var version: String
var bspVersion: String
var languages: [String]
var argv: [String]
}
extension BuildServerConfiguration {
static func swiftPM(settings: BuildSettings) async throws -> Self {
guard let swiftURL = URL(filePath: try await BuildSettings.swiftURL()) else {
throw Console.Error("Swift URL invalid")
}
return BuildServerConfiguration(
executable: swiftURL,
arguments: settings.withPackagePath("xtool/.xtool-tmp").buildServerArguments
)
}
static func swiftPM(in url: URL) async throws -> Self? {
if url.appending(path: "Package.swift").exists {
return try await .swiftPM(settings: .init(configuration: .debug, triple: "arm64-apple-ios-simulator"))
}
return nil
}
static func external(definition: BuildServerDefinition) async throws -> Self {
guard !definition.argv.isEmpty else {
throw Console.Error("BSP argv must be non-empty")
}
var arguments = definition.argv
let executable = URL(filePath: arguments.removeFirst())
return BuildServerConfiguration(
executable: executable,
arguments: arguments
)
}
static func external(definition url: URL) async throws -> Self {
let data = try Data(contentsOf: url)
let definition = try JSONDecoder().decode(BuildServerDefinition.self, from: data)
return try await .external(definition: definition)
}
static func external(in directory: URL) async throws -> Self? {
let bsp = directory.appending(path: ".bsp")
let bspContents = (try? FileManager.default.contentsOfDirectory(at: bsp, includingPropertiesForKeys: nil)) ?? []
let bspFiles = bspContents.filter { $0.pathExtension == "json" }
switch bspFiles.count {
case 0:
return nil
case 1:
return try await .external(definition: bspFiles[0])
default:
throw Console.Error("""
Found multiple Build Server definitions in '\(bsp.absoluteURL.path)'.
Please explicitly specify the one you want to use.
""")
}
}
static func discover(in directory: URL) async throws -> Self? {
if let external = try await external(in: directory) {
return external
}
if let swiftPM = try await swiftPM(in: directory) {
return swiftPM
}
return nil
}
}
struct CommandInvocation {
var command: String
var arguments: [String]
init?(_ string: some StringProtocol) {
guard let all = try? CommandParser.parse(string), !all.isEmpty else { return nil }
command = all[0]
arguments = Array(all.dropFirst())
}
func value(for option: some StringProtocol) -> String? {
guard let optionIndex = arguments.firstIndex(where: { $0 == option }) else { return nil }
guard optionIndex < arguments.count - 2 else { return nil }
return arguments[optionIndex + 1]
}
}
enum CommandParser {
enum Errors: Error, Hashable {
case unclosedQuote
case unpairedEscape
}
static func parse(_ string: some StringProtocol) throws -> [String] {
try sequence(
state: (
current: string[...],
isInsideQuote: false,
)
) { state -> Token? in
while !state.current.isEmpty {
switch state.current.removeFirst() {
case "'":
state.isInsideQuote.toggle()
case "\\" where !state.isInsideQuote:
guard !state.current.isEmpty else { return .error(.unpairedEscape) }
let actual = state.current.removeFirst()
return .value(actual)
case " " where !state.isInsideQuote:
return .sentinelSpace
case let value:
return .value(value)
}
}
guard !state.isInsideQuote else {
state.isInsideQuote = false
return .error(.unclosedQuote)
}
return nil
}
.lazy
.split(separator: .sentinelSpace)
.map {
let characters = try $0.compactMap { token -> Character? in
switch token {
case .sentinelSpace: nil
case .error(let error): throw error
case .value(let value): value
}
}
return String(characters)
}
}
private enum Token: Hashable {
case sentinelSpace
case value(Character)
case error(Errors)
}
}
+7 -1
View File
@@ -30,7 +30,13 @@ private struct XToolCommand: AsyncParsableCommand {
NewCommand.self,
DevCommand.self,
DSCommand.self,
]
] + { () -> [AsyncParsableCommand.Type] in
#if os(macOS)
[HotReloadCommand.self]
#else
[]
#endif
}()
),
CommandGroup(
name: "Device",
+1 -1
View File
@@ -43,7 +43,7 @@ extension FileManager {
do {
try result.checkSuccess()
} catch {
print("Error copying \(srcURL.path) to \(dstURL.path): \(result.standardError ?? "unknown")")
print("Error copying \(srcURL.path) to \(dstURL.path): \(result.standardError)")
throw error
}
return
@@ -0,0 +1,25 @@
import Testing
@testable import XToolSupport
@Test func commandParser() throws {
func sut(_ string: some StringProtocol) throws -> [String] {
try CommandParser.parse(string)
}
#expect(try sut(#""#).isEmpty)
#expect(try sut(#"foo"#) == ["foo"])
#expect(try sut(#"foo "#) == ["foo"])
#expect(try sut(#"foo one two"#) == ["foo", "one", "two"])
#expect(try sut(#"foo 'one two' three"#) == ["foo", "one two", "three"])
#expect(try sut(#"foo 'one!two' three"#) == ["foo", "one!two", "three"])
#expect(try sut(#"foo one\!two three"#) == ["foo", "one!two", "three"])
#expect(try sut(#"foo one\'two three"#) == ["foo", "one'two", "three"])
#expect(try sut(#"foo one'two three'four five"#) == ["foo", "onetwo threefour", "five"])
#expect(throws: CommandParser.Errors.unclosedQuote) {
try sut(#"foo one two' three"#)
}
#expect(throws: CommandParser.Errors.unpairedEscape) {
try sut(#"foo a b \"#)
}
}
+6 -7
View File
@@ -24,13 +24,12 @@ enum TestXcode {
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") {
let output = try await Subprocess.run(
.path("/usr/bin/xcode-select"),
arguments: ["-p"],
output: .string(limit: .max),
).standardOutput.trimmingCharacters(in: .whitespacesAndNewlines)
if output.hasSuffix(".app/Contents/Developer") {
return URL(filePath: output).deletingLastPathComponent().deletingLastPathComponent()
}
#endif
+1 -1
View File
@@ -1 +1 @@
3.4.3
4.0.7
+109 -84
View File
@@ -8,8 +8,8 @@ GEM
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1249.0)
aws-sdk-core (3.247.0)
aws-partitions (1.1287.0)
aws-sdk-core (3.257.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -17,11 +17,12 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.125.0)
aws-sdk-core (~> 3, >= 3.247.0)
rexml (~> 3.4, >= 3.4.2)
aws-sdk-kms (1.132.0)
aws-sdk-core (~> 3, >= 3.256.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.222.0)
aws-sdk-core (~> 3, >= 3.247.0)
aws-sdk-s3 (1.232.1)
aws-sdk-core (~> 3, >= 3.256.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
@@ -29,81 +30,75 @@ GEM
babosa (1.0.4)
base64 (0.3.0)
benchmark (0.5.0)
bigdecimal (4.1.2)
bigdecimal (4.1.3)
cgi (0.5.2)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
csv (3.3.5)
csv (3.3.6)
declarative (0.0.20)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20240107)
domain_name (0.6.20260907)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.5)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0)
faraday-multipart (~> 1.0)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.0)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
erb (6.0.7)
excon (1.7.1)
logger
faraday (2.14.4)
faraday-net_http (>= 2.0, < 3.5)
json
logger
faraday-cookie_jar (0.0.8)
faraday (>= 0.8.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-follow_redirects (0.5.0)
faraday (>= 1, < 3)
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.4)
faraday_middleware (1.2.1)
faraday (~> 1.0)
faraday-net_http (3.4.4)
net-http (~> 0.5)
faraday-retry (2.4.0)
faraday (~> 2.0)
fastimage (2.4.1)
fastlane (2.234.0)
fastlane (2.240.1)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.8, < 3.0.0)
addressable (>= 2.9.0, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
base64 (~> 0.2)
benchmark (>= 0.1.0)
bundler (>= 1.17.3, < 5.0.0)
bundler (>= 2.4.0, < 5.0.0)
cgi (~> 0.4)
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)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
excon (>= 0.71.0, < 2.0.0)
faraday (~> 2.7)
faraday-cookie_jar (~> 0.0.8)
faraday-follow_redirects (~> 0.3)
faraday-multipart (~> 1.0)
faraday-retry (~> 2.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.1.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-androidpublisher_v3 (~> 0.99)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, <= 2.1.1)
google-cloud-env (>= 1.6.0, < 2.4.0)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
irb (>= 1.8)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
jwt (>= 2.10.3, < 4)
logger (>= 1.6, < 2.0)
mini_magick (>= 4.9.4, < 5.0.0)
multi_json (~> 1.12)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3)
naturally (~> 2.2)
@@ -111,11 +106,11 @@ GEM
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)
rubyzip (>= 3.4.0, < 4.0.0)
security (~> 0.3)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (~> 3)
terminal-table (~> 4)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
@@ -127,29 +122,31 @@ GEM
fastlane-plugin-brew (~> 0.1.1)
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.100.0)
google-apis-androidpublisher_v3 (0.108.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
mini_mime (~> 1.0)
mutex_m
google-apis-core (1.2.5)
addressable (~> 2.9)
faraday (~> 2.13)
faraday-follow_redirects (~> 0.3)
googleauth (~> 1.14)
mini_mime (~> 1.1)
multi_json (~> 1.11)
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
google-apis-iamcredentials_v1 (0.27.0)
retriable (>= 3.1, < 5.0)
google-apis-iamcredentials_v1 (0.28.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.17.0)
google-apis-playcustomapp_v1 (0.18.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.62.0)
google-apis-storage_v1 (0.67.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.8.0)
google-cloud-core (1.9.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (2.1.1)
google-cloud-env (2.3.1)
base64 (~> 0.2)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.6.0)
google-cloud-storage (1.60.0)
google-cloud-errors (1.7.0)
google-cloud-storage (1.62.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-core (>= 0.18, < 2)
@@ -158,72 +155,100 @@ GEM
google-cloud-core (~> 1.6)
googleauth (~> 1.9)
mini_mime (~> 1.0)
googleauth (1.11.2)
google-logging-utils (0.2.0)
googleauth (1.17.4)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.1)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
google-cloud-env (~> 2.2)
google-logging-utils (~> 0.1)
jwt (>= 1.4, < 4.0)
os (>= 0.9, < 2.0)
pstore (~> 0.1)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.8)
http-cookie (1.1.6)
domain_name (~> 0.5)
httpclient (2.9.0)
mutex_m
io-console (0.9.4)
irb (1.18.0)
pp (>= 0.6.0)
prism (>= 1.3.0)
rdoc (>= 4.0.0)
reline (>= 0.4.2)
jmespath (1.6.2)
json (2.19.5)
jwt (2.10.2)
json (2.21.2)
jwt (3.3.0)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.21.1)
multi_json (1.21.2)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.3.0)
nkf (0.2.0)
net-http (0.9.1)
uri (>= 0.11.1)
nkf (0.3.0)
optparse (0.8.1)
os (1.1.4)
ostruct (0.6.3)
plist (3.7.2)
pp (0.6.4)
prettyprint
prettyprint (0.2.0)
prism (1.9.0)
pstore (0.2.1)
public_suffix (7.0.5)
rake (13.4.2)
rbs (4.2.0)
logger
prism (>= 1.6.0)
tsort
rdoc (8.0.0)
erb
prism (>= 1.6.0)
rbs (>= 4.0.0)
tsort
reline (0.7.0)
io-console (~> 0.5)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.4.1)
retriable (4.2.0)
rexml (3.4.4)
rouge (3.28.0)
ruby2_keywords (0.0.5)
rubyzip (2.4.1)
security (0.1.5)
signet (0.21.0)
rubyzip (3.7.0)
security (0.3.0)
signet (0.22.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 4.0)
multi_json (~> 1.10)
simctl (1.6.10)
CFPropertyList
naturally
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
terminal-table (4.0.0)
unicode-display_width (>= 1.1.1, < 4)
trailblazer-option (0.1.2)
tsort (0.2.0)
tty-cursor (0.7.1)
tty-screen (0.8.2)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unicode-display_width (2.6.0)
unicode-display_width (3.3.0)
unicode-emoji (~> 4.3)
unicode-emoji (4.3.0)
uri (1.1.1)
word_wrap (1.0.0)
xcodeproj (1.27.0)
xcodeproj (1.28.1)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
base64
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
nkf
rexml (>= 3.3.6, < 4.0)
xcpretty (0.4.1)
rouge (~> 3.28.0)
@@ -239,4 +264,4 @@ DEPENDENCIES
fastlane-plugin-xcodegen
BUNDLED WITH
2.6.7
4.0.20
+1 -1
View File
@@ -11,7 +11,7 @@ targets:
XToolMac:
type: application
platform: macOS
deploymentTarget: "13.0"
deploymentTarget: "14.0"
sources:
- path: XToolMac
- path: Resources/xtool