Package.swift file at the root of a Swift Package Manager (SPM) package allows you specify the dependencies of the package.
If your dependency is a public package hosted somewhere like GitHub itâs easy to add that to your
Package.swift. For example:
dependencies: [ .package(url: "https://github.com/user/public-repo.git", from: "1.0.0") ]
But what if you want to depend on a private repository?
One option is to specify your GitHub credentials directly in the
dependencies: [ .package(url: "https://user:firstname.lastname@example.org/user/private-repo.git", from: "1.0.0") ]
Obviously this has a number of problems. It ties your
Package.swift to a specific set of credentials, and exposes your GitHub password in plain text.
An alternative is to use a GitHub personal access token (OAuth2) with
dependencies: [ .package(url: "https://<token>:email@example.com/user/private-repo.git", from: "1.0.0") ]
This is slightly better as the tokenâs scope is limited (in comparison to a full set of GitHub credentials), however the token is still effectively a password you are exposing in the packageâs manifest. The token also has access to all of your private repositories, not just one.
A much better solution is to use a GitHub Deploy Key. This is an SSH key which gives access to a single GitHub repository, and can be stored outside the
To use SSH, the dependency URL in your
Package.swift needs to use SSH instead of HTTPS:
dependencies: [ .package(url: "firstname.lastname@example.org:user/private-repo.git", from: "1.0.0") ]
Now, create aÂ
.ssh directory in the root of your SPM package and change into it:
$ mkdir .ssh $ cd .ssh
Next, generate a new SSH key by running
ssh-keygen with the following options:
$ ssh-keygen -b 4096 -t rsa -N "" -f key Generating public/private rsa key pair. Your identification has been saved in key. Your public key has been saved in key.pub.
This generates a 4096-bit RSA key with a blank passphrase and saves it to disk. You now have two files in yourÂ
key (the private key) and
key.pub (the public key).
Still in theÂ
.ssh directory, create a file named
config with this content:
Host github.com HostName github.com User git IdentityFile ./.ssh/key
Now, on GitHub, navigate to the Settings of your private repository, click on âDeploy Keysâ in the sidebar, then click âAdd deploy keyâ. Give your key a name then paste in the contents of the
key.pub public key file. Click âAdd keyâ.
Now when you run
swift build from the root of your package, SPM will use your SSH key to authenticate with GitHub and access the private repository.
If you are deploying your Swift application to a Cloud Foundry PaaS such as IBM Cloud, the buildpack will automatically detect yourÂ
.ssh directory at deploy time and use the SSH key when building your application. Sweet!
||Join the discussion on Slack||Learn more at kitura.io||Star Kitura on GitHub|