diff --git a/.gitignore b/.gitignore index 0dfd8eda33..61c0a22225 100644 --- a/.gitignore +++ b/.gitignore @@ -52,4 +52,5 @@ Carthage/Build # Local Node Modules for Apollo CLI node_modules/ -package-lock.json \ No newline at end of file +package-lock.json +scripts/apollo diff --git a/Apollo.podspec b/Apollo.podspec index 94f863a543..5f19bc80e2 100644 --- a/Apollo.podspec +++ b/Apollo.podspec @@ -22,7 +22,12 @@ Pod::Spec.new do |s| s.subspec 'Core' do |ss| ss.source_files = 'Sources/Apollo/*.swift' - ss.preserve_paths = ['scripts/check-and-run-apollo-cli.sh', 'scripts/check-and-run-apollo-codegen.sh'] + ss.preserve_paths = [ + 'scripts/check-and-run-apollo-cli.sh', + 'scripts/check-and-run-apollo-codegen.sh', + 'scripts/run-bundled-codegen.sh', + 'scripts/apollo.tar.gz', + ] end # Apollo provides exactly one persistent cache out-of-the-box, as a reasonable default choice for diff --git a/Apollo.xcodeproj/project.pbxproj b/Apollo.xcodeproj/project.pbxproj index c521db2977..0669e49f44 100644 --- a/Apollo.xcodeproj/project.pbxproj +++ b/Apollo.xcodeproj/project.pbxproj @@ -266,6 +266,7 @@ 90690D2422433C8000FC2E54 /* Apollo-Target-PerformanceTests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Apollo-Target-PerformanceTests.xcconfig"; sourceTree = ""; }; 90690D2522433CAF00FC2E54 /* Apollo-Target-TestSupport.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Apollo-Target-TestSupport.xcconfig"; sourceTree = ""; }; 9B708AAC2305884500604A11 /* ApolloClientProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApolloClientProtocol.swift; sourceTree = ""; }; + 9B74BCBE2333F4ED00508F84 /* run-bundled-codegen.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; name = "run-bundled-codegen.sh"; path = "scripts/run-bundled-codegen.sh"; sourceTree = SOURCE_ROOT; }; 9B78C71B2326E859000C8C32 /* ErrorGenerationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorGenerationTests.swift; sourceTree = ""; }; 9B8D864E22E7A846001F6D50 /* RepoURL.graphql */ = {isa = PBXFileReference; lastKnownFileType = text; path = RepoURL.graphql; sourceTree = ""; }; 9B95EDBF22CAA0AF00702BB2 /* GETTransformerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GETTransformerTests.swift; sourceTree = ""; }; @@ -780,6 +781,7 @@ children = ( 9FC750471D2A532C00458D91 /* Apollo.h */, 9FC750491D2A532C00458D91 /* Info.plist */, + 9B74BCBE2333F4ED00508F84 /* run-bundled-codegen.sh */, 9FE3F3971DADBD870072078F /* check-and-run-apollo-cli.sh */, 9F2A74DA2137C21500E63C85 /* check-and-run-apollo-codegen.sh */, ); @@ -1141,7 +1143,8 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "# Do some magic so we can make sure `FRAMEWORK_SEARCH_PATHS` works correctly when there's a space in the scheme or the folder name.\nQUOTED_FRAMEWORK_SEARCH_PATHS=\\\"$(echo $FRAMEWORK_SEARCH_PATHS | tr -d '\"' | sed -e 's/ \\//\" \"\\//g')\\\"\n\n# Get the first result searching for the framework\nAPOLLO_FRAMEWORK_PATH=\"$(eval find ${QUOTED_FRAMEWORK_SEARCH_PATHS} -name \"Apollo.framework\" -maxdepth 1 -print | head -n 1)\"\n\nif [ -z \"${APOLLO_FRAMEWORK_PATH}\" ]; then\n echo \"error: Couldn't find Apollo.framework in FRAMEWORK_SEARCH_PATHS; make sure to add the framework to your project.\"\n exit 1\nfi\n\ncd ${SRCROOT}/Tests/StarWarsAPI\nif [[ $SDK_NAME == *\"macos\"* ]]; then\n # Run the mac script\n\"${APOLLO_FRAMEWORK_PATH}\"/Versions/Current/Resources/check-and-run-apollo-cli.sh codegen:generate --target=swift --localSchemaFile=\"schema.json\" --includes=./**/*.graphql --mergeInFieldsFromFragmentSpreads API.swift\nelse\n # run the non-mac script\n\"${APOLLO_FRAMEWORK_PATH}\"/check-and-run-apollo-cli.sh codegen:generate --target=swift --localSchemaFile=\"schema.json\" --includes=./**/*.graphql --mergeInFieldsFromFragmentSpreads API.swift\nfi\n"; + shellScript = "SCRIPT_PATH=\"${SRCROOT}/scripts/run-bundled-codegen.sh\"\n\ncd \"${SRCROOT}/Tests/StarWarsAPI\"\n\n\"${SCRIPT_PATH}\" codegen:generate --target=swift --localSchemaFile=\"schema.json\" --includes=./**/*.graphql --mergeInFieldsFromFragmentSpreads API.swift\n"; + showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ diff --git a/Tests/StarWarsAPI/API.swift b/Tests/StarWarsAPI/API.swift index a11c125e29..9832101ebf 100644 --- a/Tests/StarWarsAPI/API.swift +++ b/Tests/StarWarsAPI/API.swift @@ -72,7 +72,7 @@ public struct ReviewInput: GraphQLMapConvertible { /// Comment about the movie, optional public var commentary: Swift.Optional { get { - return graphQLMap["commentary"] as? Swift.Optional ?? .none + return graphQLMap["commentary"] as? Swift.Optional ?? Swift.Optional.none } set { graphQLMap.updateValue(newValue, forKey: "commentary") @@ -82,7 +82,7 @@ public struct ReviewInput: GraphQLMapConvertible { /// Favorite color, optional public var favoriteColor: Swift.Optional { get { - return graphQLMap["favorite_color"] as? Swift.Optional ?? .none + return graphQLMap["favorite_color"] as? Swift.Optional ?? Swift.Optional.none } set { graphQLMap.updateValue(newValue, forKey: "favorite_color") diff --git a/docs/source/installation.md b/docs/source/installation.md index abd711db47..db3dbfe2f5 100644 --- a/docs/source/installation.md +++ b/docs/source/installation.md @@ -16,9 +16,29 @@ Follow along with these steps (described in detail below) to use Apollo iOS in y ## Installing the Apollo framework -You can install `Apollo.framework` into your project using CocoaPods, Carthage, or by manually integrating it with Xcode. +You can install `Apollo.framework` into your project using [Swift Package Manager](#swift-package-manager-installation), [CocoaPods](#cocoapods-installation), [Carthage](#carthage-installation), or by [manually integrating it with Xcode](#manual-integration). -### CocoaPods +### Swift Package Manager Installation + +> **NOTE**: These instructions are intended for usage on Xcode 11 and higher. Xcode 11 is the first version of Xcode that integrates Swift Package manager and makes it _way_ easier to use than it was at the command line. If you are using older versions of Xcode, we recommend using [CocoaPods](#cocoapods-installation) + +1. Go to **File > Swift Packages > Add Package Dependency... ** + + ![add a dependency](screenshot/spm_packages_add_dependency.png) + +1. Paste the URL to the Apollo iOS repo on GitHub into the search bar, then hit the **Next** button: + + ![paste in the url](screenshot/spm_paste_url.png) + +1. Select what version you want to use, then hit next. Xcode will automatically suggest the current version `Up to Next Major`, we **strongly** suggest that while the iOS SDK is on a `0.x.x` version scheme, you select `Up To Next Minor` instead, as we will still be releasing breaking changes on minor versions: + + ![select a version](screenshot/spm_select_version.png) + +1. Select which packages you want to use. If you're just getting started, try selecting just the main `Apollo` library first - you can always come back and add the other packages later if you need them. Then hit finish. + + ![select the packages you want to use](screenshot/spm_select_package.png) + +### CocoaPods Installation 1. Because Apollo iOS has been written using Swift 5, you need to use version `1.7.0` or higher. You can install CocoaPods using: @@ -34,7 +54,7 @@ You can install `Apollo.framework` into your project using CocoaPods, Carthage, 1. Use the `.xcworkspace` file generated by CocoaPods to work on your project. -### Carthage +### Carthage Installation Since Carthage [does not allow choosing which schemes in a repo to build](https://github.com/Carthage/Carthage/issues/1874), we've moved our dependencies to a [`Cartfile.private`](https://github.com/apollographql/apollo-ios/blob/master/Cartfile.private) file so that those dependencies are not forced on people using only the `Apollo` framework and not either of our optional frameworks, `ApolloSQLite` or `ApolloWebSocket`. @@ -66,7 +86,7 @@ This makes setup a hair more complicated if you *are* using those, but is a big This script works around an [App Store submission bug](http://www.openradar.me/radar?id=6409498411401216) triggered by universal binaries and ensures that necessary bitcode-related files and dSYMs are copied when archiving. -### Manual integration +### Manual Integration You can also manually clone the [`apollo-ios` repository](https://github.com/apollostack/apollo-ios), drag `Apollo.xcodeproj` into your project or workspace, add a dependency on `Apollo.framework` to your target. @@ -123,35 +143,28 @@ If you have the Xcode add-ons installed, you can use the Xcode companion view to ## Adding a code generation build step -In order to invoke `apollo` as part of the Xcode build process, create a build step that runs before "Compile Sources" to invoke `apollo` through the `check-and-run-apollo-cli.sh` wrapper script. +Code generation uses your `.graphql` files to generate API code that will help you send queries, subscriptions, and mutations, as well as parse and cache responses. To run code generation as part of the Xcode build process, you need to create a build step that runs before "Compile Sources" to invoke a wrapper script. -The main reason for calling the wrapper is to check whether the version of `apollo` installed on your system is compatible with the framework version installed in your project, and to warn you if it isn't. Without this check, you could end up generating code that is incompatible with the runtime code contained in the framework. +The wrapper will call through to the included binaries and files that constitute the `apollo` command-line interface. This ensures that you can use our tooling without having to worry about NPM Version Hell™, and that the version of the framework you're using is compatible with the version of the codegen you're using. -The location of this wrapper script is slightly different based on how you've integrated Apollo into you project, but the first steps are the same everywhere: +The location of this wrapper script is slightly different based on how you've integrated Apollo into your project, but the first steps are the same everywhere: 1. On your application target's **Build Phases** settings tab, click the **+** icon and choose **New Run Script Phase**. 2. In the created Run Script, change its name to **Generate Apollo GraphQL API** 3. Drag this new run script just above **Compile Sources** in your list of **Build Phases** so that it executes before your code is compiled. -4. Add the appropriate contents to the run script from the options below. +4. Add the contents of the appropriate run script for the package manager you're using from this list: -### If you ARE integrating Apollo using CocoaPods + - [Swift Package Manager](#swift-package-manager-run-script) + - [CocoaPods](#cocoapods-run-script) + - [Carthage](#carthage-run-script) + - [Manual Integration](#manual-integration-run-script) -Our CocoaPods install includes the code-generation script as a file which will not be added to the framework. Since this is always installed in a consistent place, you can use the same path to it. Add the following to the Run Script: +### Swift Package Manager Run Script -```sh -SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts" -cd "${SRCROOT}/${TARGET_NAME}" -"${SCRIPT_PATH}"/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift -``` - -### If you are integrating Apollo using SPM + Xcode 11 [BETA] - -> NOTE: These instructions are as of Xcode 11, beta 4. Please file an issue if anything has changed in newer betas or in the final release! - -If you're using Xcode 11, SPM will check out the appropriate build script along with the rest of the files. Add the following to your Run Script build phase: +If you're using Xcode 11 or higher, SPM will check out the appropriate build script along with the rest of the files when it checks out the repo. Add the following to your Run Script build phase: ```sh -# Go to the build root and go back up to where SPM keeps the apollo iOS framework checked out. +# Go to the build root and go back up to where SPM keeps the Apollo iOS repo checked out. cd "${BUILD_ROOT}" cd "../../SourcePackages/checkouts/apollo-ios/scripts" @@ -163,63 +176,54 @@ if [ -z "${APOLLO_SCRIPT_PATH}" ]; then fi cd "${SRCROOT}/${TARGET_NAME}" -"${APOLLO_SCRIPT_PATH}"/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift +"${APOLLO_SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift ``` > NOTE: If you try to use this with command line SPM, when you regenerate your `xcodeproj` this build script will get wiped out. We strongly recommend using Xcode 11's built-in SPM handling rather than the command line because of this. -### If you're NOT integrating Apollo using CocoaPods - -In this case, the `check-and-run-apollo-cli.sh` file is bundled into the framework. The procedures to call it are slightly different based on whether you're using an iOS or macOS target because of the way the frameworks are compiled. +### CocoaPods Run Script -📱 For an **iOS** target or a **Cocoa Touch Framework**, add the following to your Run Script build phase: +Our CocoaPods install includes the code-generation scripts and binaries of the `apollo` CLI client as files which will not be added to the framework, but which you can still call from a Run Script Build Phase. Add the following to the Run Script: ```sh -# Do some magic so we can make sure `FRAMEWORK_SEARCH_PATHS` works correctly when there's a space in the scheme or the folder name. -QUOTED_FRAMEWORK_SEARCH_PATHS=\"$(echo $FRAMEWORK_SEARCH_PATHS | tr -d '"' | sed -e 's/ \//" "\//g')\" +SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts" +cd "${SRCROOT}/${TARGET_NAME}" +"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift +``` -# Get the first result searching for the framework -APOLLO_FRAMEWORK_PATH="$(eval find ${QUOTED_FRAMEWORK_SEARCH_PATHS} -name "Apollo.framework" -maxdepth 1 -print | head -n 1)" +### Carthage Run Script -if [ -z "${APOLLO_FRAMEWORK_PATH}" ]; then - echo "error: Couldn't find Apollo.framework in FRAMEWORK_SEARCH_PATHS; make sure to add the framework to your project." - exit 1 -fi +In the never-ending battle of what's going to be more painful when it comes to dependency management, we've decided to make working with Carthage a bit more of a pain in order to make working with NPM way less of a pain. -cd "${SRCROOT}/${TARGET_NAME}" -"${APOLLO_FRAMEWORK_PATH}"/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift -``` +The scripts and binaries which you need to generate code will be included in the `Carthage/Checkouts` folder. If this folder is not checked into version control, all developers on a team (and your CI machine) will need to run `carthage checkout` when changes are made to the version to ensure they have the correct underlying binaries and scripts. -💻 For a **macOS** or a **Cocoa Framework** target, add the following to your Run Script build phase: +Once everyone's on the same page about that, you should be able to use this build script: ```sh -# Do some magic so we can make sure `FRAMEWORK_SEARCH_PATHS` works correctly when there's a space in the scheme or the folder name. -QUOTED_FRAMEWORK_SEARCH_PATHS=\"$(echo $FRAMEWORK_SEARCH_PATHS | tr -d '"' | sed -e 's/ \//" "\//g')\" +SCRIPT_PATH="${SRCROOT}/Carthage/Checkouts/apollo-ios/scripts" +cd "${SRCROOT}/${TARGET_NAME}" +"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift +``` -# Get the first result searching for the framework -APOLLO_FRAMEWORK_PATH="$(eval find ${QUOTED_FRAMEWORK_SEARCH_PATHS} -name "Apollo.framework" -maxdepth 1 -print | head -n 1)" +### Manual Integration Run Script -if [ -z "${APOLLO_FRAMEWORK_PATH}" ]; then - echo "error: Couldn't find Apollo.framework in FRAMEWORK_SEARCH_PATHS; make sure to add the framework to your project." - exit 1 -fi +You'll need to find the place where you've downloaded the Apollo iOS SDK, and manually set the `SCRIPT_PATH` to that folder. Usually this works best if it's related to `SRCROOT` so it's always the same +Replace `__YOUR_PATH_TO_THE_SCRIPT_FOLDER__` with (you guessed it) your path to the script folder in this script: + +```sh +SCRIPT_PATH=__YOUR_PATH_TO_THE_SCRIPT_FOLDER__ cd "${SRCROOT}/${TARGET_NAME}" -"${APOLLO_FRAMEWORK_PATH}"/Versions/Current/Resources/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift +"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift ``` + ## Build your target At this point, you can try building your target in Xcode. This will verify that the `schema.json` file can be found by the `apollo` script created above, and run the codegen. ### Troubleshooting -If you've installed `apollo` globally with NPM and the script still seems to be having trouble finding it, add the following to the beginning of your Run Script Build Phase: - -```bash -source ~/.bash_profile -``` - If you get this error: > Cannot find GraphQL schema file [...] @@ -230,13 +234,7 @@ If you get this error: > No operations or fragments found to generate code for. -If you don't have any `.graphql` files in your build tree, and you need to create at least `.graphql` file with a valid query. - -If you get this error: - -> Ensure that there is only one instance of "graphql" in the node_modules directory. If different versions of "graphql" are the dependencies of other relied on modules, use "resolutions" to ensure only one version is installed. - -Delete the `node_modules` folder in your source root and rebuild. +If you don't have any `.graphql` files in your build tree, and you need to create at least `.graphql` file with a valid query. If you need to validate the structure of your query, please use [the GraphQL Formatter tool](http://toolbox.sangria-graphql.org/format). ## Adding the generated API file to your target diff --git a/docs/source/screenshot/spm_packages_add_dependency.png b/docs/source/screenshot/spm_packages_add_dependency.png new file mode 100644 index 0000000000..1612cf7a93 Binary files /dev/null and b/docs/source/screenshot/spm_packages_add_dependency.png differ diff --git a/docs/source/screenshot/spm_packages_setting.png b/docs/source/screenshot/spm_packages_setting.png new file mode 100644 index 0000000000..835082fd96 Binary files /dev/null and b/docs/source/screenshot/spm_packages_setting.png differ diff --git a/docs/source/screenshot/spm_paste_url.png b/docs/source/screenshot/spm_paste_url.png new file mode 100644 index 0000000000..60934a8b56 Binary files /dev/null and b/docs/source/screenshot/spm_paste_url.png differ diff --git a/docs/source/screenshot/spm_select_package.png b/docs/source/screenshot/spm_select_package.png new file mode 100644 index 0000000000..b5dbd094af Binary files /dev/null and b/docs/source/screenshot/spm_select_package.png differ diff --git a/docs/source/screenshot/spm_select_version.png b/docs/source/screenshot/spm_select_version.png new file mode 100644 index 0000000000..1bb9a543c9 Binary files /dev/null and b/docs/source/screenshot/spm_select_version.png differ diff --git a/docs/source/screenshot/spm_version_change.png b/docs/source/screenshot/spm_version_change.png new file mode 100644 index 0000000000..fc293a9f36 Binary files /dev/null and b/docs/source/screenshot/spm_version_change.png differ diff --git a/scripts/apollo.tar.gz b/scripts/apollo.tar.gz new file mode 100644 index 0000000000..bf5b0d0968 Binary files /dev/null and b/scripts/apollo.tar.gz differ diff --git a/scripts/check-and-run-apollo-cli.sh b/scripts/check-and-run-apollo-cli.sh index c195d5f1b2..754c310d47 100755 --- a/scripts/check-and-run-apollo-cli.sh +++ b/scripts/check-and-run-apollo-cli.sh @@ -1,3 +1,5 @@ +echo "warning: The check-and-run-apollo-cli.sh script is deprecated and will be removed. Please see https://www.apollographql.com/docs/ios/installation/#adding-a-code-generation-build-step for updated build instructions which use a bundled version of the Apollo CLI." + # Only major and minor version should be specified here REQUIRED_APOLLO_CLI_VERSION=2.17 # Specify fully qualified version here. Ideally this should be a LTS version. diff --git a/scripts/run-bundled-codegen.sh b/scripts/run-bundled-codegen.sh new file mode 100755 index 0000000000..0f85cabcdf --- /dev/null +++ b/scripts/run-bundled-codegen.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash + +# Exit on all errors, undeclared variables and pipefailures. +set -euo pipefail + +# Get the path to the script directory +SCRIPT_DIR="$(dirname "$0")" + +# Get the SHASUM of the tarball +ZIP_FILE="${SCRIPT_DIR}/apollo.tar.gz" +SHASUM="$(/usr/bin/shasum -a 256 "${ZIP_FILE}")" +SHASUM_FILE="${SCRIPT_DIR}/apollo/.shasum" +APOLLO_DIR="${SCRIPT_DIR}"/apollo + +# Helper functions +remove_existing_apollo() { + rm -r "${APOLLO_DIR}" +} + +extract_cli() { + tar xzf "${SCRIPT_DIR}"/apollo.tar.gz -C "${SCRIPT_DIR}" + echo "${SHASUM}" | tee "${SHASUM_FILE}" +} + +validate_codegen_and_extract_if_needed() { + # Make sure the SHASUM matches the release for this version + EXPECTED_SHASUM="13febaa462e56679099d81502d530e16c3ddf1c6c2db06abe3822c0ef79fb9d2 ${ZIP_FILE}" + + if [ "${SHASUM}" == "${EXPECTED_SHASUM}" ]; then + echo "Correct version of the CLI tarball is included, checking if it's already been extracted..." + else + echo "Error: The SHASUM of this zip file does not match the official released version from Apollo! This may present security issues. Terminating code generation." >&2 + exit 1 + fi + + # Check if the SHASUM file has already been written for this version + if [ -f "${SHASUM_FILE}" ]; then + # The file exists, let's see if it's the same SHASUM + FILE_CONTENTS="$(cat "${SHASUM_FILE}")" + if [ "${FILE_CONTENTS}" == "${SHASUM}" ]; then + echo "Current verson of CLI is already extracted!" + else + echo "Extracting updated version of the Apollo CLI. This may take a minute..." + remove_existing_apollo + extract_cli + fi + else + # The file doesn't exist, unzip the CLI + echo "Extracting the Apollo CLI. This may take a minute..." + extract_cli + fi +} + +# Make sure we're using an up-to-date and valid version of the Apollo CLI +validate_codegen_and_extract_if_needed + +# Use the bundled executable of the Apollo CLI to generate code +APOLLO_CLI="${SCRIPT_DIR}/apollo/bin/run" + +# Print version +echo "Apollo CLI Information: $("${APOLLO_CLI}" --version)" + +# Print commands before executing them (useful for troubleshooting) +set -x +"$APOLLO_CLI" "$@"