Home IOS Development DocC Tutorial for Swift: Automating Publishing With GitHub Actions

DocC Tutorial for Swift: Automating Publishing With GitHub Actions

0
DocC Tutorial for Swift: Automating Publishing With GitHub Actions

[ad_1]

Within the software program improvement routine, it’s frequent to carry out repetitive duties manually. However this comes with a worth: It’s each tedious and error-prone. Fortuitously, the trade has developed options that handle the necessity to automate the repetitive processes a developer or a crew should carry out.

In a earlier tutorial, Mina H. Gerges walked by way of utilizing DocC and Xcode to generate documentation for an app and a Swift package deal after which export them within the DocC archive format.

On this follow-up tutorial, you’ll learn to automate exporting a DocC archive file utilizing DocC on GitHub Actions after which publish it on the web utilizing GitHub Pages as a static web site host.

Alongside the way in which, you’ll be taught:

  • The best way to generate the documentation within the DocC utilizing Xcode and the command line.
  • The best way to configure a GitHub repo to host the generated documentation.
  • The best way to arrange GitHub Actions to regenerate and republish the documentation whenever you push adjustments to the repo.
Observe: This tutorial assumes you’ve got a primary notion of how Git and GitHub work. To be taught extra about it, try Open-Supply Collaboration Utilizing Git and GitHub.

You’ll construct documentation for a package deal that requires SwiftUI and the iOS SDK. For that motive, this tutorial makes use of DocC integration inside Xcode, which requires a Mac host. If you happen to’re keen to doc a pure Swift package deal that may be constructed on Linux, you may use the Swift-DocC plugin instantly, as defined on this web page. In addition to that distinction, you’ll be able to nonetheless comply with alongside to grasp how GitHub Actions works.

Getting Began

Begin by clicking Obtain supplies on the prime or backside of this tutorial. Open GivenWithLove.xcworkspace within the Starter listing in Xcode.

You’ll discover the workspace incorporates the app in addition to a Swift package deal. For each, Xcode can construct the documentation. Whereas this tutorial is about calling DocC through command line, you should use the Xcode UI to construct the documentation. To take action, choose any simulator as a run vacation spot slightly than a tool or Any iOS Gadget. Then, open the Product menu, and choose Construct Documentation.

Xcode allows building the documentation. Click the Product menu, then Build Documentation.

After just a few seconds, Xcode builds the documentation after which mechanically opens it within the Developer Documentation window.

On this tutorial, you’ll learn to execute this similar Motion from the command line, export it to HTML and host it utilizing GitHub Pages — all powered by GitHub Actions. However earlier than beginning and getting your arms on the keyboard, right here’s a fast evaluation of what CI/CD and GitHub Actions imply.

Understanding CI/CD and GitHub Actions

If you happen to work with cellular or net improvement, there’s an excellent likelihood you’re aware of the phrases steady integration (CI), steady supply (CD) and GitHub Actions. In the event that they’re new to you, no worries: You’re in the best place!

What Is CI/CD?

When including new options or fixing bugs, you want to take a look at your new code and confirm you didn’t break the rest. Otherwise you may work on an SDK and have to publish the up to date documentation. However doing it manually — many times — is way from ideally suited. To unravel this challenge, and to scale back human error, an excellent observe is automating these duties.

Steady integration is the automation of constructing and testing code at any time when the model management system, resembling Git, detects new adjustments. Normally, utilizing webhooks, the Git distant repository updates the CI system in regards to the adjustments. For instance, when the principle department has a brand new commit, when somebody creates a pull request or when a brand new tag is offered, it updates the CI, which, in flip, runs particular workflows relying on the set off.

One other time period that often seems alongside CI is CD, which stands for “steady supply”. In addition to compiling and operating exams on the brand new code, builders typically wish to preview their adjustments with out performing handbook operations. A CD system (no, not these previous sound methods from the ’90s) addresses this want by deploying a preview web site or a beta app, and even totally releasing an app or an internet site.

Git operation update the CI, which tests or builds the code

On the whole, CI/CD runs on a distant, hosted pc, with the target of offloading time and sources from a developer’s machine, along with the round the clock availability.

Meet GitHub Actions

Though Git and CI/CD aren’t interchangeable ideas, they’re basically intertwined. By definition, CI/CD should have entry to the supply code and be alert for the occasions talked about above. Due to the pure relationship between these instruments, in 2018, GitHub launched its personal workflow automation instrument. By offering each Git and CI/CD, GitHub can centralize them in a single place, permitting for a sooner, seamless developer expertise.

A repository on GitHub may include a number of workflows, every with a unique aim. As an example, one workflow runs exams whereas one other builds and uploads a brand new app model. They run based mostly on triggered occasions: The exams’ workflow can run when there’s a brand new pull request, and the deploy workflow can begin as soon as a brand new Git tag is pushed. The workflow itself incorporates one or a number of jobs, which in flip encompass a number of steps.

A step could be a common terminal command, resembling operating Swift, NodeJS or some other CLI instruments and binaries. However to make its CI much more highly effective, GitHub permits builders to create their very own constructing blocks and share them with the open-source group. These constructing blocks are known as actions, and your workflows can use these steps moreover operating one-off script instructions. Right here’s the place GitHub’s platform makes a distinction, and the GitHub Market web page allows you to seek for actions that may suit your wants.

Runners are one other necessary part of GitHub Actions. A runner is a server hosted by GitHub that executes a job of a workflow. Upon execution of a job, a recent, clear digital machine is created, operating the platform of your alternative: Linux, Home windows or macOS.

Basic components of GitHub Actions

The Workflow YAML File

GitHub Actions permits a number of workflows per repository, and every workflow describes its jobs and their steps utilizing a YAML file. If you happen to aren’t aware of the syntax, YAML is a knowledge serialization language broadly adopted within the trade, principally for describing configuration recordsdata. Right here’s a brief instance of the way it works:


# Key-value pairs are separated by a colon and an area
identify: Jane Appleseed
age: 30
metropolis: Cupertino

# Maps/Dictionaries use indentation to indicate nested key-value pairs
handle:
  avenue: 19400 Homestead Highway
  metropolis: Cupertino
  state: CA
  zip: 95014

# Arrays are denoted by a hyphen and an area, and might include any sort of information, together with nested dictionaries or arrays
fruits:
  - apple
  - orange
  - banana

As some individuals discover the syntax complicated, you’ll be able to go to Be taught YAML in Y minutes if you wish to be taught extra or have additional doubts. On-line linter instruments, resembling YAML Lint, are additionally helpful when validating a YAML file.

One should place all workflow recordsdata within the .github/workflows listing of a repository. A later part will instruct you on the best way to configure a workflow file for this tutorial’s function, however listed below are a number of the most necessary and frequent properties:

  • identify: The identify GitHub shows for actions that ran a workflow underneath the “Actions” tab. It’s elective, defaulting to the workflow file identify.
  • on: A listing of occasions that set off a workflow, resembling pushes, new pull requests, webhooks and plenty of extra. You possibly can see the complete checklist of occasions on this hyperlink.
  • jobs: A workflow consists of a number of jobs. Though they run in parallel, a job can have a dependency on one other job, which means it waits for an additional’s completion earlier than beginning.
  • runs-on: Each job in a workflow can run in a unique runner. The job should declare which working system and machine to run on. A few of the choices are macos-latest, macos-13, ubuntu-latest, ubuntu-18.04 and some other runner picture current on this checklist.

The total checklist of choices and parameters is offered within the Workflow syntax for GitHub Actions web page.

Constructing the Documentation Regionally

Earlier than transferring straight to GitHub Actions, you must confirm which you can construct the documentation domestically. To attain that — and to arrange the following steps of the automation — you’ll create a bash script to consolidate the instructions.

Creating the Script

First, open Terminal within the root listing of the pattern mission to create the script file. Enter the next command:


contact build-docc.sh

This creates a file named build-docc.sh. Earlier than enhancing it, make the script executable by including the suitable permission to the file so you’ll be able to run it later:


chmod +x build-docc.sh

Now, open it along with your textual content editor of alternative, and add the next command:


##!/bin/sh

xcrun xcodebuild docbuild 
    -scheme GivenWithLove 
    -destination 'generic/platform=iOS Simulator' 
    -derivedDataPath "$PWD/.derivedData"

Though it’s unfold throughout 4 traces, this can be a single command. Right here’s what it does:

  1. xcrun is a instrument that enables interplay with Xcode through command line, and xcodebuild is the a part of it accountable for constructing Xcode initiatives. docbuild is the subcommand that builds the documentation for a given goal.
  2. Select the scheme you wish to construct documentation for. On this case, it’s the GivenWithLove app.
  3. Each the app and package deal have been constructed for iOS and import SwiftUI, so set the vacation spot to iOS. Some xcodebuild actions don’t require a selected gadget or simulator to run on, so prefix the vacation spot with generic/. And since you don’t wish to take care of code signing, select iOS Simulator as an alternative of an precise gadget.
  4. By default, xcodebuild generates its merchandise and locations them within the default derived knowledge folder. Since you’ll want to search out the documentation it generates, use a customized derived knowledge location, with a identified path, for straightforward entry.

Operating the Script Regionally

Now, it’s time to make use of the script and generate the documentation domestically. Again in Terminal, run the next command:


./build-docc.sh

After just a few moments, the command ought to succeed. As soon as the xcodebuild output ends its explosion of characters, you’re able to discover the generated documentation.

To search out the DocC archives, open the .derivedData folder. As a result of it’s a hidden folder, you may not see it instantly in Finder. To show hidden recordsdata and directories, press Command-Shift-.. As soon as you discover it, open it and go to the Construct folder, adopted by the Merchandise and the Debug-iphonesimulator directories. There, you’ll discover the GivenWithLove.doccarchive file. If you happen to can’t discover the hidden folder or wish to leap proper into the ultimate listing, run the next command:


open .derivedData/Construct/Merchandise/Debug-iphonesimulator

That is what you’ll see in that folder:

The fresh Docc archive

Double-click GivenWithLove.doccarchive, and Xcode will open the Developer Documentation window once more. Discover how Xcode now shows it underneath the Imported Documentation part, as xcrun constructed it:

Xcode displaying the documentation created via command line

Congrats! You simply generated your package deal’s documentation utterly through Terminal instructions — with out interacting with the Xcode UI. Within the upcoming sections, you’ll learn to generate the identical recordsdata on GitHub Actions, rework them right into a website-compatible format and publish them to GitHub Pages.

Changing the Documentation to HTML

Whereas it’s attainable to view the DocC archive on a Mac, it’s nonetheless not the best format for publishing on the net. For that, Apple has added a command to docc that converts a .doccarchive enter right into a listing. This listing will include all the required recordsdata for publishing the documentation as a static web site.

Open the build-docc.sh file, and add the next traces after the prevailing command:


xcrun docc process-archive transform-for-static-hosting 
    "$PWD/.derivedData/Construct/Merchandise/Debug-iphonesimulator/GivenWithLove.doccarchive" 
    --output-path ".docs" 
    --hosting-base-path "" # add your repo identify later

By operating this command, you’ll inform docc the place to search out the enter archive and the place it ought to place the output recordsdata: in a folder named .docs. After creating your repository on GitHub, you’ll have to set the hosting-base-path argument, however you’ll be able to go away it empty for now. Run the script once more to examine the end result:


./build-docc.sh

After this command finishes, navigate to the .docs folder to see its contents:


open .docs

Observe: To view the documentation domestically, you’ll have to run a neighborhood server to host the web site. As operating a neighborhood server isn’t within the scope of this tutorial and likewise isn’t important to it, it’s solely briefly talked about. In case you have Python 3 put in, you’ll be able to run the command python3 -m http.server -d .docs. In case your macOS doesn’t have Python, you’ll be able to set up it with homebrew — brew set up python3 — first. Upon getting the native server operating, the documentation will likely be seen at http://localhost:8000/documentation/givenwithlove/.

Redirecting to the Documentation Web page

If you happen to have been capable of serve the docs domestically, you is perhaps questioning why the basis web page shows an error. It is because DocC organizes the recordsdata for static internet hosting within the following construction:

The documentation in a format that can be statically served on the web

As you’ll be able to see, the givenwithlove listing is situated underneath documentation. To view the documentation of an app or package deal, the handle needs to be within the sample host.com/documentation/your-product-name as an alternative of accessing the basis web page (host.com). Accessing the basis web page leads to an error.

To assist your readers, you’ll be able to change the .docs/index.html file with a redirect, and the browser will lead them on to the right path.

Open the build-docc.sh file once more, and in a brand new line, add the next:


echo '<script>window.location.href += "/documentation/givenwithlove"</script>' > .docs/index.html

This can redirect the basis web page to the documentation. Rerun build-docc.sh, restart your native server, and whenever you go to http://localhost:8000/, you’ll be redirected to the documentation web page.

Now, it’s time to maneuver on and get your arms on GitHub!

Setting Up GitHub Pages

Up to now, you’ve realized the best way to generate the .doccarchive file and convert it right into a format appropriate for static internet hosting. The following step is defining the workflow file for operating the identical script you ran domestically and publishing the content material to GitHub Pages.

GitHub Pages is one other service — you guessed proper, from GitHub — that enables builders to host static web site content material for a private profile or particular initiatives. It even permits customized domains with HTTPS help!

Activating GitHub Pages in Your Repository

Create an empty repository on GitHub for this tutorial. GitHub Pages solely works with personal repos if you happen to’re on the Professional plan. In any other case, when you’ve got a free GitHub account, ensure you create a public repository. To make pushing your commits smoother, don’t embody a Readme or a .gitignore file.

In your browser, open your new repository, and go to the Settings tab. Within the left pane, underneath the Code and automation part, click on Pages. Within the Construct and deployment part, click on the Supply menu, and select GitHub Actions. There are two methods of deploying to GitHub Pages, and though nonetheless in beta, publishing to Pages through Actions is the way in which GitHub recommends (as an alternative of pushing to a selected department).

The GitHub Pages section in the repository settings

The GitHub Pages URL Format

GitHub Pages can host two kinds of pages: private and initiatives. Private pages are supposed to be your “dwelling” on the net, whereas mission pages might be an open-source mission’s showcase.

Whereas private pages should belong to a repository named <username>.github.io, and the web page is accessible at https://username.github.io, mission pages work barely in another way. The repository can have any identify, and customers can discover it at https://username.github.io/<repository-name>.

To take that into consideration, the export command can obtain a base path and regulate the routes accordingly. Open — for the final time as we speak — the construct script at build-docc.sh. Within the second command, the place you see the remark, set your repository identify within the already current, however empty, hosting-base-path argument:


--hosting-base-path "<your-repository-name>"

This makes your documentation conscious of the relative location through which it’s positioned on the web site when DocC transforms the documentation for publishing.

Transferring ahead, it’s time to arrange your workflow.

Configuring GitHub Actions

All of the GitHub Actions configuration you’ll want takes place within the workflow file, so there’s no want to vary the Actions settings. All workflow recordsdata should reside underneath the .github/workflows listing. To create one, run the next command:


mkdir -p .github/workflows

Now, create the YAML file you’ll use to outline your workflow:


contact .github/workflows/docc.yml

Defining the Workflow File

Open the file you simply created along with your textual content editor. Copy the traces under and paste them into this new file. Be sure that your textual content editor retains the area indentation as an alternative of changing them with tabs. YAML depends on the areas and the indentation to validate the content material and its construction.


#1
identify: docc

#2
on:
  push:
    branches: [main]
  workflow_dispatch:

#3
permissions:
  pages: write
  id-token: write
  contents: learn

Right here’s what this file describes to date:

  1. The identify of this workflow.
  2. The occasions that may set off operating this workflow. The push set off will work when new commits are pushed to the principle department. Including workflow_dispatch permits manually triggering the workflow from the GitHub Actions UI.
  3. Set permissions for the GitHub token operating the Motion to permit deployment to GitHub Pages, and browse permissions for testing the repository content material.

A workflow incorporates a number of jobs. The primary stage of the workflow is operating the script you ready above. To configure the job to take action, add the next code:


#1
jobs:
  construct:
    #2
    runs-on: macos-12
    #3
    steps:
      - identify: Checkout Repository
        makes use of: actions/checkout@v3
        with:
          fetch-depth: 0
      #4
      - identify: Run Construct Docs
        run: ./build-docc.sh
      #5
      - identify: Setup Pages
        id: pages
        makes use of: actions/configure-pages@v3
      - identify: Add artifact
        makes use of: actions/upload-pages-artifact@v1
        with:
          path: .docs

It is perhaps so much, however breaking it down piece by piece makes it simpler to grasp:

  1. Declare the roles map, and begin with the construct job.
  2. As a result of the script depends on xcrun and Xcode, you’ll want a macOS runner. When utilizing DocC as a Swift package deal plugin, you should use a Linux machine as an alternative.
  3. A number of steps make up a job. Declare the checklist of steps, and begin by testing the repository taking solely the final commit. Due to this fact, the fetch-depth possibility is ready to 0.
  4. After testing the repository, run the build-docc.sh script.
  5. Use the actions that GitHub gives: one for configuring pages and one other for importing the contents that the script will generate and place underneath .docs. Discover how this is similar listing you set within the final line.

You’re virtually completed! Now, you want to outline a job to deploy what the construct job generated.

Publishing to GitHub Pages through Actions

Nonetheless within the docc.yml file, add the traces under. Take note of the truth that the deploy key ought to have the identical indentation because the construct key from the earlier snippet.


  #1
  deploy:
    #2
    runs-on: ubuntu-latest
    #3
    wants: construct
    #4
    steps:
      - identify: Deploy to GitHub Pages
        id: deployment
        makes use of: actions/deploy-pages@v2 
    setting:
      identify: github-pages
      url: ${{ steps.deployment.outputs.page_url }}

Right here’s what these traces imply:

  1. Outline the deploy job.
  2. As a result of Xcode isn’t obligatory anymore, you’ll be able to select a Linux runner.
  3. The earlier job, construct, created and uploaded the artifacts. So, add a dependency on that job, which means that this one will solely run when the primary has completed.
  4. Declare a single step for this job based mostly on the official actions/deploy-pages Motion. Set the setting variables it requires.

It’s lastly time to check all of it!

Operating the Workflow on GitHub Actions

If you happen to haven’t but created your repository domestically, run:


git init

As this can be a new repository, all of your adjustments are file additions. After staging them, create an preliminary commit. Then, add the GitHub distant. Change your username and the repository identify earlier than operating this command:


git distant add origin https://github.com/<your-username>/<your-repository-name>.git

Create the principle department, and push your adjustments:


git department -M predominant && git push -u origin predominant

After pushing it to GitHub, open your repository web page, and go to the Actions tab. Within the checklist, you’ll see the Motion you simply created, inside just a few moments, within the queued state.

In some circumstances, the Motion may get caught within the queued state. If that’s the case, you’ve already outlined the workflow_dispatch occasion within the workflow, which permits manually triggering the Motion.

A GitHub workflow in the queued state, waiting to be started.

After transferring from the queued to the operating state, click on the workflow run within the checklist to see extra particulars:

A GitHub workflow while it's running

Discover how, within the picture above, there’s a line between the construct and deploy. It represents the dependency of the deploy job on the construct job.

After a couple of minutes, each jobs needs to be full:

A GitHub Action after all jobs completed successfully

As you’ll be able to see, each jobs have inexperienced examine marks, making the run itself a profitable one. Underneath deploy, you’ll see a hyperlink. Clicking it’ll take you to https://<your-username>.github.io/<repository-name>, and the browser will show the documentation you labored so exhausting to publish:

The app documentation is live on GitHub Pages!

The place to Go From Right here?

You possibly can obtain the finished mission recordsdata by clicking Obtain supplies on the prime or backside of the tutorial.

Congratulations on reaching the tip of this tutorial! It included many steps: writing a shell script, making a repository, enabling GitHub Pages on it, defining your workflow file and operating it. If you happen to made it right here, it means you realized and purchased new expertise.

If you happen to already really feel the superpowers of automating your processes, you may wish to develop your data within the CI/CD area, deepen your experience in GitHub Actions, and likewise in applied sciences or providers that host static content material and make its distribution even sooner with content material supply networks (CDNs). Right here’s what you may do subsequent:

  • Wrap your often used steps right into a shareable Motion of your individual.
  • Connect with the online: Automate calling your workflows through webhooks and likewise name exterior webhooks out of your workflow steps.
  • Automate technology of Swift code that compiles on Linux, utilizing the DocC Swift Bundle Supervisor plugin, as an alternative of counting on Xcode and macOS. By doing so, you don’t want to make use of the macOS runners. The Linux runners will likely be sufficient, which is a constructive issue since they eat fewer credit than the macOS ones.
  • Publish your documentation to different providers, resembling Netlify, which gives a CDN on prime of internet hosting.

We hope you loved this tutorial, and when you’ve got any questions or feedback, please be a part of the discussion board dialogue under!

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here