Prefs CLI Tools for Mac Admins

Recently I have been working on some… well… “stuff” that uses custom configuration profiles. Very custom, and since I am testing things, they need to be updated a lot.

The issue with defaults

When you are working with defaults/preferences/settings/property lists on macOS, you will be familiar with the defaults command line tool. But, as useful as defaults can be, it has some downsides.

One of the great advantages of macOS’ preference system is that settings can be provided on multiple levels or domains. In my book “Property Lists, Preferences and Profiles for Apple Administrators, I have identified 19 different levels where settings for a single application can originate.

You will be most familiar with plist files in /Library/Preferences (system), ~/Library/Preferences (user), and managed configuration profiles (managed). When an app or tool requests a setting, the preferences system will merge all those levels together and present only the most relevant value. When the developer uses the system APIs (correctly), they do not have to worry about all the underlying levels, domains and mechanisms very much, but automatically gain support for things like separated system and user level settings files and support for management through configuration profiles.

The macOS defaults command line tool can work with settings on different levels or domains, but will only show the settings from one at a time. By default it only works with the user domain settings stored in ~/Library/Preferences/. When you have settings in multiple levels or from configuration profiles, you may be able to point defaults directly at the files. Or in the case of managed settings from profiles, you have to use a different tool. Either way, you have to determine which setting might override another and which final value might be visible to the app or process.

A new prefs tool

Years back, I had built a python script, called prefs.py, which would not only show the coalesced set of settings but their origin level. When macOS removed Python 2 in macOS 12.3, this tool obviously broke.

While working with preferences and profiles recently, this feature would have been quite useful to debug and verify preferences. I could have adapted the existing tool to work with MacAdmins Python 3, but felt I would learn something from recreating it in Swift. I had already started down that road just a bit for my sample project in this post.

So, you can find the new Swift-based prefs command line tool on GitHub. You can also download a signed and notarized pkg which will install the binary in /usr/local/bin/.

If its most basic form, you run it with a domain or application identifier. It will then list the merged settings for that preference domain, showing the level where the final value came from.

% prefs com.apple.screensaver
moduleDict [host]: {
    moduleName = "Computer Name";
    path = "/System/Library/Frameworks/ScreenSaver.framework/PlugIns/Computer Name.appex";
    type = 0;
}
PrefsVersion [host]: 100
idleTime [host]: 0
lastDelayTime [host]: 1200
tokenRemovalAction [host]: 0
showClock [host]: 0
CleanExit [host]: 1

I find this useful when researching where services and applications store their settings and also to see if a custom configuration profile is set up and applying correctly. There is a bit of documentation in the repo’s ReadMe and you can get a description of the options with prefs --help.

plist2profile

Another tool that would have been useful to my work, but that was also written in python 2 is Tim Sutton’s mcxToProfile. Back in the day, this tool was very useful when transitioning from Workgroup Manager and mcx based management to the new MDM and configuration profile based methods. If you have a long-lived management service, you will probably find some references to mcxToProfile in the custom profiles.

Even after Workgroup Manager and mcx based settings management was retired, Tim’s tool allowed to create a custom configuration profile from a simple property list file. Configuration Profiles require a lot of metadata around the actual settings keys and values, and mcxToProfile was useful in automating that step.

Some management systems, like Jamf Pro, have this feature built in. Many other management systems, however, do not. (Looking at you Jamf School.) But even then creating a custom profile on your admin Mac or as part of an automation, can be useful.

So, you probably guessed it, I also recreated mcxToProfile in Swift. The new tool is called plist2profile and available in the same repo and pkg. I have focused on the features I need right now, so plist2profile is missing several options compared to mcxToProfile. Let me know if this is useful and I might put some more work into it.

That said, I added a new feature. There are two different formats or layouts that configuration profiles can use to provide custom setting. The ‘traditional’ layout goes back all the way to the mcx data format in Workgroup Manager. This is what mcxToProfile would create as well. There is another, flatter format which has less metadata around it. Bob Gendler has a great post about the differences.

From what I can tell, the end effect is the same between the two approaches. plist2profile uses the ‘flatter’, simpler layout by default, but you can make it create the traditional mcx format by adding the --mcx option.

Using it is simple. You just need to give it an identifier and one or more plist files from which it will build a custom configuration profile:

% plist2profile --identifier example.settings com.example.settings.plist

You can find more instructions in the ReadMe and in the commands help with plist2profile --help

Conclusion

As I had anticipated, I learned a lot putting these tools together. Not just about the preferences system, but some new (and old) Swift strategies that will be useful for the actual problems I am trying to solve.

I also learnt more about the ArgumentParser package to parse command line arguments. This is such a useful and powerful package, but their documentation fails in the common way. It describes what you can do, but not why or how. There might be posts about that coming up.

Most of all, these two tools turned out to be useful to my work right now. Hope they will be useful to you!

Build a notarized package with a Swift Package Manager executable

One of the most popular articles on this blog is “Notarize a Command Line Tool with notarytool.” In that post I introduced a workflow for Xcode to build and notarize a custom installer package for a command line tool. This workflow also works with apps and other projects that require a customized installer package building workflow. I use it in many of my own projects.

But Xcode is not the only way to build Swift binaries. Especially for command line tools, you can also use Swift Package Manager. This provides a mostly command line based interface to building and organizing your project, which you might prefer if you want to use an IDE that is not Xcode, or have Swift projects that need to run cross-platform.

I also have an older article on building a command line tool with Swift Package Manager. But then, I did not create an installer package or notarize the resulting binary.

Placing the binary in an installer package file is the best way to distribute a binary as you can control where in the file system the binary is installed. Notarizing the pkg file is necessary when you are distributing a command line tool, since it enables installations without scary dialogs or handling quarantine flags.

Also, some of the behavior of Swift Package Manager (SPM) and Xcode have changed since the previous posts. So, this article will introduce an updated workflow using Swift Package Manager tools and how to sign, package and notarize a command line tool for distribution.

Note on nomenclature: Swift Package Manager projects are called ‘packages.’ On macOS, installer files (with the pkg file extension) are also called ‘packages.’ We will be using SPM to build a notarized installation package (a pkg file) from a Swift package project. This is confusing. There is not much I can do about that other than using ‘installer package’ and ‘Swift package project’ to help distinguish.

Prerequisites

I wrote this article using Xcode 14.3.1 and Swift 5.8.1. It should also work with somewhat older or newer versions of Xcode and Swift, but I have not tested any explicitly.

Since I said earlier that using Swift Package Manager allows us to not use Xcode and maybe even build a cross-platform project, you may be wondering why we need Xcode. While we don’t need Xcode for our project, it is one way of installing all the tools we need, most importantly the swift and notarytool binaries. You get those from Developer Command Line tools, as well. We will also see that we can combine Xcode with the command line Swift Package Manager workflow, which I find a very useful setup.

To submit a binary to Apple’s notarization process you will need a Personal or Enterprise Apple Developer account, and access to the Developer ID Application and Developer ID Installer certificates from that account. A free Apple Developer account does not provide those certificates, but they are necessary for notarization

You can follow the instructions in the Xcode article on how to get the certificates and how to configure notarytool with an application specific password. If you had already done this previously you should be able to re-use all of that here. When you reach the ‘Preparing the Xcode Project’ section in that article, you can stop and continue here. Apple also has some documentation on how to configure notarytool.

The sample code we will be using will only work on macOS as it uses CoreFoundation functions. Installer packages and notarization are features of macOS, too, so this is not really a problem here. You can use this workflow to build macOS specific signed binaries and notarized installation pkg files from a cross-platform Swift package project. This will work as long as you keep in mind that the tools to sign, package and notarize only exist and/or work on macOS.

The sample code

We will build the same simple sample tool as in the last article. The prf command (short for ‘pref’ or ‘preference’) reads a default setting’s effective value using the CFPreferencesCopyAppValue function.

The macOS defaults command will read preferences, but only from the user level, or from a specified file path. This ignores one of the main features of macOS’ preferences system as it will not show if a value is being managed by a different preference level, such as the global domain, a file in /Library/Preferences, or (most importantly for MacAdmins) a configuration profile.

You can learn all about preferences and profiles in my book “Property Lists, Preferences and Profiles for Apple Administrators.”

We will build a really simple command line tool, named prf which shows the effective value of a setting, no matter where the value comes from. You could make this tool far more elaborate, but we will keep it simple, since the code is not the actual topic for this article.

We will also be using the Swift Argument Parser package to parse command line arguments and provide a help message. We could build this simple tool without using Argument Parser, but using an external package module is one of the strengths of using Swift Package Manager.

Create the Swift Package project

With all the preparations done, it is time to create our Swift package. We will do all the work in the shell, so open Terminal or your other favorite terminal app and navigate to the directory where you want to create the project.

> cd ~/Projects

Then create a new directory with the name swift-prf. This will contain all the files from the Swift package project. Change directory into that new directory. All following commands will assume this project directory is the current working directory.

> mkdir swift-prf
> cd swift-prf

Then run the swift tool to setup the template structure for our command line tool or ‘executable.’

> swift package init --type executable 
Creating executable package: swift-prf
Creating Package.swift
Creating .gitignore
Creating Sources/
Creating Sources/main.swift

You can inspect the hierarchy of files that the init tool created in the Finder (open .) or in your preferred editor or IDE.

.gitignore
Package.swift
Sources
    main.swift

`

You can open this package project in Xcode. In older versions of Xcode you had to run a special swift package command to generate the Xcode project, but now, Xcode can open Swift package projects directly. Use xed (the ‘Xcode text editor invocation tool’) to open the current directory in Xcode.

> xed .

There is a pre-filled .gitignore (which will be hidden in Finder and probably your IDE), a Package.swift, and a Sources directory with a single main.swift inside. If you want to use git (or another version control) system, now is the time to initialize with git init.

Build the project with swift build and/or run it with swift run. Not surprisingly, the template prints Hello, world!.

> swift build
Building for debugging...
[3/3] Linking swift-prf
Build complete! (0.92s)
> swift run  
Building for debugging...
Build complete! (0.11s)
Hello, world!

After building, there will also be a .build directory (also hidden in Finder, unless you toggle the visibility of invisible files using shift-command-.) which contains all the interim files. In the debug folder, you can find the swift-prf executable. You can run it directly:

> .build/debug/swift-prf
Hello, world!

You can clean all the generated pieces from the .build directory with swift package clean. This will leave some empty folders behind but remove all the interim and final products. This means the next build is going to take much longer, but this can be helpful after reconfiguring the Package.swift file or when the compiler gets confused.

Sidenote: when you use Xcode to edit your Swift package project, and choose Build or Run from the Xcode interface, then it will build and run in a different location (~/Library/Developer/Xcode/DerivedData/swift-prf-<random-letters>/Build). You need to be aware of this when you alternate between Xcode and the command line.

Configuring the Package

The Package.swift file contains the configuration for a Swift package project. You can see that the executable package template has a single target named swift-prf that builds from the files in Sources.

To change the name of the executable file, change the value of the name: of the .executableTarget to just prf. There is another name: earlier in the file, that sets the name of the entire project, you can leave that being swift-prf. They do not have to match.

Then build the project in the command line and run it directly:

> swift build
Building for debugging...
[3/3] Linking prf
Build complete! (0.51s)
> .build/debug/prf          
Hello, world!

We want to add the Swift Argument Parser package to our project as a dependency, so we can use its functionality in our code. For that, we will have to add a ‘dependency’ to the project and then to the target, as well. Modify the Package.swift file to match this:

// swift-tools-version: 5.8
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
  name: "swift-prf",
  products: [
    .executable(name: "prf", targets: ["prf"]),
  ],
  dependencies: [
    .package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0"),
  ],
  targets: [
    .executableTarget(
      name: "prf",
      dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")],
      path: "Sources")
  ]
)

This means that our project uses the package available at the given URL, and our target is going to use the specific product (or module or framework) named ArgumentParser from that package. Some packages have several products combined out of several targets.

You can find more information on the format of the Package.swift file in this overview, and the full documentation.

The next time you build after this change, it will download the repository, build and link to toward your executable. That might take a while. The next build should be much faster again. Also, a Package.resolved file will appear in the project. This file caches the current versions of the included packages protecting you from unexpected changes when a package repo dependency updates. You can force Swift Package Manager to update the file with swift package update.

Sprinkle some code

Now that we have the Swift package project prepared, we can add the code to actually do something.

First, let’s keep the ‘Hello, world!’ for a moment, but put it in the right struct to use ArgumentParser. Change main.swift to:

import Foundation
import ArgumentParser
@main
struct PRF: ParsableCommand {
  func run() {
    print("Hello, world!")
  }
}

This should build and run fine from the command line with swift build and swift run. However, when you open this now in Xcode, you will see an error: 'main' attribute cannot be used in a module that contains top-level code

This comes from a long-running issue in Swift. In older versions of Swift it appears on the command line, as well. The work-around is easy though. It only seems to appear when the @main designator is the main.swift file. We can rename our main file to PRF.swift.

You may want to close the Xcode project window before you do this because this can confuse Xcode. If you manage to get Xcode into a confused state where the project in Xcode does not match what is on disk any more, quit Xcode and delete the .swiftpm/xcode directory, which is where Xcode keeps its generated files.

> mv Sources/main.swift Sources/PRF.swift

Now the project should build and run the same with the Swift Package Manager tools and in Xcode.

Now we can add the ‘full’ code for our tool. Keep in mind that the goal of this tutorial is not to learn how to write complex swift code for command line tools, but to learn the infrastructure requires to create and distribute them, so this code is intentionally simple and basic.

import Foundation
import ArgumentParser
@main
struct PRF: ParsableCommand {
  static var configuration = CommandConfiguration(
    commandName: "prf",
    abstract: "read effective preference value",
    version: "1.0"
  )
  @Argument(help: "the preference domain, e.g. 'com.apple.dock'")
  var domain: String
  @Argument(help: "the preference key, e.g. 'orientation'")
  var key: String
  func run() {
    let plist = CFPreferencesCopyAppValue(key as CFString, domain as CFString)
    print(plist?.description ?? "<no value>")
  }
}

When you compare that to the code from the last article, there are a few differences. We are using the @main attribute to designate the main entry point for the code (this was added in Swift 5.3) and I have added some help text to the tool and argument declarations.

When you use Swift Argument Parser, you should study the documentation on adding help to [commands](I have added some help text to the tool and argument declarations. ) and flags, arguments and options. (To be honest, you should read the entire documentation, a lot has changed since the last article.)

When you now run the tool:

> swift run  
Building for debugging...
[3/3] Linking prf
Build complete! (0.54s)
Error: Missing expected argument '<domain>'
OVERVIEW: read effective preference value
USAGE: prf <domain> <key>
ARGUMENTS:
  <domain>                the preference domain, e.g. 'com.apple.dock'
  <key>                   the preference key, e.g. 'orientation'
OPTIONS:
  --version               Show the version.
  -h, --help              Show help information.

We get the help text generated by Swift Argument Parser with the extra information we provided in the code.

If you want to provide the arguments to the swift run you have to add the executable name, as well:

> swift run prf com.apple.dock orientation       
Building for debugging...
Build complete! (0.11s)
left

Or you can run the executable directly from the .build/debug directory. (This will not automatically re-build the command like swift run does.

> .build/debug/prf com.apple.dock orientation
left

Since we provided a version in the CommandConfiguration, ArgumentParser automatically generates a --version option:

> .build/debug/prf --version       
1.0

Now that we have a simple but working tool, we can tackle the main part: we will package and notarize the tool for distribution.

Preparing the binary

When you run swift build or swift run it will compile the tool in a form that is optimized for debugging. This is not the form you want to distribute the binary in. Also, we want to compile the release binary as a ‘universal’ binary, which means it will contain the code for both Intel and Apple silicon, no matter which CPU architecture we are building this on.

The command to build a universal release binary is

> swift build --configuration release --arch arm64 --arch x86_64

When that command is finished, you will find the universal binary file in .build/apple/Products/Release/prf. we can check that it contains the Intel (x86_64) and Apple silicon (arm64) with the lipo tool:

> lipo -info .build/apple/Products/Release/prf
Architectures in the fat file: .build/apple/Products/Release/prf are: x86_64 arm64 

For comparison, the debug version of the binary only contains the platform you are currently on:

> lipo -info .build/debug/prf
Non-fat file: .build/debug/prf is architecture: arm64

Apple’s notarization process requires submitted binaries to fulfill a few restrictions. They need a timestamped signature with a valid Developer ID and have the ‘hardened runtime’ enabled.

Xcode will always sign code it generates, but the swift command line tool does not. We will have to sign it ourselves using the codesign tool. You will need the full name of your “Developer ID Application” certificate for this. (Don’t confuse it with the “Developer ID Installer” certificate, which we will need later.)

You can list the available certs with

> security find-identity -p basic -v

and copy the entire name (including the quotes) of your certificate. Then run codesign:

> codesign --sign "Developer ID Application: Your Name (ABCDEFGHJK)" --options runtime  --timestamp .build/apple/Products/Release/prf

You can verify the code signature with

> codesign --display --verbose .build/apple/Products/Release/prf

Build the installation package

Now that we have prepared the binary for distribution, we can wrap it in an package installer file.

To cover all deployment scenarios, we will create a signed ‘product archive.’ You can watch my MacDevOps presentation “The Encyclopedia of Packages” for all the gory details.

First, create a directory that will contain all the files we want put in the pkg. Then we copy the binary there.

> mkdir .build/pkgroot
> cp .build/apple/Products/Release/prf .build/pkgroot/

Then build a component pkg from the pkgroot:

> pkgbuild --root .build/pkgroot --identifier com.scriptingosx.prf --version 1.0 --install-location /usr/local/bin/ prf.pkg

The --identifier uses the common reverse domain notation. This is what the installer system on macOS uses to determine whether an installation is an upgrade, so you really need to pay attention to keep using the same identifier across different versions of the tool. The --version value should change on every update.

The --install-location determines where the contents of the payload (i.e. the contents of the pkgroot directory) get installed to. /usr/local/bin/ is a useful default for macOS, but you can choose other locations here.

Next, we need to wrap the component pkg inside a distribution package.

> productbuild --package prf.pkg --identifier com.scriptingosx.prf --version 1.0 --sign "Developer ID Installer: Your Name (ABCDEFGHJK)" prf-1.0.pkg

It is important that you use the “Developer ID Installer” certificate here. The --identifier and --version are optional with productbuild but this data required for some (admittedly rare) deployment scenarios, and we want to cover them all.

You can inspect the installer pkg file with a package inspection tool such as the amazing Suspicious Package. The package file should as a signed “Product Archive.”

We don’t need the component pkg anymore, and it’s presence might be confusing, so let’s remove it:

> rm prf.pkg

Note: If you want to learn more about building installation packages, check out my book “Packaging for Apple Administrators”

Notarization

We are nearly there, just two more steps.

It is important to notarize pkgs that will be installed by a user, because otherwise they will get a scary warning that Apple can’t verify the pkg for malicious software.

notarytool submits the installer package to Apple’s Notarization process and returns the results. Use the keychain profile name you set up, following the instructions in the previous article or the instructions from the Apple Developer page.

> xcrun notarytool submit prf-1.0.pkg --keychain-profile notary-example.com --wait

This will print a lot of logging, most of which is self-explanatory. The process might stall at the “waiting” step for a while, depending on how busy Apple’s servers are. You should eventually get status: Accepted.

If you got a different status, or if you are curious, you can get more detail about the process, including rejection reasons, with notarytool log. You will need the ‘Submission ID’ from the submission output:

xcrun notarytool log <submission-uuid> --keychain-profile notary-example.com

As the final step, you should ‘staple’ the notarization ticket to the pkg. This means that the (signed) notarization information is attached to the pkg-file, saving a round trip to Apple’s servers to verify the notarization status when a system evaluates the downloaded installer package file.

xcrun stapler staple prf-1.0.pkg
Processing: /Users/armin/Desktop/swift-prf/prf-1.0.pkg
Processing: /Users/armin/Desktop/swift-prf/prf-1.0.pkg
The staple and validate action worked!

And with that, we have a signed and notarized installation pkg file! You can verify this with spctl:

> spctl --assess --verbose -t install prf-1.0.pkg 
prf-1.0.pkg: accepted
source=Notarized Developer ID

Automation

While it is instructive to do this process manually, it is also quite complex and error-prone. If you have been following this blog for any time, you will know that I don’t stop at detailed step-by-step instructions with explanations.

You can find a script to automate all of these steps here. The enclosing repository includes the entire project (all three files) for your reference.

There is a section at the beginning with variables to modify with the information specific to your environment and project, such as your developer ID information and the name of the credential profile for notarytool. Then there are a few variables, such as the product name, and the installation package identifier.

Run the pkgAndNotarize.sh script from the root of the Swift package project directory.

./pkgAndNotarize.sh

The script creates the installer pkg file in the .build directory. The last line of output is the path to the final, signed, notarized and stapled pkg file.

The script mostly follows the process described above, with a few extras. For example, the script determines the version dynamically by running the tool with the --version option. It also uses the modern compression options I described in this post.

If any of the steps in the script fail, you can determine what exactly failed from the output, error message and error code.

(I belief that this could probably be a makefile, but I have no experience with that (yet). I guess I will need to ‘make’ time for this…)

Conclusion

Apple provides developers and MacAdmins with amazing platforms and tools to build all kinds of powerful apps, tools and automations. But then they don’t really document any of the processes or best practices at all. The amount of searching, guesswork, and frustrating trial and error necessary to piece all of this together for a workflow like this one is quite the shocking condemnation of Apple’s documentation.

There are glimmers of hope. The documentation for the notarization process and notarytool are exemplary.

But they only cover one piece of this puzzle. A developer building a tool has to still figure out how to

  • sign all the binaries properly
  • assemble the binaries and resources necessary into an installation package payload
  • how (and when, and when not) to use pre- and postinstall scripts
  • which kind of package installer to build and which tools to use
  • securely manage the Developer ID certificates (this is especially challenging for developer teams)
  • automate this workflow with Xcode or Swift Package Manager or a CI/CD system

MacAdmins often complain about poorly built installer pkgs, and often for good reasons. But to be fair, there are no best practices and little to no documentation for this from Apple. How are developers supposed to know all of this? Most MacAdmins can define what an installer package should do and not do, but wouldn’t be able to explain to a developer how to build such an installer package, let alone integrate that into their build automations. And most developers don’t even know a MacAdmin to ask about this.

Apple requires that developers create signed and notarized archives for software distribution. And I agree wholeheartedly with their motivations and goals here. But when impose requirements for distribution, you have to make the process of creating the installers the correct way easy, or at least well documented, whether you use Xcode or a different tool set, whether you want to distribute a simple self-contained app, a single command line tool, or a complex suite of tools and resources.

Apple has their work cut out to improve this. Official best practices and sample workflows for installer creation and distribution that consider and respect the requirements of MacAdmins for deployment, have been disgracefully lacking for a long time. The more requirements and security Apple piles on to application and tool distribution, the more desperately they need to provide documentation, best practices and guidance.

Until that happens, you have my paltry scripts.

Build a macOS Application to Run a Shell Command with Xcode and SwiftUI – Part 2

A long time ago, I wrote a post on how to build a simple App using SwiftUI that would run a shell command. Amazingly, the tutorial still works!

This is particularly useful for MacAdmins, because we sometimes want to provide a simple UI for some command or script. However, some things have changed since I wrote this tutorial three years. While the code still “works,” there are some things that can be improved. Also, when I wrote the original post, there were some features I didn’t expand upon, because the post was already very long, and, to be honest, back then, I didn’t really know how they worked, myself.

When I re-visited this earlier because of a question in the MacAdmins Slack, I was really surprised that I didn’t need to update code to make it work. That said, there are the matters I didn’t explain last time. Also Swift has changed in some ways. That means it is time for the second part.

You can get the sample code from the first part as a starting point.

Get the output of the command

In the first part, we ran the say command, which doesn’t have a text output. Often times we want to run shell commands to get information from the command’s standard output (or sometimes standard error). To grab the output of commands, we need to prepare the Process object, which means we cannot use the convenience method Process.run() any more.

The say command has an option to change the voice being used. You can list the names of voices available to the say command by running say -v '?' in Terminal. We’d like to get that output and populate a menu with the available voices in our UI.

Note: the output of the say -v '?' command does not show most of the modern voices available in macOS. Most of the voices listed are quite old, funny, and, to be honest, awful. As has been mentioned before, I am using the say command as a convenient example for a shell command. If you want proper speech synthesis in your app, you should not use the say command but the proper speech synthesis API.

We will start out experimenting with code in a macOS Playground in Xcode and later add it to the app from the first part. When you create a new Playground in Xcode (File > New > New Playground), make sure you select ‘macOS’ for the platform above the template picker and then ‘Blank’ as the template.

Start with this code:

let process = Process()
process.launchPath = "/usr/bin/say"
process.arguments = ["-v", "?"]
let outPipe = Pipe()
process.standardOutput = outPipe
process.terminationHandler = { process in
  let outData = outPipe.fileHandleForReading.readDataToEndOfFile()
  let output = String(data: outData, encoding: .utf8) ?? ""
 print(output)
}
try? process.run()
process.waitUntilExit()

You will recognize some of the code from the first part of this tutorial. We create a Process object and set its launchPath and arguments. Note that the Process.run() convenience method, which we used in the first part, takes a URL to define the executable, but the launchPath is a String containing the path to the executable. We also (this is the new part) create a Pipe and set it as the standardOutput of the process.

The process will run the say command asynchronously. Since we want to work with the output , we have to give the process some code to execute when the command is done. We set this terminationHandler to a closure. The code in this closure grabs the data from pipe we connected to standardOutput of the process, converts it to a String and prints it.

At the end of our code, we tell the process object to run(). The waitUntilExit() is necessary here, because that is all this particular playground code does and we want to be sure that the command and the termination handler get a chance to do their work, before the code ends. In an app, where many things may be happening at the same time, you usually will not use waitUntilExit(). We will see that later when we implement our solution in SwiftUI.

Many outcomes

This code grabs the standard out from the command. Unix commands have different results that can be interesting. Some commands print to standard error instead of (or together with) standard out. All unix commands also have an exit code, which should return 0 for successful runs and a non-zero value for failures. Some commands use different non-zero value to give information for different errors.

All of this is available from Process objects. However, you have to set up the pipes and connections and get the data back in the termination handler, and the code gets quite complicated and tedious to set up. We have the seen the Process type has a convenience method to create and run a command without the pipes. I don’t know why it doesn’t have a convenience method when you are interested in all the data, but the good news is, we can create an extension to build our own.

Replace the code in the playground with the following:

import Foundation

extension Process {
  @discardableResult
  static func launch(
    path: String,
    arguments: [String] = [],
    terminationHandler: @escaping (Int, Data, Data) -> Void
  ) throws -> Process {
    let process = Process()
    let outPipe = Pipe()
    let errorPipe = Pipe()
    process.standardOutput = outPipe
    process.standardError = errorPipe
    process.arguments = arguments
    process.launchPath = path
    process.terminationHandler = { process in
      let outData = outPipe.fileHandleForReading.readDataToEndOfFile()
      let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
      let exitCode = Int(process.terminationStatus)
      terminationHandler(exitCode, outData, errorData)
    }
    try process.run()
    return process
  }
}

let process = try? Process.launch(
  path: "/usr/bin/say", 
  arguments: ["-v", "?"]
) { exitCode, outData, errData in
  let output = String(data: outData, encoding: .utf8) ?? ""
  print(output)
}
process?.waitUntilExit()

You will recognize the code from our first example in the launch function in the extension. But here, we have added the configuration for a second Pipe for standardError, in the closure we get the Data for the standard out, standard error and the exit code and pass them in to the closure passed in a termination handler.

This method simplifies using the Process type. We just have to pass in the path to the command and the arguments array and give a closure that is called when the command completes.

async/await

But it still uses a closure for the termination handler. This breaks our code into different fragments that are not executed in the order they appear in. Since macOS Monterey 12 and iOS 15, Swift has had a concurrency feature called async/await. With this, your code appears in a more natural order.

When a function has the await marker, the system knows to suspend the code at that point until the function returns a result. While this code is “on hold” other threads or tasks can run, such as the UI handling, so your process or app isn’t blocked. When the function returns, the code continues after the function, so the code that processes the output of the function comes in the logical order, which makes it easier to read and understand.

For some reason, the Process type has not yet been updated to use this new feature. We can however, add this functionality using an extension. Add this method to the extension:

  static func launch(
    path: String,
    arguments: [String] = []
  ) async throws -> (exitCode: Int, standardOutput: Data, standardError: Data) {
    try await withCheckedThrowingContinuation { continuation in
      do {
        try launch(path: path, arguments: arguments) { exitCode, outData, errData in
          continuation.resume(returning: (exitCode, outData, errData))
        }
      } catch let error {
        continuation.resume(throwing: error)
      }
    }
  }

If you want to get more detail how async and await work, I recommend the WWDC session “Meet async/await in Swift” from WWDC 2021.

With this, we can change our code to run the say command to:

guard let (exitCode, outData, errData) = try? await Process.launch(
    path: "/usr/bin/say",
    arguments: ["-v", "?"]
) else { exit(0) }

let output = String(data: outData, encoding: .utf8) ?? ""
print(output)

The code is now in a more sensible order. If you can afford macOS Monterey as a minimum system requirement, you should consider adopting async/await.

Now that we have our output of the command, we have to parse out the names of the voices. This code will turn the output of the say into an Array of names, ignoring the language code and sample text:

func parseVoices(_ output: String) -> [String] {
  output
    .components(separatedBy: "\n")
    .map {
      $0
        .components(separatedBy: "#")
        .first?
        .trimmingCharacters(in: .whitespaces)
        .components(separatedBy: CharacterSet.whitespaces)
        .dropLast()
        .filter { !$0.isEmpty }
        .joined(separator: " ")
      ?? ""
    }
    .filter { !$0.isEmpty }
}

So we can add these lines to get an Array of `voices:

let voices = parseVoices(output)
print(voices)

You can find the stages of code for the playground in this gist.

Updating the app

Now that we have assembled all the pieces working in a playground, we can move on to putting these pieces in our SwiftUI app. The goal is to have a popup menu with all the voices above the field where you can enter text.

We will be using some features that were introduced in macOS Monterey 12.0. If you have built the project a while ago with an older version of macOS, the project may be set to build with older versions of macOS. To verify and, if necessary, update the deployment target for the project, select the blue project icon at the very top of the item sidebar, then select the gray “SayThis” icon under the “Targets” section. Then select “General” in the tab list. The second section is called “Minimum Deployments” and should show macOS 12.0 or later. When you change this from an older version, Xcode may prompt to update some other settings in the project, you can accept those.

First, we want to use the extension to the Process type we created in the playground earlier. Create a new file in the project (File > New > New File…), select “Swift File” from the templates, and name it ‘Process-launch’. Copy and paste the extension code from the playground (with both methods) to that file. You could have all the code in a single file, but it is cleaner and more maintainable to have one file per type or extension. This also allows you to copy that file to other projects to use it there.

Next we need two more state variables to track the state of the popup-menu that we are going to add. In the ContentView file, add these two lines right under the existing @State variables:

  @State var voices: [String] = []
  @State var selectedVoice: String = "Samantha"

The first is where we are going to store all the available voices that we parse from the output of say -v '?'. The second variable will store the current selection.

Next, we will insert the popup menu for the voices into the UI. In the body, insert this below the title and above the HStack:

      Picker(selection: $selectedVoice, label: Text("Voice:")) {
          ForEach(voices, id: \.self) { Text($0) }
      }

First we create a Picker view, which is not really proper terminology for macOS. But since SwiftUI is designed to share objects across all platforms, a ‘Picker’ will render as a popup menu in macOS. We attach the selectedVoice state variable to the selection of the picker. Then, we loop through all the items in the voices state variable to add them to the picker.

At this point, you should see the popup menu in the preview and when you run the project. You cannot select anything from it, though, which makes sense as the voices array is empty.

We need to populate the voices array before the UI appears. SwiftUI offers a special modifier to do this. You can attach a .task modifier to any view and its closure will be run asynchronously once, before the view appears for the first time. Add this code to the end of the VStack block, right below the line that reads .frame(maxWidth: .infinity, maxHeight: .infinity):

    .task {
      guard let (_, outData, _) = try? await Process.launch(
        path: "/usr/bin/say",
        arguments: ["-v", "?"]
      ) else { return }

      let output = String(data: outData, encoding: .utf8) ?? ""
      voices = parseVoices(output)
    }

You also need to copy the parseVoices() function from the test playground and add it to the ContentView struct.

This will populate the popup menu with all the voices. Build and run to test. It will still not actual use the selected voice. We need to update the runCommand() method to:

  func runCommand() {
    let arguments = [message, "-v", selectedVoice]
    let executableURL = URL(fileURLWithPath: "/usr/bin/say")
    self.isRunning = true
    try! Process.run(executableURL, arguments: arguments) { _ in
      self.isRunning = false
    }
  }

We have achieved what we set out to do. You can find the project with all the code for this point here.

Refinements

However, there are some refinements and improvements that we can and should still add to the code.

First, the runCommand() function still uses the old convenience handler with a termination handler. We can change it to use our new await Process.launch():

  func runCommand() async {
    let arguments = [message, "-v", selectedVoice]
    self.isRunning = true
    let _ = try? await Process.launch(path: "/usr/bin/say", arguments: arguments)
    self.isRunning = false
  }

This will now generate an error in the Button because we have changed the runCommand() function to be async. Change the code of the Button to

        Button("Say") {
          Task {
            await runCommand()
          }
        }
        .disabled(isRunning)

By wrapping the await runCommand() function in a Task { } we are telling the system that this code should run in the background and not return immediately. This is necessary to run code blocks with async functions from UI elements.

The say command will use the voice set in the system settings when no -v option is given. We want to provide a way to recreate that behavior in our UI. We can add items to the Picker by adding elements before the ForEach:

      Picker(selection: $selectedVoice, label: Text("Voice:")) {
        Text("System Default").tag("System Default")
        Divider()
        ForEach(voices, id: \.self) { Text($0) }
      }

Also change the default value of the selectedVoice variable to "System Default".

Then we have to change the runCommand() method to only use the -v and voice name arguments when their value is not “System Default”

  func runCommand() async {
    var arguments = [message]
    if selectedVoice != "System Default" {
      arguments.append(contentsOf: ["-v", selectedVoice])
    }
    self.isRunning = true
    let _ = try? await Process.launch(path: "/usr/bin/say", arguments: arguments)
    self.isRunning = false
  }

You can find the code for this here.

Out of the Sandbox

The say command provides a fun example to play around with. You will probably already have plenty of ideas that you want to try out. There is one thing that might trip you up here: sandboxed apps do not get access to all available command line tools. If you want to run such ‘prohibited’ commands, you will need to remove the sandbox configuration from the app.

Better Extension

The extension I put together here will work in most situations, but there are conditions where different parts might not work well. Quinn the Eskimo has published this code which goes further and is probably “even more” thread safe.

Launching commands is an “expensive” task. You should always do some research to see if there is some framework that can give you access to the same functionality natively in Swift. Nevertheless, sometimes it might be necessary, and sometimes it might just be easier to call out to an external command.

This tutorial should help you along the way of using these tools effectively.

Swift UI Tutorial – Part 3

The big conferences expect you to provide a topic and a brief description several months in advance. This can be challenging as you have to pick something that you think will still be interesting in eight months or so, even if there is a WWDC and the larger part of the beta phase of a new macOS and iOS version in between. It also has to be able to hold my attention for about eight months, which is not an easy requirement.

I usually try to meet that challenge by choosing something that is complex enough that it has a large likelihood of remaining relevant. For this year’s JNUC, I chose “Use Swift with the Jamf API.” This would very certainly remain relevant, as both Swift and the Jamf Pro API were certain to remain in existence. I was also not expecting too great changes in either and if there were smaller changes—both Swift and the Jamf API update regularly—I was confident I would be able to handle them.

It also covered another goal I have for my presentation: it was something I didn’t really know at the time and wanted to learn more about. I had dabbled with SwiftUI before, most prominently for my 2021 MacSysAdmin Online presentation “Let’s Swift Again” and I had also tried myself with using the Jamf API from Swift. But the new concurrency features of Swift 5.5 looked like they could make the code much more interesting.

My hunch was correct. But, even though the new concurrency features simplified the code, using Swift to retrieve and work with objects from the Jamf API still remained quite a bit more complex than doing so with curl in a shell script. A JNUC session was supposed to fit into 30 minutes.

So, I hatched a crazy plan. To remain in the 30 minutes, I would just superficially introduce the most important concepts in the sessions, and then publish a tutorial and some sample code that would explain the details. Ideally, the tutorial would publish around the same time as JNUC.

Even early in putting together the session slides and sample code, I realized, there is far too much to explain for a single post. So it would become a series of posts. No problem, I have done that before. I suggested the series to Jamf marketing and they were happy to go with it, so I was committed.

I did manage to get the first part done and published in time for JNUC. Then the work that piled up over being away for the conference struck and it took a while to get part two out. Part three was published yesterday. The project is starting to take form and is diving into some really essential, but also exciting features of Swift.

I am polishing part 4 right now and will send it to the great people who run the Jamf blog for editing and more polishing soon-ish. I am working on the sequels, where we finally, actually will get into the SwiftUI part of the tutorial. I expect there to be seven parts in total, though this project may have more surprises for me yet.

I think this worked out well, even though it certainly turned out to be far more complex and far more work than I had originally anticipated. I have certainly learned a lot along the way, so that goal was achieved! I hope you will enjoy this series as much as I did writing it. (Some people like it.)

Next year, maybe I will go for something less complex… maybe…

Some Swift Updates

Earlier this year, at JNUC I did a presentation on how to “Use Swift with the Jamf API” and one of the things promised there is a series of articles that described more details than I could cover in the 30 minute presentation.

Note: the session video (and all other JUNC sessions recordings) is available to attendees of JNUC in the conference portal for 60 days. Then the sessions will be made available on YouTube for everyone.

The first part has been out for a while. But for various reasons, the second part took much longer than anticipated. Nevertheless, the wait is over and you can go read the second part here!

Future installments will hopefully not take as long.

If you worked your way through the first part, the Jamf Blog CMS had initially mangled some of the Swift code which lead to some errors. Those errors are now fixed. The sample code repo always had the correct code.

Much earlier (last year) I did a different presentation on Swift at MacSysAdmin. Some of the code used in that presentation’s demo to change the default browser was already deprecated. I still used the deprecated LaunchServices functions because the replacement functions were only made available in Monterey and I wanted the code to work on older versions of macOS, as well. Now, in Ventura, the deprecated functions have been removed. I have updated the sample code to now check the macOS version and use the older LaunchServices functionality on Big Sur and older, and the new NSWorkspace based functions in Monterey and higher. You can get the sample code in this gist.

I enjoyed putting together these presentations and tutorials.

MDOYVR 22 Talk: The Encyclopedia of macOS Automation

Last week I had the pleasure and honor of participating and presenting at MacDevOps YVR. The videos for the sessions are now appearing on YouTube.

There is a page for my talk “The Encyclopedia of macOS Automation,” in which I discuss the options for scripting and automation on macOS, with extra links and notes. You can go directly to the video here.

The talks this year were graphic recorded by the amazing Ashton Rodenhiser (website, twitter). The graphic at the top of this post was made by her while I was presenting.

As always, I had a lot of fun at this conference. Many thanks to the organizers and all the other speakers. Until next year!

Monterey, python, and free disk space

With Montery, many MacAdmins have been seeing dialogs that state:

“ProcessName” needs to be updated

and often the “ProcessName” is your management system. As others have already pointed out, the process, or scripts this process is calling, is using the pre-installed Python 2.7 at /usr/bin/python.

This is Apple’s next level of warning us that that the pre-installed Python (and Perl and Ruby) is deprecated and going away in “future version of macOS.” I have written about this before.

Even though the management system will be identified as the process that “needs to be updated,” the culprits are scripts and scriptlets that the management system calls for for management tasks (e.g. policies, tasks, scripts) and information gathering (e.g. extension attributes, facts, etc.). Ben Tom’s post above has information on how to identify scripts which may use python in a Jamf Pro server.

You can suppress the warning using a configuration profile. While this a useful measure to avoid confusing users with scary dialogs, you will have to start identifying and fixing scripts that are written entirely in python or just use simple python calls, and replacing them with non-python solutions.

Python 2.7 is not getting any more security patches and I assume Apple is eager to remove it from macOS. The clock is really ticking on this one.

Current User

The most common python call is probably the one which determines the currently logged in user. The python call for this was developed by Mike Lynn and popularized by Ben Toms in this post and has been a reliable MacAdmin tool for years. I have written about this and introduced a shell-based solution discovered by Erik Berglund.

But there are other use cases, where it is not so straight forward to replace the python code. The built-in python is so popular for MacAdmin tasks because it comes with PyObjC which allows access to the macOS system frameworks. With a few python calls you can avoid having to build an Objective-C or Swift command line tool.

Desktop Picture

I built desktoppr for this reason. The standard way to set a desktop picture with locking it down was a line of AppleScript. But, starting in macOS Mojave, sending AppleEvents to another process (in this case Finder) required a PPPC profile. You can also set the desktop picture using a framework call. There were python scripts out there, but the Swift solution will survive them…

Available Disk Space

Yesterday, I came across another such problem. With the recent versions of macOS, getting a value of the available disk space is not as strightforward as it used to be. There are a lot of files and data on the system, which will be cleared out when some process requires more disk space. Most of this is cache data or data that can be restored from cloud storage. But this ‘flexible’ available disk space will not be reported by the traditional tools, such as df or diskutil. The available disk space these tools report will be woefully low.

The available disk space which Finder reports will usually be much higher. There is functionality in the macOS system frameworks where apps can get the values for available that takes the ‘flexible’ files into account. There is even useful sample code!

Starting with this sample code, I built a command line tool that reports the different levels of ‘available’ disk space. When you run diskspace it will list them all. There are raw and ‘human-readable’ formats.

> diskspace                  
Available:      70621810688
Important:      231802051028
Opportunistic:  214051607271
Total:          494384795648
> diskspace -H              
Available:      70.62 GB
Important:      231.8 GB
Opportunistic:  214.05 GB
Total:          494.38 GB

The ‘Available’ value matches the actually unused disk space that df and diskutil will report. The ‘Important’ value matches what Finder will report as available. The ‘Opportunistic’ value is somewhat lower, and from Apple’s documentation on the developer page, that seems to be what we should use for automated background tasks.

For use in scripts, you can get each raw number with some extra flags:

> diskspace --available               
70628638720
> diskspace --important
231808547284
> diskspace --opportunistic
214057661159
> diskspace --total
494384795648

You can get more detail by running diskspace --help.

In Scripts

If you wanted to check if there is enough space to run the macOS Monterey upgrade (26 GB) you could do something like this:

if [[ $(/usr/local/bin/diskspace --opportunistic ) -gt 26000000000 ]]; then
     echo "go ahead"
else
    echo "not enough free disk space"
fi

Jamf Extension Attributes

Or, you can use diskspace in a Jamf Extension Attribute:

#!/bin/sh

diskspace="/usr/local/bin/diskspace"

# test if diskspace is installed
if [ ! -x "$diskspace" ]; then
    # return a negative value as error
    echo "<result>-1</result>"
fi

echo "<result>$($diskspace --opportunistic)</result>"

Since, this extension attribute relies on the diskspace tool being installed, you should have a ‘sanity check’ to see that the tool is there.

Get and install the tool

You can get the tool from the GitHub repo and I have created a (signed and notarized) installer pkg that will drop the tool in /usr/local/bin/diskspace.

Download Full Installer update

The small tool to download the InstallAssistant.pkg I built a while back, has been working fine, even on Monterey. However, earlier this week some people started noticing that it would not show the 11.6.1 installer. The reason had me stumped, and I was putting together a minor update with UI fixes and an icon for Monterey installers, when I realized what the problem was and was able to fix it. So you will actually find _two_ new releases on the GitHub repo today, but of course, you only need the latest, v1.1.1 aka “The real Monterey Update”.

MacSysAdmin Online 2021 is live!

The first set of sessions for the MacSysAdmin Online sessions are… well… online!

There is an introduction video from Patrik Jerneheim, a session on Time Machine by Howard Oakley, Rich Trouton demonstrates AutoPkg in the cloud and Charles Edge celebrates Scandinavian contributions to computing. Oh, and I talk about building tools with Swift and SwiftUI.

You can find the links to all the videos from today on the MacSysAdmin website. More sessions will be published every day this week at 09:30 CEST (UTC+2).

You can find the links and resources for my Swift session here.

You can still support MacSysAdmin Online by purchasing a T-Shirt. The store will remain open until Friday.

Many thanks to Patrik Jerneheim and the team for putting this on. Also to all the presenters for building these sessions.

Download Full Installer

A while back I wrote up a blog post on deploying the Install macOS Big Sur application. As one of the solutions, I posted a script (based on Greg Neagle’s installinstallmacos.py) which listed the pkgs from Apple’s software update catalogs so you could download them.

During and after WWDC, I wanted to see if I could build a SwiftUI app. I thought that building a user interface for this task would be a nice practice project.

Ironically, since I want the app to work on Big Sur, I could not use any of the new Swift and SwiftUI features Apple introduced this year. Even so, since I had not used SwiftUI to build a Big Sur application, most of the features Apple introduced last year were still new to me.

It was often unexpected to me which parts turned out to be challenging and which parts were really easy to implement. For example, implementing a preferences window, turned out to be super-easy, but it took me two false-starts to find the correct approach. Communicating with the preferences system of macOS is also very easy, but so poorly documented that you are always second guessing if what you are doing is right.

Apple’s documentation for Swift and SwiftUI on this has definite highlights, but is very sparse overall. I am still not sure if some of the decisions I made while putting this together were “good” choices.

Nevertheless, it works! I think it might be a nice tool to have, so I put it on GitHub. You can just download the app from the release page and use it, or clone the repo and take a look at the code.

Constructive feedback is always welcome! I am still learning this as I go along, too.