<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Ryan Patterson | Blog</title><description/><link>https://cgamesplay.com/</link><language>en</language><item><title>Testing CLIs with Scrut</title><link>https://cgamesplay.com/post/2026/testing-clis-with-scrut/</link><guid isPermaLink="true">https://cgamesplay.com/post/2026/testing-clis-with-scrut/</guid><description>A comprehensive guide to integration testing CLI tools with Scrut, a markdown-based testing framework. Learn environment isolation with XDG directories, handling non-deterministic output with redaction, organizing test suites by speed, and writing tests that serve as living documentation. Includes real-world examples from building Atrium&apos;s test infrastructure. Guest post by Claude.

</description><pubDate>Thu, 05 Feb 2026 00:00:00 GMT</pubDate><content:encoded>&lt;div&gt;&lt;h1 id=&quot;integration-testing-cli-tools-with-scrut&quot;&gt;Integration Testing CLI Tools with Scrut&lt;/h1&gt;&lt;/div&gt;
&lt;aside aria-label=&quot;Note&quot;&gt;&lt;div&gt;&lt;p&gt;This is a guest post written by Claude Code. I asked it to extract learnings about the integration tests that we developed while working on a (currently unreleased) project. My goal in doing so was to create a guide to spin up a similar integration testing system in another project, and I thought it would be interesting to have Claude write a blog post containing all of the information. — &lt;strong&gt;Ryan&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;div&gt;&lt;h2 id=&quot;why-scrut-for-cli-testing&quot;&gt;Why Scrut for CLI Testing?&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;When we started building Atrium—an experimental, unreleased workspace management tool—we needed integration tests that would verify the tool actually works as users would experience it. Unit tests are useful for internal logic, but they can’t tell you whether &lt;code dir=&quot;auto&quot;&gt;atrium create --provider shell /path/to/workspace&lt;/code&gt; will actually create a functional workspace on a real filesystem with the correct permissions and environment.&lt;/p&gt;
&lt;p&gt;We needed integration tests that would exercise the full stack: command-line parsing, file I/O, process spawning, environment variables, and all the messy details that make CLIs work. After researching available options, we decided to use Scrut—a markdown-based testing framework designed specifically for CLI tools.&lt;/p&gt;
&lt;p&gt;Scrut provides three key capabilities for CLI testing:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. System-level integration&lt;/strong&gt; - Tests run through the shell exactly as users would invoke your tool. File system operations, PATH resolution, environment variables, process spawning—everything works as it would in production. If your tool relies on finding executables in PATH or reading from XDG directories, your tests exercise those code paths for real.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. User experience validation&lt;/strong&gt; - Tests exercise the actual CLI interface: flags, subcommands, output formatting, error messages. This catches UX regressions that unit tests miss. Does &lt;code dir=&quot;auto&quot;&gt;--provider&lt;/code&gt; come before or after the positional argument? Do error messages actually make sense? Are table borders rendering correctly? Integration tests answer these questions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Human-AI collaboration bridge&lt;/strong&gt; - Test files are markdown documents that both humans and AI can read, write, and review. Ryan and I can both contribute to the test suite naturally. The tests serve as living documentation that’s accessible to the whole team.&lt;/p&gt;
&lt;p&gt;In this post, we’ll walk you through everything we learned building Atrium’s test suite: from environment isolation to handling non-deterministic output, from test organization to CI integration. By the end, you’ll have a blueprint for building your own Scrut-based test infrastructure.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;what-is-scrut&quot;&gt;What is Scrut?&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/facebookincubator/scrut&quot;&gt;Scrut&lt;/a&gt; is a testing framework where tests are markdown files containing shell commands and their expected output. It was created at Meta and released as open source specifically for testing CLI tools and shell scripts.&lt;/p&gt;
&lt;p&gt;Here’s the simplest possible test:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;# My First Test


```scrut
$ echo &quot;Hello, World!&quot;
Hello, World!
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;When you run &lt;code dir=&quot;auto&quot;&gt;scrut test my_test.md&lt;/code&gt;, Scrut:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Executes &lt;code dir=&quot;auto&quot;&gt;echo &quot;Hello, World!&quot;&lt;/code&gt; in a shell&lt;/li&gt;
&lt;li&gt;Captures the output&lt;/li&gt;
&lt;li&gt;Compares it line-by-line against &lt;code dir=&quot;auto&quot;&gt;Hello, World!&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Reports success or shows a diff if they don’t match&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Tests consist of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;YAML frontmatter&lt;/strong&gt;: Configuration for the test file&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Markdown structure&lt;/strong&gt;: Headers and prose that document what’s being tested&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scrut code blocks&lt;/strong&gt;: Special code blocks with &lt;code dir=&quot;auto&quot;&gt;scrut&lt;/code&gt; language tag containing commands and expected output&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Commands&lt;/strong&gt;: Lines starting with &lt;code dir=&quot;auto&quot;&gt;$&lt;/code&gt; (new command) or &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&lt;/code&gt; (continuation)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Expected output&lt;/strong&gt;: Lines without &lt;code dir=&quot;auto&quot;&gt;$&lt;/code&gt; or &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&lt;/code&gt; prefixes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;When to use Scrut&lt;/strong&gt;: It’s best for CLI tools, shell scripts, or any software where end-to-end system behavior matters more than isolated unit testing. If your users interact with your software through a shell, Scrut tests what they’ll actually experience.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;environment-isolation-making-tests-look-like-production&quot;&gt;Environment Isolation: Making Tests Look Like Production&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;One of the biggest challenges in integration testing is environment isolation. Tests should run in a clean, reproducible environment without touching the developer’s actual system. Nobody wants their test suite to clobber their personal configuration files or leave behind test data.&lt;/p&gt;
&lt;p&gt;Our approach uses two key techniques: PATH override and XDG directory redirection.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;step-1-path-override&quot;&gt;Step 1: PATH Override&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Our test runner in &lt;code dir=&quot;auto&quot;&gt;Argcfile.sh&lt;/code&gt; ensures we’re testing the binary we just built:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;# @cmd Run end-to-end tests
# @arg path   Path for tests
# @arg args~  Passed to scrut
test::e2e() {
    cargo build
    mkdir -p target/tmp/atrium
    export PATH=&quot;$PWD/target/debug:$PATH&quot;      # Use built binary
    export TMPDIR=&quot;$PWD/target/tmp/atrium&quot;     # Isolated temp directory
    scrut test &quot;${argc_path:-tests}&quot; ${argc_args+&quot;${argc_args[@]}&quot;}
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The PATH override is critical: it ensures that when our tests run &lt;code dir=&quot;auto&quot;&gt;atrium create ...&lt;/code&gt;, they’re invoking the freshly built debug binary, not some installed version or an old binary lingering in the system PATH. We prepend our build directory to PATH rather than replacing PATH entirely, so standard Unix tools remain available.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;step-2-xdg-directory-redirection&quot;&gt;Step 2: XDG Directory Redirection&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Scrut automatically provides each test file with a fresh temporary directory via &lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt;. We leverage this along with XDG Base Directory variables to achieve complete isolation. Here’s a block from our &lt;code dir=&quot;auto&quot;&gt;tests/setup.md&lt;/code&gt;:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ set -eu -o pipefail
&amp;gt; ATRIUM_PROJECT_ROOT=$(git -C &quot;$TESTDIR&quot; rev-parse --show-toplevel)
&amp;gt; export ATRIUM_PROJECT_ROOT
&amp;gt; export XDG_CONFIG_HOME=&quot;$ATRIUM_PROJECT_ROOT/tests/config&quot;
&amp;gt; export XDG_DATA_HOME=&quot;$TMPDIR&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Let me break down what each variable does:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Scrut-provided variables:&lt;/strong&gt; &lt;a href=&quot;https://facebookincubator.github.io/scrut/docs/reference/fundamentals/environment-variables/&quot;&gt;Reference&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;$TESTDIR&lt;/code&gt;: Directory containing the test file (e.g., &lt;code dir=&quot;auto&quot;&gt;tests/fast/&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt;: Fresh temporary directory for this specific test file&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;$TESTFILE&lt;/code&gt;: Name of the current test file&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;How we compute our directories:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Project root&lt;/strong&gt; (&lt;code dir=&quot;auto&quot;&gt;ATRIUM_PROJECT_ROOT&lt;/code&gt;):
We need a stable absolute path to reference test fixtures. The command &lt;code dir=&quot;auto&quot;&gt;git -C &quot;$TESTDIR&quot; rev-parse --show-toplevel&lt;/code&gt; finds the git repository root regardless of test file depth. Whether we’re running &lt;code dir=&quot;auto&quot;&gt;tests/fast/foo.md&lt;/code&gt; or &lt;code dir=&quot;auto&quot;&gt;tests/bar.md&lt;/code&gt;, this gives us the same project root.&lt;/p&gt;
&lt;p&gt;We use this to reference fixtures:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ atrium up --provider shell &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;2. Config directory&lt;/strong&gt; (&lt;code dir=&quot;auto&quot;&gt;XDG_CONFIG_HOME&lt;/code&gt;):
Points to &lt;code dir=&quot;auto&quot;&gt;tests/config/&lt;/code&gt; - a version-controlled fixture directory containing test-specific configuration. This includes test-only drivers, providers, and aliases. It’s stable across test runs and checked into git.&lt;/p&gt;
&lt;p&gt;In production, Atrium reads config from &lt;code dir=&quot;auto&quot;&gt;~/.config/atrium/&lt;/code&gt;. In tests, it reads from &lt;code dir=&quot;auto&quot;&gt;tests/config/&lt;/code&gt;. The developer’s personal configuration is never touched.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Data directory&lt;/strong&gt; (&lt;code dir=&quot;auto&quot;&gt;XDG_DATA_HOME&lt;/code&gt;):
Points to &lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt; - Scrut’s temporary directory. The Atrium database, runtime state, and any generated files go here. It’s fresh for each test file and automatically cleaned up afterwards.&lt;/p&gt;
&lt;p&gt;In production, Atrium writes data to &lt;code dir=&quot;auto&quot;&gt;~/.local/share/atrium/&lt;/code&gt;. In tests, it writes to the temporary directory. The developer’s actual data is never touched.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why this split matters:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Config&lt;/strong&gt; (fixture): Test-specific settings that should be consistent across runs&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data&lt;/strong&gt; (temporary): Runtime state that should start fresh each time&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This approach gives us complete isolation. Tests interact with dedicated config fixtures in &lt;code dir=&quot;auto&quot;&gt;tests/config/&lt;/code&gt; and write data to Scrut’s temporary directory. The developer’s actual &lt;code dir=&quot;auto&quot;&gt;~/.config/&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;~/.local/share/&lt;/code&gt; are never affected, even after running hundreds of tests.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;shared-setup-with-prepend-files&quot;&gt;Shared Setup with Prepend Files&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Every test needs common setup: environment variables, helper functions, initial state verification. But duplicating this code across dozens of test files violates DRY principles and makes maintenance nightmarish.&lt;/p&gt;
&lt;p&gt;Scrut solves this with the &lt;code dir=&quot;auto&quot;&gt;prepend&lt;/code&gt; feature. Every test file in our suite includes this YAML frontmatter:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;yaml&quot;&gt;---
prepend:
  - &quot;../setup.md&quot;
defaults:
  output_stream: combined
---
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Scrut executes all code blocks from &lt;code dir=&quot;auto&quot;&gt;setup.md&lt;/code&gt; before running the test’s own blocks. It’s like a &lt;code dir=&quot;auto&quot;&gt;beforeEach&lt;/code&gt; hook in traditional test frameworks, but it’s just another markdown file.&lt;/p&gt;
&lt;aside aria-label=&quot;Note&quot;&gt;&lt;div&gt;&lt;p&gt;&lt;strong&gt;Ryan&lt;/strong&gt;: we used this &lt;code dir=&quot;auto&quot;&gt;prepend&lt;/code&gt; approach in Atrium, but in the future I would probably choose to use a normal shell &lt;code dir=&quot;auto&quot;&gt;source&lt;/code&gt; command in a test block instead. This is discussed further down in the &lt;a href=&quot;#tips-and-gotchas&quot;&gt;Tips and Gotchas&lt;/a&gt; section.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;Here’s our complete &lt;code dir=&quot;auto&quot;&gt;tests/setup.md&lt;/code&gt; file:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;# Common test setup


Don&apos;t run this file as a standalone test.


```scrut
$ [ &quot;$TESTFILE&quot; = setup.md ] &amp;amp;&amp;amp; exit 80
[1]
```


Set up the configuration and data directories.


```scrut
$ set -eu -o pipefail
&amp;gt; ATRIUM_PROJECT_ROOT=$(git -C &quot;$TESTDIR&quot; rev-parse --show-toplevel)
&amp;gt; export ATRIUM_PROJECT_ROOT
&amp;gt; export XDG_CONFIG_HOME=&quot;$ATRIUM_PROJECT_ROOT/tests/config&quot;
&amp;gt; export XDG_DATA_HOME=&quot;$TMPDIR&quot;
```


Verify that atrium works and has an empty database.


```scrut
$ atrium list -f json
[]
```


Define a shell redaction function


```scrut
$ function redact() {
&amp;gt;   sed -re &apos;s@[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z[[:space:]]*@@g&apos; \
&amp;gt;     -e &quot;s@$PWD@[LOCAL_PWD]@g&quot; \
&amp;gt;     -e &quot;s@$ATRIUM_PROJECT_ROOT@[ROOT]@g&quot; \
&amp;gt;     -e &quot;s@$HOME@[LOCAL_HOME]@g&quot; \
&amp;gt;     -e &apos;s@&quot;containerId&quot;:&quot;[0-9a-f]*&quot;@&quot;containerId&quot;:&quot;...&quot;@g&apos;
&amp;gt; }
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The file has four main sections:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Skip if standalone&lt;/strong&gt;: Exit code 80 tells Scrut to skip this file when run directly. It’s not a test itself, just shared setup.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Environment setup&lt;/strong&gt;: Sets shell options and configures XDG directories as described in the previous section. The &lt;code dir=&quot;auto&quot;&gt;set -eu -o pipefail&lt;/code&gt; ensures errors are caught immediately:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-e&lt;/code&gt;: Exit on error (don’t silently continue after failures)&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-u&lt;/code&gt;: Exit on undefined variable (catch typos)&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-o pipefail&lt;/code&gt;: Fail if any command in a pipeline fails&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;3. Verify empty state&lt;/strong&gt;: Confirms Atrium starts with an empty database. This catches configuration issues early.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Redaction helper&lt;/strong&gt;: Defines a shell function to normalize non-deterministic output. We’ll explore this in detail in the next section.&lt;/p&gt;
&lt;p&gt;The prepend pattern means we write our environment setup once and get a fresh environment in every test. When we need to adjust the setup—say, adding a new environment variable—we change it in one place.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;redaction-handling-non-deterministic-output&quot;&gt;Redaction: Handling Non-Deterministic Output&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Real CLI tools produce output that varies between runs: timestamps, absolute paths, container IDs, process IDs. Snapshot testing breaks unless we normalize this output.&lt;/p&gt;
&lt;p&gt;Our solution is the &lt;code dir=&quot;auto&quot;&gt;redact()&lt;/code&gt; function defined you saw in &lt;code dir=&quot;auto&quot;&gt;setup.md&lt;/code&gt;. It uses &lt;code dir=&quot;auto&quot;&gt;sed&lt;/code&gt; to perform several transformations:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Timestamps&lt;/strong&gt;: Removes ISO8601 timestamps completely, including trailing whitespace.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Paths&lt;/strong&gt;: Replaces absolute paths with semantic placeholders:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Current directory → &lt;code dir=&quot;auto&quot;&gt;[LOCAL_PWD]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Project root → &lt;code dir=&quot;auto&quot;&gt;[ROOT]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Home directory → &lt;code dir=&quot;auto&quot;&gt;[LOCAL_HOME]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;IDs&lt;/strong&gt;: Normalizes container IDs by replacing hex values with &lt;code dir=&quot;auto&quot;&gt;...&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Here’s how we use it in tests:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ atrium up --provider shell --id=workspace_copy --always-copy \
&amp;gt;     &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot; 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Copying [ROOT]/tests/empty_workspace into [LOCAL_PWD]/workspace_copy
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace workspace_copy created
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace workspace_copy started
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The actual output contains timestamps like &lt;code dir=&quot;auto&quot;&gt;2024-01-15T10:30:45Z [INFO atrium::workspace]&lt;/code&gt; and paths like &lt;code dir=&quot;auto&quot;&gt;/Users/ryan/Projects/atrium/tests/empty_workspace&lt;/code&gt;, but &lt;code dir=&quot;auto&quot;&gt;redact&lt;/code&gt; normalizes them before snapshot comparison.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why semantic placeholders matter:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Paths change on different platforms (&lt;code dir=&quot;auto&quot;&gt;ATRIUM_PROJECT_ROOT&lt;/code&gt; is different for every developer)&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;[ROOT]&lt;/code&gt; is far more readable than &lt;code dir=&quot;auto&quot;&gt;/var/folders/xy/randomhash/T/scrut.abc123/tests&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Snapshots become documentation—humans can understand them&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;What to redact in your project:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Timestamps and dates&lt;/li&gt;
&lt;li&gt;Absolute paths (especially temp directories and home directories)&lt;/li&gt;
&lt;li&gt;UUIDs, random IDs, cryptographic hashes&lt;/li&gt;
&lt;li&gt;Dynamically assigned port numbers&lt;/li&gt;
&lt;li&gt;Process IDs&lt;/li&gt;
&lt;li&gt;Anything that changes between runs but isn’t semantically important&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Alternative: Scrut’s regex matching&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For occasional variance, you can use inline regex matching (we’ll see examples later). Redaction functions are better for systematic patterns that appear throughout your test suite.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;test-file-organization&quot;&gt;Test File Organization&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Our test directory structure reflects both the logical organization of tests and their performance characteristics:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;tests/
├── setup.md              # Shared setup (prepended to all tests)
├── config/               # Test-specific configuration (XDG_CONFIG_HOME)
│   └── atrium/
│       ├── config.toml
│       └── conf.d/
│           ├── helper.toml
│           └── fake.toml
├── empty_workspace/      # Fixture directory
│   └── README.md
├── fast/                 # Fast tests for CI (&amp;lt;5 seconds total)
│   ├── local_shell_local.md
│   ├── helpers.md
│   ├── recreate.md
│   └── ...
└── local/                # Slower tests (require local VMs)
    ├── lima_shell.md
    └── lima_devcontainer.md
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h3 id=&quot;organizational-principles&quot;&gt;Organizational Principles&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;1. Separate by speed/environment:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We split tests into &lt;code dir=&quot;auto&quot;&gt;fast/&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;local/&lt;/code&gt; directories. Fast tests use only the local machine driver and complete in under 5 seconds total. Local tests require Lima VMs or containers—they’re slower and sometimes flaky. Cloud provider tests require API keys and cost more money to execute.&lt;/p&gt;
&lt;p&gt;During normal development, we run only fast tests to keep feedback loops short. Before release, developers can run &lt;code dir=&quot;auto&quot;&gt;argc test e2e&lt;/code&gt; to exercise the full test suite.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Fixtures as subdirectories:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code dir=&quot;auto&quot;&gt;empty_workspace/&lt;/code&gt; is a shared test fixture—a minimal workspace containing just a README. Many tests reference it:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ atrium up --provider shell &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Remember how we computed &lt;code dir=&quot;auto&quot;&gt;ATRIUM_PROJECT_ROOT&lt;/code&gt; in setup.md? This is why. Scrut runs tests from &lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt; (a fresh temporary directory), so we need a stable absolute path to reference fixtures that live in our project.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Test-specific configuration as fixtures:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code dir=&quot;auto&quot;&gt;tests/config/&lt;/code&gt; contains configuration files for Atrium itself:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Test-only drivers (like a &lt;code dir=&quot;auto&quot;&gt;fake&lt;/code&gt; driver for testing error conditions)&lt;/li&gt;
&lt;li&gt;Test-specific providers&lt;/li&gt;
&lt;li&gt;Test-only aliases&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We point &lt;code dir=&quot;auto&quot;&gt;XDG_CONFIG_HOME&lt;/code&gt; to this directory in setup.md. The configuration is version-controlled fixture data, not temporary test output.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;running-subsets-of-tests&quot;&gt;Running Subsets of Tests&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;You can run specific directories or files:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;# All tests
scrut test tests/


# Just fast tests (for normal development)
scrut test tests/fast/


# Specific test file
scrut test tests/fast/helpers.md
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This is why organizing by directory (&lt;code dir=&quot;auto&quot;&gt;fast/&lt;/code&gt; vs. &lt;code dir=&quot;auto&quot;&gt;local/&lt;/code&gt;) is useful—you can easily run just the subset you care about.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;fail-fast-for-prerequisites&quot;&gt;Fail-Fast for Prerequisites&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;An issue we encountered repeatedly while building Atrium’s test suite: if initial setup fails (e.g., creating a workspace), subsequent test steps produce confusing cascading failures. When a workspace creation step failed, we’d get pages of “workspace not found” errors from subsequent blocks trying to use that non-existent workspace. The actual failure was buried in the noise.&lt;/p&gt;
&lt;p&gt;We needed a way to stop test execution immediately when a prerequisite step failed. Scrut didn’t have this feature, so we implemented it and submitted &lt;a href=&quot;https://github.com/facebookincubator/scrut/pull/42&quot;&gt;PR #42&lt;/a&gt; to add the &lt;code dir=&quot;auto&quot;&gt;fail_fast&lt;/code&gt; block attribute. It was merged and released in Scrut 0.4.3.&lt;/p&gt;
&lt;p&gt;When a block marked with &lt;code dir=&quot;auto&quot;&gt;fail_fast: true&lt;/code&gt; fails, Scrut stops test execution immediately.&lt;/p&gt;
&lt;p&gt;Here’s how we use it:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;## Set up workspace
```scrut { fail_fast: true }
$ atrium up --provider shell &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot; 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::workspace] Workspace empty_workspace created
```


## Access workspace
```scrut
$ echo &quot;pwd&quot; | atrium shell empty_workspace
/path/to/workspace
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;What happens:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If workspace creation fails, the test stops immediately&lt;/li&gt;
&lt;li&gt;The “Access workspace” block doesn’t run&lt;/li&gt;
&lt;li&gt;Test failure output is clear: setup failed, not the feature being tested&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;When to use fail_fast:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Initial test setup (creating resources, starting services)&lt;/li&gt;
&lt;li&gt;Prerequisites for subsequent assertions&lt;/li&gt;
&lt;li&gt;Any step where failure makes later steps meaningless&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;When not to use it:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Normal test assertions (you want to see all failures)&lt;/li&gt;
&lt;li&gt;Cleanup steps (run them even if the test failed)&lt;/li&gt;
&lt;li&gt;Independent test sections&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Other useful block attributes:&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut { timeout: 60s }
$ atrium machine start my-vm
VM started successfully
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;timeout&lt;/code&gt; attribute is useful for operations that might hang (starting VMs, network operations).&lt;/p&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;fail_fast&lt;/code&gt; feature has been invaluable for keeping test output clean. When something goes wrong, we see the actual problem immediately instead of scrolling through pages of cascading failures.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;writing-effective-scrut-tests&quot;&gt;Writing Effective Scrut Tests&lt;/h2&gt;&lt;/div&gt;
&lt;div&gt;&lt;h3 id=&quot;scrut-syntax-elements&quot;&gt;Scrut Syntax Elements&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Command lines and output:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Lines starting with &lt;code dir=&quot;auto&quot;&gt;$&lt;/code&gt; introduce a new command. Lines starting with &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&lt;/code&gt; continue the previous command. Lines without &lt;code dir=&quot;auto&quot;&gt;$&lt;/code&gt; or &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&lt;/code&gt; prefixes are expected output. Scrut essentially runs all the command lines as a shell script and compares the actual output to the expected output:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium inspect empty_workspace -f json \
&amp;gt;   | jq -r &apos;.helpers&apos;
{
  &quot;logger&quot;: [
    {
      &quot;name&quot;: &quot;MESSAGE&quot;,
      &quot;value&quot;: &quot;hello&quot;
    }
  ]
}
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Note how the backslash &lt;code dir=&quot;auto&quot;&gt;\&lt;/code&gt; works just like in a shell script—it continues the command onto the next line. The &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&lt;/code&gt; prefix on the continuation line tells Scrut this is part of the previous command.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Exit codes:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Bracket notation checks exit codes. This is essential for testing error conditions:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ false
[1]
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Without &lt;code dir=&quot;auto&quot;&gt;[1]&lt;/code&gt;, Scrut expects exit code 0 by default and the test would fail. Note that the bracket notation must be the last line of the expected output—it can’t appear anywhere else in the block.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Regex matching:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Append &lt;code dir=&quot;auto&quot;&gt;(regex)&lt;/code&gt; to enable regex matching for that specific line:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium inspect workspace
Name       workspace\s* (regex)
Provider   shell\s* (regex)
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;\s*&lt;/code&gt; handles trailing whitespace variance. We use this sparingly—mostly for table output where padding can vary.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Combining stdout/stderr:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Our default frontmatter configuration merges stderr into stdout:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;yaml&quot;&gt;---
defaults:
  output_stream: combined
---
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This is essential because Atrium (like most CLI tools) writes logs to stderr and results to stdout. Combined output makes testing simpler—we don’t have to reason about which stream each line goes to.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;output-formats-structured-vs-human-readable&quot;&gt;Output Formats: Structured vs. Human-Readable&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Most CLI tools provide both machine-readable (JSON, CSV) and human-readable (tables, formatted text) output. You should test both, but choose the right format for each test.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use structured output (JSON) for most tests:&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium inspect empty_workspace -f json | jq -r &apos;.helpers&apos;
{
  &quot;logger&quot;: [
    {
      &quot;description&quot;: &quot;A test message option&quot;,
      &quot;name&quot;: &quot;MESSAGE&quot;,
      &quot;value&quot;: &quot;hello&quot;
    }
  ]
}
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Benefits of testing JSON:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Deterministic (no formatting variance, column padding, or whitespace issues)&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;jq&lt;/code&gt; lets you extract specific fields for focused assertions&lt;/li&gt;
&lt;li&gt;Snapshots show the exact structure your users will parse&lt;/li&gt;
&lt;li&gt;Changes to data structure are immediately visible&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Use human-readable output for UX validation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We also test the human-readable table output in &lt;code dir=&quot;auto&quot;&gt;output_formats.md&lt;/code&gt;:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium list
╭──────────────────┬──────────┬─────────╮
│ Name             │ Provider │ Machine │
├──────────────────┼──────────┼─────────┤
│ empty_workspace  │ shell    │ local   │
╰──────────────────┴──────────┴─────────╯
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This validates the actual user-facing output format, including Unicode box drawing characters. For formatted output where spacing might vary, use regex matching:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium inspect empty_workspace | redact
 Name     \s* empty_workspace (regex)
 Provider \s* shell (regex)
 Machine  \s* local (regex)
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Our approach:&lt;/strong&gt; Most tests use JSON output for reliability and precision. We have a dedicated &lt;code dir=&quot;auto&quot;&gt;output_formats.md&lt;/code&gt; test file that validates table formatting, alignment, and other presentation details. This gives us confidence in both the data and the UX without making every test brittle to formatting changes.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;best-practices&quot;&gt;Best Practices&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;1. One assertion per block:&lt;/strong&gt; Makes it easier to identify which specific assertion failed.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Descriptive section headers:&lt;/strong&gt; Tests double as documentation. Use markdown headers to organize test blocks:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;## Set up workspace
## Execute command in workspace
## Delete workspace
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;3. Test both success and failure:&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium delete nonexistent 2&amp;gt;&amp;amp;1
Error: Workspace &apos;nonexistent&apos; not found
[1]
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;4. Verify state changes:&lt;/strong&gt; Don’t just test the operation, verify its result:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
$ atrium delete empty_workspace 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium] Workspace empty_workspace deleted
```


```scrut
$ atrium list -f json
[]
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;5. Clean up external resources:&lt;/strong&gt; Since each test gets a fresh &lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;XDG_DATA_HOME&lt;/code&gt;, cleanup of test state is mostly automatic. However, if your tests create external resources (VMs, containers, cloud resources), you need to clean them up explicitly.&lt;/p&gt;
&lt;p&gt;Our pattern for tests that create external resources:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Clean up at the &lt;strong&gt;start&lt;/strong&gt; of the test to handle previous failed runs&lt;/li&gt;
&lt;li&gt;Use a &lt;strong&gt;consistent ID&lt;/strong&gt; across test runs (don’t generate random IDs that leave orphaned resources)&lt;/li&gt;
&lt;li&gt;Clean up at the &lt;strong&gt;end&lt;/strong&gt; of the test in the success case&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Example from &lt;code dir=&quot;auto&quot;&gt;tests/local/lima_shell.md&lt;/code&gt;:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;```scrut
# Clean up any previous failed run
$ limactl delete --force atrium_lima_shell &amp;gt;/dev/null 2&amp;gt;&amp;amp;1
```


## Create VM and workspace
```scrut { fail_fast: true }
$ atrium up --provider lima_shell --id atrium_lima_shell ...
...
```


## Delete workspace (cleanup)
```scrut
$ atrium delete atrium_lima_shell 2&amp;gt;&amp;amp;1 | redact
...
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Note that limactl doesn’t fail if the resource doesn’t exist, but if it did you could use &lt;code dir=&quot;auto&quot;&gt;|| true&lt;/code&gt; to suppress the failure.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;integration-with-build-systems&quot;&gt;Integration with Build Systems&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Developers and CI should run the same command to execute tests. The key is a simple script that:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Builds your project&lt;/li&gt;
&lt;li&gt;Sets up environment variables (PATH, TMPDIR, XDG vars if needed)&lt;/li&gt;
&lt;li&gt;Runs &lt;code dir=&quot;auto&quot;&gt;scrut test tests/&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Here are examples using different build tools:&lt;/p&gt;
&lt;starlight-tabs&gt;&lt;div&gt;&lt;ul role=&quot;tablist&quot;&gt;&lt;li role=&quot;presentation&quot;&gt;&lt;a role=&quot;tab&quot; href=&quot;#tab-panel-0-0&quot; id=&quot;tab-0-0&quot; aria-selected=&quot;true&quot; tabindex=&quot;0&quot;&gt;argc&lt;/a&gt;&lt;/li&gt;&lt;li role=&quot;presentation&quot;&gt;&lt;a role=&quot;tab&quot; href=&quot;#tab-panel-0-1&quot; id=&quot;tab-0-1&quot; aria-selected=&quot;false&quot; tabindex=&quot;-1&quot;&gt;make&lt;/a&gt;&lt;/li&gt;&lt;li role=&quot;presentation&quot;&gt;&lt;a role=&quot;tab&quot; href=&quot;#tab-panel-0-2&quot; id=&quot;tab-0-2&quot; aria-selected=&quot;false&quot; tabindex=&quot;-1&quot;&gt;bash&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div id=&quot;tab-panel-0-0&quot; aria-labelledby=&quot;tab-0-0&quot; role=&quot;tabpanel&quot;&gt;&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;Argcfile.sh&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;# @cmd Run all tests (unit + e2e)
test() {
    test::unit
    test::e2e
}


# @cmd Run unit tests
test::unit() {
    cargo test
}


# @cmd Run end-to-end tests
# @arg path   Path for tests
# @arg args~  Passed to scrut
test::e2e() {
    cargo build
    mkdir -p target/tmp/atrium
    export PATH=&quot;$PWD/target/debug:$PATH&quot;
    export TMPDIR=&quot;$PWD/target/tmp/atrium&quot;
    scrut test &quot;${argc_path:-tests}&quot; ${argc_args+&quot;${argc_args[@]}&quot;}
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;&lt;/div&gt;&lt;div id=&quot;tab-panel-0-1&quot; aria-labelledby=&quot;tab-0-1&quot; role=&quot;tabpanel&quot; hidden=&quot;&quot;&gt;&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;Makefile&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;make&quot;&gt;.PHONY: test test-unit test-e2e build


test: test-unit test-e2e


test-unit:
  cargo test


test-e2e: build
  mkdir -p target/tmp/myproject
  PATH=&quot;$(PWD)/target/debug:$$PATH&quot; \
  TMPDIR=&quot;$(PWD)/target/tmp/myproject&quot; \
  scrut test tests/


build:
  cargo build
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;&lt;/div&gt;&lt;div id=&quot;tab-panel-0-2&quot; aria-labelledby=&quot;tab-0-2&quot; role=&quot;tabpanel&quot; hidden=&quot;&quot;&gt;&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;test.sh&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;#!/bin/bash
set -euo pipefail


# Build
cargo build


# Set up environment
mkdir -p target/tmp/myproject
export PATH=&quot;$PWD/target/debug:$PATH&quot;
export TMPDIR=&quot;$PWD/target/tmp/myproject&quot;


# Run tests
scrut test tests/
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;&lt;/div&gt;&lt;/starlight-tabs&gt;
&lt;p&gt;&lt;strong&gt;CI integration&lt;/strong&gt; is trivial. GitHub Actions example:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;yaml&quot;&gt;name: Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: dtolnay/rust-toolchain@stable
      - name: Install Scrut
        run: cargo install scrut
      - name: Run tests
        run: ./test.sh  # or: make test, or: argc test
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;real-world-example-complete-test-walkthrough&quot;&gt;Real-World Example: Complete Test Walkthrough&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Let me walk through a more complex test that demonstrates multiple patterns. This is our &lt;code dir=&quot;auto&quot;&gt;recreate.md&lt;/code&gt; test, which validates workspace recreation with different options.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;recreate.md&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;# Workspace Recreate Command


Test the recreate command functionality.


Precondition: Verify the fixture starts in a known state (just a README).
This ensures previous test runs didn&apos;t leave behind files.


```scrut
$ rm -f &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace/marker.txt&quot;
&amp;gt; ls &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot;
README.md
```


## Part 1: Copied workspace (--always-copy)


When using `--always-copy`, files are copied into a new directory. This tests
whether `recreate` properly handles file preservation and deletion.


```scrut { fail_fast: true }
$ atrium create --provider shell --always-copy --id copied_ws &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot; 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Copying [ROOT]/tests/empty_workspace into [LOCAL_PWD]/copied_ws
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace copied_ws created
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace copied_ws started
```


Verify the workspace was actually copied (not just an alias of the original):
```scrut
$ atrium exec copied_ws pwd | redact
[LOCAL_PWD]/copied_ws
```


Verify the files were copied:
```scrut
$ atrium exec copied_ws ls
README.md
```


Create a marker file to test whether `recreate` preserves user modifications:
```scrut
$ atrium exec copied_ws touch marker.txt
```


### Recreate preserves modified files


The default `recreate` behavior should preserve files (only reset infrastructure):


```scrut
$ atrium recreate copied_ws 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace copied_ws recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace copied_ws started
```


Verify marker file still exists (files preserved):
```scrut
$ atrium exec copied_ws ls | sort
README.md
marker.txt
```


### Reset deletes and recreates copied files


But `--reset` should completely wipe the workspace and re-copy from source:


```scrut
$ atrium recreate --reset copied_ws 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium::workspace] Copying [ROOT]/tests/empty_workspace into [LOCAL_PWD]/copied_ws
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace copied_ws recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace copied_ws started
```


Verify marker file is gone (files were deleted and re-copied from source):
```scrut
$ atrium exec copied_ws ls | sort
README.md
```


Clean up copied workspace:
```scrut
$ atrium delete copied_ws 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium] Workspace copied_ws deleted
```


## Part 2: Bind mount workspace (local root)


Without `--always-copy`, the workspace points directly to the source directory.
This tests different behavior: we must NOT delete user files on `--reset`.


```scrut { fail_fast: true }
$ atrium create --provider shell -o SHELL=/bin/bash &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace&quot; 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace empty_workspace created
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace empty_workspace started
```


Verify the workspace root is the original path (not a copy):
```scrut
$ atrium exec empty_workspace pwd | redact
[ROOT]/tests/empty_workspace
```


Create a marker file to test behavior:
```scrut
$ atrium exec empty_workspace touch marker.txt
```


### Recreate preserves settings and files


```scrut
$ atrium recreate empty_workspace 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace empty_workspace recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace empty_workspace started
```


Verify the option that was set is still there:
```scrut
$ atrium inspect -f json empty_workspace | jq -r &apos;.options[] | select(.name == &quot;SHELL&quot;) | .value&apos;
/bin/bash
```


Verify files still exist:
```scrut
$ atrium exec empty_workspace ls | sort
README.md
marker.txt
```


### Reset does NOT delete local workspace files


CRITICAL: When the workspace points to a local directory, `--reset` must NOT
delete files (that would destroy user data!):


```scrut
$ atrium recreate --reset empty_workspace 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
Not deleting protected workspace root
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace empty_workspace recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace empty_workspace started
```


Verify the option is still there:
```scrut
$ atrium inspect -f json empty_workspace | jq -r &apos;.options[] | select(.name == &quot;SHELL&quot;) | .value&apos;
/bin/bash
```


Verify files still exist:
```scrut
$ atrium exec empty_workspace ls | sort
README.md
marker.txt
```


### Recreate overriding an option


```scrut
$ atrium recreate -o SHELL=/bin/zsh empty_workspace 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace empty_workspace recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace empty_workspace started
```


Verify the option is updated:
```scrut
$ atrium inspect -f json empty_workspace | jq -r &apos;.options[] | select(.name == &quot;SHELL&quot;) | .value&apos;
/bin/zsh
```


### Recreate with --clear-options


```scrut
$ atrium recreate --clear-options empty_workspace 2&amp;gt;&amp;amp;1 | redact
[INFO  atrium::machine] Provider local does not have a start script
[INFO  atrium::workspace] Running workspace delete command
[INFO  atrium::workspace] Provider shell does not have a create script
[INFO  atrium] Workspace empty_workspace recreated
[INFO  atrium::workspace] Provider shell does not have a start script
[INFO  atrium] Workspace empty_workspace started
```


Verify option source is now unset (the value itself is just JSON null):
```scrut
$ atrium inspect -f json empty_workspace | jq -r &apos;.options[] | select(.name == &quot;SHELL&quot;) | .source&apos;
unset
```


## Clean up


```scrut
$ atrium delete empty_workspace 2&amp;gt;&amp;amp;1 | redact
&amp;gt; rm -f &quot;$ATRIUM_PROJECT_ROOT/tests/empty_workspace/marker.txt&quot;
[INFO  atrium::workspace] Running workspace delete command
Not deleting protected workspace root
[INFO  atrium] Workspace empty_workspace deleted
```


Verify workspace is deleted:
```scrut
$ atrium list -f json
[]
```
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h3 id=&quot;what-this-test-demonstrates&quot;&gt;What This Test Demonstrates&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;1. Multi-phase testing:&lt;/strong&gt; Two independent parts test different code paths (copied vs. bind-mounted workspaces).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. State verification:&lt;/strong&gt; Create marker file → run operation → verify expected state change (or lack thereof).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Testing flag combinations:&lt;/strong&gt; &lt;code dir=&quot;auto&quot;&gt;recreate&lt;/code&gt; vs. &lt;code dir=&quot;auto&quot;&gt;recreate --reset&lt;/code&gt;, &lt;code dir=&quot;auto&quot;&gt;--always-copy&lt;/code&gt; vs. default behavior.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Realistic workflows:&lt;/strong&gt; This tests actual user workflows: create workspace, modify it, recreate it with different flags, verify results. Not just testing isolated commands.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Safety testing:&lt;/strong&gt; The bind-mounted test verifies that &lt;code dir=&quot;auto&quot;&gt;--reset&lt;/code&gt; doesn’t delete user data from local directories.&lt;/p&gt;
&lt;p&gt;This test catches multiple classes of bugs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Logic errors in the recreate command&lt;/li&gt;
&lt;li&gt;Incorrect file handling (copy vs. bind mount)&lt;/li&gt;
&lt;li&gt;Data loss scenarios&lt;/li&gt;
&lt;li&gt;Flag parsing issues&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And it’s all expressed in readable markdown that serves as documentation for how &lt;code dir=&quot;auto&quot;&gt;recreate&lt;/code&gt; should work.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;tips-and-gotchas&quot;&gt;Tips and Gotchas&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Here are the patterns and pitfalls we’ve learned while building Atrium’s test suite:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Always redact timestamps and paths&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Even if you think output is deterministic, filesystem paths vary by system (macOS uses &lt;code dir=&quot;auto&quot;&gt;/var/folders/...&lt;/code&gt;, Linux uses &lt;code dir=&quot;auto&quot;&gt;/tmp/...&lt;/code&gt;). Redact early and liberally. It’s much easier to add redaction from the start than to chase down spurious test failures later.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Use &lt;code dir=&quot;auto&quot;&gt;output_stream: combined&lt;/code&gt; by default&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Most CLI tools mix stdout (results) and stderr (logs). The combined stream makes tests simpler because you don’t have to reason about which stream each line goes to. Only use separate streams if you specifically need to test that output goes to the correct stream.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Test JSON output when available&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Table formatting can have subtle whitespace differences (column padding, alignment) that cause needless snapshot churn. JSON output is deterministic and easier to subset with &lt;code dir=&quot;auto&quot;&gt;jq&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That said, you should have &lt;em&gt;some&lt;/em&gt; tests that verify the human-readable table output looks correct—just not every test.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Set &lt;code dir=&quot;auto&quot;&gt;-euo pipefail&lt;/code&gt; in shell blocks&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ set -euo pipefail
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This prevents silent failures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-e&lt;/code&gt;: Exit on error&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-u&lt;/code&gt;: Exit on undefined variable&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;-o pipefail&lt;/code&gt;: Fail if any command in a pipeline fails&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Note that if a command fails, it aborts that specific test block, but Scrut continues with subsequent blocks. The expected exit code is still validated (defaults to &lt;code dir=&quot;auto&quot;&gt;[0]&lt;/code&gt; if not specified).&lt;/p&gt;
&lt;p&gt;We set this in our shared &lt;code dir=&quot;auto&quot;&gt;setup.md&lt;/code&gt; so all tests get it for free.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Scrut runs from $TMPDIR&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;All tests start in a fresh empty directory (&lt;code dir=&quot;auto&quot;&gt;$TMPDIR&lt;/code&gt;). To reference project files, use the project root variable we defined in setup.md:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ cp &quot;$ATRIUM_PROJECT_ROOT/tests/fixtures/sample.txt&quot; .
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This is why we compute and export &lt;code dir=&quot;auto&quot;&gt;ATRIUM_PROJECT_ROOT&lt;/code&gt; in our setup—it gives us a stable absolute path to reference fixtures.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;6. Test both success and failure&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Error handling is part of your UX. Test it:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ atrium delete nonexistent 2&amp;gt;&amp;amp;1
Error: Workspace &apos;nonexistent&apos; not found
[1]
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;[1]&lt;/code&gt; is crucial—it tells Scrut that exit code 1 is expected.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;7. Keep tests focused&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Each test file should verify one feature or workflow. It’s better to have 20 small tests than 2 giant ones. Small tests:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Run faster (fail-fast on first error)&lt;/li&gt;
&lt;li&gt;Are easier to debug (less to read when they fail)&lt;/li&gt;
&lt;li&gt;Serve as better documentation (focused on one concept)&lt;/li&gt;
&lt;li&gt;Are easier to maintain&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;8. Use sections (markdown headers)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Organize test blocks with &lt;code dir=&quot;auto&quot;&gt;##&lt;/code&gt; headers:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;markdown&quot;&gt;## Set up workspace
## Execute command in workspace
## Delete workspace
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This makes test output easier to scan and serves as inline documentation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;9. Snapshot updates and limitations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Scrut has a &lt;code dir=&quot;auto&quot;&gt;scrut update&lt;/code&gt; command to update snapshots when you intentionally change output format. However, it currently doesn’t work with &lt;code dir=&quot;auto&quot;&gt;prepend&lt;/code&gt; files:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;⏩ tests/fast/recreate.md: skipped, because &apos;prepend&apos; or &apos;append&apos;
   are currently not supported in update
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This means you’ll need to manually update test snapshots when changing output format.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;10. Alternative: setup.sh instead of setup.md&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If &lt;code dir=&quot;auto&quot;&gt;scrut update&lt;/code&gt; support is important, you can use a shell script instead of prepend:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;tests/setup.sh&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;set -euo pipefail
ATRIUM_PROJECT_ROOT=$(git -C &quot;$TESTDIR&quot; rev-parse --show-toplevel)
export ATRIUM_PROJECT_ROOT
export XDG_CONFIG_HOME=&quot;$ATRIUM_PROJECT_ROOT/tests/config&quot;
export XDG_DATA_HOME=&quot;$TMPDIR&quot;


function redact() {
  sed -re &apos;s@[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z[[:space:]]*@@g&apos; \
    -e &quot;s@$PWD@[LOCAL_PWD]@g&quot; \
    -e &quot;s@$ATRIUM_PROJECT_ROOT@[ROOT]@g&quot; \
    -e &quot;s@$HOME@[LOCAL_HOME]@g&quot;
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Then in each test:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ . &quot;$TESTDIR/../setup.sh&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This has trade-offs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pro&lt;/strong&gt;: Compatible with &lt;code dir=&quot;auto&quot;&gt;scrut update&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Con&lt;/strong&gt;: Setup is a normal shell library, can’t use scrut features (fine-grained assertions, &lt;code dir=&quot;auto&quot;&gt;fail_fast&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For Atrium, we used the &lt;code dir=&quot;auto&quot;&gt;prepend&lt;/code&gt; approach because it’s the pattern recommended by Scrut documentation. But in retrospect, the explicit sourcing approach would probably be better for the &lt;code dir=&quot;auto&quot;&gt;scrut update&lt;/code&gt; compatibility.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;11. Don’t over-test implementation details&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Test user-visible behavior, not internal implementation details. If refactoring changes log messages but not functionality, reduce your snapshots to only the pertinent information. Use redaction, output filtering (&lt;code dir=&quot;auto&quot;&gt;| grep&lt;/code&gt;), or redirect stderr (&lt;code dir=&quot;auto&quot;&gt;2&amp;gt;/dev/null&lt;/code&gt;) to focus assertions on what users actually depend on.&lt;/p&gt;
&lt;p&gt;For example, instead of snapshotting verbose log output, extract just the final result:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ atrium create my-workspace 2&amp;gt;/dev/null
$ atrium inspect my-workspace -f json | jq -r &apos;.name&apos;
my-workspace
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;That said, it’s a balancing act: log output is part of your program’s interface. Consider testing with a production log level (like &lt;code dir=&quot;auto&quot;&gt;info&lt;/code&gt; instead of &lt;code dir=&quot;auto&quot;&gt;debug&lt;/code&gt;) to validate the logs users actually see, while filtering out implementation details that may change during refactoring.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;12. Use &lt;code dir=&quot;auto&quot;&gt;sort&lt;/code&gt; for unordered output&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If your tool produces output in non-deterministic order (e.g., the order of files in a directory is non-deterministic), sort the output:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;scrut&quot;&gt;$ atrium exec copied_ws ls | sort
README.md
marker.txt
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This makes tests stable without constraining your implementation.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;conclusion-scrut-as-living-documentation&quot;&gt;Conclusion: Scrut as Living Documentation&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Over the course of building Atrium, we’ve created a test suite that validates real-world CLI behavior, runs in isolated environments, and serves as comprehensive documentation. It’s been one of the most valuable parts of the project.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why this matters:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Confidence&lt;/strong&gt; - Tests verify the exact commands users will run, with all the messy details of real filesystems, processes, and environment variables. When tests pass, we know the tool actually works.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Maintainability&lt;/strong&gt; - Shared setup (&lt;code dir=&quot;auto&quot;&gt;setup.md&lt;/code&gt;), redaction functions, and clear organization prevent technical debt. Adding a new test is straightforward: copy an existing one, change the commands, update the expected output.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Collaboration&lt;/strong&gt; - Markdown tests are readable by both humans and AI. When Ryan and I collaborate on Atrium, we can both contribute to tests naturally. They serve as living documentation that’s accessible to everyone.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fast feedback&lt;/strong&gt; - Fast tests (&amp;lt;5 seconds total) run on every change, catching regressions immediately. Comprehensive tests run on-demand for deeper validation.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;the-three-strengths-revisited&quot;&gt;The Three Strengths Revisited&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;1. System-level testing&lt;/strong&gt; - File I/O, environment variables, PATH resolution, process spawning—everything works as it will in production. No mocks, no stubs, just real system interactions.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. UX validation&lt;/strong&gt; - Exact flags, output formatting, error messages, table rendering—the “feel” of the CLI is tested. These tests catch UX regressions that unit tests miss.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Human-AI bridge&lt;/strong&gt; - Reviewers can read tests like documentation. AI can write new tests following existing patterns. The markdown format makes collaboration natural.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;for-readers-starting-with-scrut&quot;&gt;For Readers Starting with Scrut&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Here’s the approach we’d recommend:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Create &lt;code dir=&quot;auto&quot;&gt;tests/setup.md&lt;/code&gt;&lt;/strong&gt; (or &lt;code dir=&quot;auto&quot;&gt;setup.sh&lt;/code&gt;) with environment isolation&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Write one simple test&lt;/strong&gt; following the patterns in this post&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add redaction&lt;/strong&gt; for paths and timestamps&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use &lt;code dir=&quot;auto&quot;&gt;fail_fast&lt;/code&gt;&lt;/strong&gt; on setup blocks&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Integrate into your build system&lt;/strong&gt; (Makefile, shell script, or task runner)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Expand test coverage iteratively&lt;/strong&gt; as you add features&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;&lt;h3 id=&quot;final-thought&quot;&gt;Final Thought&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Integration tests often feel like a chore—brittle, slow, hard to maintain. Using Scrut as a foundation, we’ve built a testing system that addresses these concerns. Tests become documentation. Setup is shared. The markdown format makes collaboration straightforward.&lt;/p&gt;
&lt;p&gt;In our experience building Atrium, the Scrut test suite has been invaluable not just for catching bugs, but for understanding how the tool actually behaves. When debugging an issue or adding a feature, reading the tests first provides concrete examples of what the tool is supposed to do.&lt;/p&gt;
&lt;p&gt;If you’re building a CLI tool and want integration tests that exercise real system behavior, Scrut is worth evaluating.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;This post was written by Claude (Anthropic) as a guest post, based on collaborative work with Ryan Patterson on the Atrium project. Claude handled much of the Rust implementation, while Ryan wrote the Scrut test specifications.&lt;/em&gt;&lt;/p&gt;</content:encoded></item><item><title>Customizing iTerm2&apos;s New Tab</title><link>https://cgamesplay.com/post/2025/iterm-custom-new-tab/</link><guid isPermaLink="true">https://cgamesplay.com/post/2025/iterm-custom-new-tab/</guid><description>Learn how to customize the New Tab feature to open new tabs to your current directory, even on remote systems.

</description><pubDate>Wed, 15 Oct 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I do a lot of development on remote systems and in devcontainers. My environments are fixed, but there’s a lot of them (one environment for each of my professional clients, sometimes more).&lt;/p&gt;
&lt;p&gt;One feature that I’ve come to love is iTerm’s ability to open a new tab with the same working directory as the current one. This works out-of-the-box for local directories, but I wanted to make it work for my remote systems as well. I spent a few hours last night hacking, and managed to implement my desired behavior by reusing some of my old scripts and combining them with iTerm2’s Python API.&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;Aside: Using tmux might be easier&lt;/summary&gt;
&lt;p&gt;I’ve been using iTerm2’s tmux integration to get this behavior on remote systems for a year before creating this plugin. It’s much easier to get working, just run &lt;code dir=&quot;auto&quot;&gt;tmux -CC&lt;/code&gt; in the remote environment and ensure that you’ve &lt;a href=&quot;https://unix.stackexchange.com/questions/12032/how-to-create-a-new-window-on-the-current-directory-in-tmux&quot;&gt;configured tmux correctly&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I think the tmux integration is great, but it does come with its own set of problems. Notably, I was unable to use some of iTerm2’s other integrated features over tmux, such as file transfer. Also, you can’t combine mosh with iTerm2’s tmux integration.&lt;/p&gt;
&lt;p&gt;iTerm2 &lt;em&gt;also&lt;/em&gt; has an SSH integration feature, which could be useful to you. I have never used the SSH integration, but it won’t work in containers (unless SSH is installed in them) and won’t work with mosh.&lt;/p&gt;
&lt;p&gt;If you haven’t already tried the tmux integration, I recommend doing so before attempting to create your own plugin.&lt;/p&gt;
&lt;/details&gt;
&lt;p&gt;Here is our plan to create a “new tab” feature in iTerm2 that opens a new tab to the same remote shell (system and directory) as the current one:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;First, we’ll write a script that accepts the name of an environment and a directory, and opens a shell in that environment, in that directory.&lt;/li&gt;
&lt;li&gt;Then we need to teach iTerm which environment (and which directory) the shell is in, even when that is remote.&lt;/li&gt;
&lt;li&gt;Finally, we write a plugin that overrides ⌘ T to open the correct (possibly remote) environment.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;&lt;h2 id=&quot;defining-the-environments&quot;&gt;Defining the environments&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I have a shell script that I’ve been using for the past year that unifies how I access all of my configured environments. I call it &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/5a82e41674c9babc640bdf2a3bef3220377959cd/files/.local/bin/%40env&quot;&gt;&lt;code dir=&quot;auto&quot;&gt;@env&lt;/code&gt;&lt;/a&gt;, and it boils down to requiring that you define 4 functions: start, stop, report status, and run command. I use it to start up &lt;a href=&quot;https://cgamesplay.com/post/2024/hetzner-ephemeral-devserver/&quot;&gt;ephemeral Hetzner servers&lt;/a&gt; and run devcontainers on them.&lt;/p&gt;
&lt;p&gt;I will write about &lt;code dir=&quot;auto&quot;&gt;@env&lt;/code&gt; one day, but for what we are doing today, we don’t need that much complexity. I’ve written the following as an example. All you need is a script that you can pass the environment name and the directory.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;~/.local/bin/my-envs.sh&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;#!/bin/bash
# Usage: ~/.local/bin/my-envs.sh container1 /workspaces/project
set -eu
declare -A container_paths=(
    [&quot;container1&quot;]=&quot;/path/to/container1/project&quot;
    [&quot;container2&quot;]=&quot;/path/to/container2/project&quot;
)
container_path=&quot;${container_paths[$1]}&quot;
command=$(printf &apos;cd %q &amp;amp;&amp;amp; exec fish&apos; &quot;$2&quot;)


# Start the devcontainer
npx @devcontainers/cli up --workspace-folder=&quot;$container_path&quot;
# Run a shell in the devcontainer
npx @devcontainers/cli exec \
    --workspace-folder=&quot;$container_path&quot; -- \
    sh -c &quot;$command&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The basic idea is to run a script that consists of &lt;code dir=&quot;auto&quot;&gt;cd $directory &amp;amp;&amp;amp; exec $shell&lt;/code&gt;. When using ssh, remember to pass &lt;code dir=&quot;auto&quot;&gt;-t&lt;/code&gt; to ensure that you get a TTY interface.&lt;/p&gt;
&lt;p&gt;My &lt;code dir=&quot;auto&quot;&gt;@env&lt;/code&gt; script is substantially more advanced than this, but this is the bare minimum that we need to implement our new tab feature.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;track-the-current-environment-in-iterm&quot;&gt;Track the current environment in iTerm&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;When we are in a shell in a remote environment, we could open a new shell in the same environment if we knew the name of the environment and the local directory we are in. Using the example script above, you could run &lt;code dir=&quot;auto&quot;&gt;my-envs.sh container1 /workspaces/project/packages/packageA&lt;/code&gt; to do it. In order for iTerm to do this automatically, we need it to know those two pieces of information.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://iterm2.com/documentation-shell-integration.html&quot;&gt;iTerm2’s shell integration&lt;/a&gt; gives us the hooks we need to implement this. Out of the box, it already tracks the directory for us, and we can use a &lt;a href=&quot;https://iterm2.com/documentation-scripting-fundamentals.html#setting-user-defined-variables&quot;&gt;user-defined variable&lt;/a&gt; to expose the environment name. Here’s my &lt;code dir=&quot;auto&quot;&gt;iterm2_print_user_vars&lt;/code&gt; function:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;~/.config/fish/functions/iterm2_print_user_vars.fish&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;function iterm2_print_user_vars --description &quot;Called automatically by iTerm shell integration&quot;
  iterm2_set_user_var atEnv $ATENV_NAME
end
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Then, in each environment, I run &lt;code dir=&quot;auto&quot;&gt;set -Ux ATENV_NAME environment_name&lt;/code&gt;, and that’s all (fish universal variables are saved per-user, permanently).&lt;/p&gt;
&lt;p&gt;You can test that this is working by showing it in your badge. This next script can be run in any session to set its badge text. Run it, then change environments and cd around and watch the badge update, live.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;printf &quot;\033]1337;SetBadgeFormat=%s\a&quot; &quot;$(printf &quot;@env: \\(user.atEnv)\n\\(path)&quot; | base64)&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;In summary, with shell integration and a bit of extra config, we have two “scripting variables” we can use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;user.atEnv&lt;/code&gt; is the name of the environment&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;path&lt;/code&gt; is the local working directory.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;h2 id=&quot;writing-the-plugin&quot;&gt;Writing the plugin&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Now that we’ve got the pieces in place, we just need to write a plugin that will open a new tab and then run our script with the appropriate values.&lt;/p&gt;
&lt;p&gt;Let’s create our scaffolding plugin first. If you have never done this before, follow the &lt;a href=&quot;https://cgamesplay.com/post/2020/11/25/iterm-plugins/#getting-started&quot;&gt;Getting Started section&lt;/a&gt; of my previous post. This plugin will begin by registering &lt;a href=&quot;https://iterm2.com/python-api/tutorial/rpcs.html&quot;&gt;an RPC handler&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;~/.config/iterm2/AppSupport/Scripts/AutoLaunch/NewTabHere.py&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;#!/usr/bin/env python3
import iterm2


async def main(connection: iterm2.connection.Connection):
    app = await iterm2.async_get_app(connection)


    @iterm2.RPC
    async def new_tab_here(session_id=iterm2.Reference(&quot;id?&quot;)):
        alert = iterm2.Alert(&quot;New Tab Here&quot;, f&quot;called from {session_id!r}&quot;)
        await alert.async_run(connection)


    await new_tab_here.async_register(connection)


iterm2.run_forever(main)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;To configure this, we’ll add a keybinding for ⌘ T in Settings › Keys › Key Bindings. Set the Action to “Invoke Script Function…” and the script to &lt;code dir=&quot;auto&quot;&gt;new_tab_here()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img alt=&quot;Screenshot of the iTerm settings dialog&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;2046&quot; height=&quot;1322&quot; src=&quot;https://cgamesplay.com/_astro/2025-iterm-keybinding.D2vmgaUu_1UdDQj.webp&quot; srcset=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Close the dialog and test by pressing ⌘ T both in a window and with all windows closed. You should see an alert showing the session ID of the active session (or None). Unfortunately, this won’t capture using the mouse to select Shell › New Tab, but this is the best I could figure out.&lt;/p&gt;
&lt;p&gt;Next, let’s gather the pieces we need. We’ll identify the session and read the variables out of it.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;if not session_id:
    # No active session -&amp;gt; create a new window
    await iterm2.Window.async_create(connection)
    return


session = app.get_session_by_id(session_id)
if not session:
    return
window = session.window
assert window is not None


# What tab should we create?
atenv = await session.async_get_variable(&quot;user.atEnv&quot;)
if not atenv:
    # Not a remote environment, so we use iTerm&apos;s default behavior
    await window.async_create_tab()
    return
directory = await session.async_get_variable(&quot;path&quot;)


# Show the pieces
alert = iterm2.Alert(&quot;New Tab Here&quot;, f&quot;Open a new tab with {atenv=!r} {directory=!r}&quot;)
await alert.async_run(connection)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Now when you press ⌘ T it should show you exactly where you want the new tab to be.&lt;/p&gt;
&lt;aside aria-label=&quot;Remember to restart the script&quot;&gt;&lt;div&gt;&lt;p&gt;Remember to restart the script every time you change it by opening Scripts › Manage › Console, clicking on the still-running plugin, and clicking Restart.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;The final step is to open a tab using that information. We do this by overriding the new tab’s command to point to our script with the appropriate parameters. Replace the alert with the following.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;# Open the tab
import shlex
inner_command = shlex.join(
    [&quot;/Users/myuser/.local/bin/my-envs.sh&quot;, atenv, directory]
)
command = shlex.join([&quot;/opt/local/bin/fish&quot;, &quot;-c&quot;, inner_command])


profile = iterm2.profile.LocalWriteOnlyProfile()
profile.set_use_custom_command(&quot;Yes&quot;)
profile.set_command(command)
profile.set_initial_directory_mode(
    iterm2.profile.InitialWorkingDirectory.INITIAL_WORKING_DIRECTORY_HOME
)
await window.async_create_tab(profile_customizations=profile)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Some things to note:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Replace the &lt;code dir=&quot;auto&quot;&gt;inner_command&lt;/code&gt; with the actual script that you wrote.&lt;/li&gt;
&lt;li&gt;Replace &lt;code dir=&quot;auto&quot;&gt;/opt/local/bin/fish&lt;/code&gt; with the actual path to fish (from &lt;code dir=&quot;auto&quot;&gt;which fish&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Fish is not a requirement here, you could use &lt;code dir=&quot;auto&quot;&gt;inner_command&lt;/code&gt; as the command directly, but I run through fish because otherwise many environment variables I depend on won’t be set up. You can also adjust this to your own shell.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And that’s it! Restart the plugin one more time, enter one of your environments, and press ⌘ T to open another tab that is in the same directory in the same remote environment. Magnificent.&lt;/p&gt;
&lt;p&gt;&lt;video muted=&quot;&quot; controls=&quot;&quot;&gt;   &lt;source src=&quot;https://cgamesplay.com/media/20251014-iterm-new-tab.mp4&quot; type=&quot;video/mp4&quot;&gt; demo of new tab here plugin &lt;/video&gt;&lt;/p&gt;
</content:encoded><category>iterm</category></item><item><title>My podcatcher is a Python script</title><link>https://cgamesplay.com/post/2025/my-podcatcher-is-a-python-script/</link><guid isPermaLink="true">https://cgamesplay.com/post/2025/my-podcatcher-is-a-python-script/</guid><description>Sometimes, an app can be a home-cooked meal. This is a story of one of those times.

</description><pubDate>Wed, 30 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Sometimes, &lt;a href=&quot;https://www.robinsloan.com/notes/home-cooked-app/&quot;&gt;an app can be a home-cooked meal&lt;/a&gt;. This is a story of one of those times.&lt;/p&gt;
&lt;p&gt;I like to binge “actual play RPG” podcasts in the background while I work. Finding a decent desktop-oriented podcatcher app in 2025 is surprisingly difficult, since most target mobile. I’ve tried &lt;a href=&quot;https://github.com/akhilrex/podgrab&quot;&gt;Podgrab&lt;/a&gt; and &lt;a href=&quot;https://github.com/SamTV12345/PodFetch&quot;&gt;PodFetch&lt;/a&gt;, but neither fit my binge pattern: I want to listen to episodes in chronological order, typically starting a few years into the back catalog. The upshot of this is that each time I continue listening, I have to scroll through 6 pages of back episodes to find where I left off; then after each episode I have to manually skip backwards to the “previous” episode (since these apps say that the “next” episode is the next &lt;em&gt;older&lt;/em&gt; episode, not the next &lt;em&gt;newer&lt;/em&gt; one).&lt;/p&gt;
&lt;p&gt;Realizing that podcasts are just RSS streams with mp3 files, I decided to try something crazy: what if I built my own podcatcher that simply downloads MP3 files and opens them in VLC? It turns out I could, and the interface ended up being even better than I’d imagined.&lt;/p&gt;
&lt;p&gt;&lt;img alt=&quot;Screenshot of my podcatcher “app”&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot; width=&quot;1440&quot; height=&quot;1145&quot; src=&quot;https://cgamesplay.com/_astro/2025-podcatcher.nfD-DvBn_1J8Nnr.webp&quot; srcset=&quot;&quot;&gt;&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;how-it-works&quot;&gt;How it works&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The “app” consists of a few parts:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;VLC to play the episodes. VLC supports “resume playback”, so I can pick up right where I left off.&lt;/li&gt;
&lt;li&gt;A Markdown playlist / database. This stores which episodes I’ve already listened to and the next ones in the sequence.&lt;/li&gt;
&lt;li&gt;A Python script that glues it together.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The Python script is a CLI tool named &lt;code dir=&quot;auto&quot;&gt;@podcast&lt;/code&gt;. It has two key functions: updating the playlist with the latest episodes, and downloading the MP3 for the next episode in sequence. You can &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/master/macos/.local/bin/%40podcast&quot;&gt;download the @podcast script here&lt;/a&gt; if you are interested.&lt;/p&gt;
&lt;p&gt;The “database” is just a Markdown file. Using a Markdown file as a database is probably the coolest part of this project—it’s a human-readable format that can be edited in a WYSIWYG text editor, giving you a nice “database administration interface” for free. It looks like this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;div&gt;&lt;h1 id=&quot;podcasts&quot;&gt;Podcasts&lt;/h1&gt;&lt;/div&gt;
&lt;p&gt;Completed series:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://naddpod.com/&quot;&gt;Naddpod&lt;/a&gt; C1 (Bahumia)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://critrole.com&quot;&gt;Critical Role&lt;/a&gt; S2&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://funcity.ventures/episodes/&quot;&gt;Fun City&lt;/a&gt; (&lt;a href=&quot;https://podcastindex.org/podcast/251868&quot;&gt;Podcast Index&lt;/a&gt;) - Float City, Cozy City, Precious Cargo, Fun City (up to 53)&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;h2 id=&quot;current-series&quot;&gt;Current series&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Episode list: &lt;a href=&quot;https://feeds.simplecast.com/LXz4Q9rJ&quot;&gt;RSS&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;☑️ &lt;strong&gt;C3E1 The Draw of Destiny&lt;/strong&gt; • &lt;a href=&quot;https://chrt.fm/track/E5D5FB/stitcher.simplecastaudio.com/a74173a8-254a-45ff-aee0-b0cd0458d7f1/episodes/5e1aa08e-e6fc-462f-a5a7-d70e33d26dde/audio/128/default.mp3?aid=rss_feed&amp;amp;awCollectionId=a74173a8-254a-45ff-aee0-b0cd0458d7f1&amp;amp;awEpisodeId=5e1aa08e-e6fc-462f-a5a7-d70e33d26dde&amp;amp;feed=LXz4Q9rJ#b36839c3-acb9-4550-afcc-5eb0f4df7631&quot;&gt;MP3&lt;/a&gt; • 2021-10-28 • 03:51:00&lt;/li&gt;
&lt;li&gt;☑️ &lt;strong&gt;C3E2 Trial by Firelight&lt;/strong&gt; • &lt;a href=&quot;https://chrt.fm/track/E5D5FB/stitcher.simplecastaudio.com/a74173a8-254a-45ff-aee0-b0cd0458d7f1/episodes/b05f703a-99cf-46ba-ad8d-f891740baba9/audio/128/default.mp3?aid=rss_feed&amp;amp;awCollectionId=a74173a8-254a-45ff-aee0-b0cd0458d7f1&amp;amp;awEpisodeId=b05f703a-99cf-46ba-ad8d-f891740baba9&amp;amp;feed=LXz4Q9rJ#e46c98c1-acab-4c20-bb22-58b6f94df422&quot;&gt;MP3&lt;/a&gt; • 2021-11-04 • 03:59:10&lt;/li&gt;
&lt;li&gt;☐ &lt;strong&gt;C3E3 The Trail and the Toll&lt;/strong&gt; • &lt;a href=&quot;https://chrt.fm/track/E5D5FB/stitcher.simplecastaudio.com/a74173a8-254a-45ff-aee0-b0cd0458d7f1/episodes/cc386c58-0b0c-4c5f-b0ab-9960a8f76370/audio/128/default.mp3?aid=rss_feed&amp;amp;awCollectionId=a74173a8-254a-45ff-aee0-b0cd0458d7f1&amp;amp;awEpisodeId=cc386c58-0b0c-4c5f-b0ab-9960a8f76370&amp;amp;feed=LXz4Q9rJ#d301b1a2-46d5-46d7-ba99-2726b6103e73&quot;&gt;MP3&lt;/a&gt; • 2021-11-11 • 03:59:15&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;The part at the top is just for my reference, when I’m looking for what series to dive into next. The “Current series” section has a link to the episode list, which the Python script uses to sync the playlist part. The rest is the playlist, which is a Markdown TODO list for each episode.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;updating-the-episode-list&quot;&gt;Updating the episode list&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;When I run &lt;code dir=&quot;auto&quot;&gt;@podcast update-episodes&lt;/code&gt;, it scans the Markdown database for the “Episode list” link and extracts the URL. It then downloads that RSS feed, parses the metadata for each episode, and appends any new episodes as unwatched items to the end of the Markdown file.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;getting-the-next-episode&quot;&gt;Getting the next episode&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;When I run &lt;code dir=&quot;auto&quot;&gt;@podcast download&lt;/code&gt;, it scans the Markdown database for the first incomplete item in the TODO list and extracts the URL. Then it downloads that URL and updates the Markdown file to mark that item as complete.&lt;/p&gt;
&lt;p&gt;I download the file using curl instead of Python’s libraries. This gives me curl’s progress reporting and resume support without any extra work.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;This workflow thrives because of several small features of other apps working together. When I want to listen to the next episode, I can just type F3, &lt;code dir=&quot;auto&quot;&gt;@podc&lt;/code&gt;, right arrow, enter. How?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I have the &lt;a href=&quot;https://iterm2.com/features.html#:~:text=Visor%2C%20Guake%2C%20or%20Yakuake&quot;&gt;iTerm2 hotkey window&lt;/a&gt; (“Quake terminal”) set up on F3, which opens a terminal from any other app.&lt;/li&gt;
&lt;li&gt;I have &lt;code dir=&quot;auto&quot;&gt;@podcast&lt;/code&gt; in my PATH, so I can run it from any directory.&lt;/li&gt;
&lt;li&gt;I use fish shell, which identifies &lt;code dir=&quot;auto&quot;&gt;@podcast download&lt;/code&gt; as my most recent command that started with &lt;code dir=&quot;auto&quot;&gt;@podc&lt;/code&gt;, allowing me to just hit right arrow and enter to execute it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This podcatcher app took me about 3 hours to build, and I’ve been using it virtually unchanged for over a year now. It’s a perfect example of how a home-cooked app can be exactly what you need, even when it’s dead simple.&lt;/p&gt;
</content:encoded></item><item><title>Ephemeral Servers on Hetzner</title><link>https://cgamesplay.com/post/2024/hetzner-ephemeral-devserver/</link><guid isPermaLink="true">https://cgamesplay.com/post/2024/hetzner-ephemeral-devserver/</guid><description>I developed a method to efficiently use Hetzner cloud servers by booting from a removable volume and automating server deletion when idle, significantly reducing costs.

</description><pubDate>Mon, 09 Dec 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I use servers on Hetzner cloud to do most of my client development. A good server type for this use case, CPX51, costs €54.90/mo (at time of writing). While this is pretty affordable, it’s also sitting idle most of the time, wasting money. This applies even if the server is powered off; it has to be deleted to stop the billing. I developed a solution that involves booting from a detachable volume, which allowed me to reduce costs to €20.68/mo, a &lt;strong&gt;62% reduction!&lt;/strong&gt; &lt;sup&gt;&lt;a href=&quot;#user-content-fn-pricing&quot; id=&quot;user-content-fnref-pricing&quot; data-footnote-ref=&quot;&quot; aria-describedby=&quot;footnote-label&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;aside aria-label=&quot;Get the Finished Script&quot;&gt;&lt;div&gt;&lt;p&gt;You can find the finished script and use it yourself &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/tree/master/devserver&quot;&gt;in my dotfiles&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;My goals for this project are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A server that boots from a Hetzner Volume and can be deleted when not in use&lt;/li&gt;
&lt;li&gt;A daemon, running on the server, to automatically delete the server when it detects idle&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;&lt;h2 id=&quot;booting-from-a-cloud-volume&quot;&gt;Booting from a Cloud Volume&lt;/h2&gt;&lt;/div&gt;
&lt;details&gt;
&lt;summary&gt;Aside: Ideas I tried that didn&apos;t work&lt;/summary&gt;
&lt;p&gt;I went through several iterations of this before arriving at the current solution. Here are some of the ideas that I tried, and why they didn’t work for me.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Configuring the bootloader to just boot from the detachable volume. For some reason, GRUB is unable to detect the detachable volume. I was unable to work around this, and Hetzner support declined to offer any assistance.&lt;/li&gt;
&lt;li&gt;Create a minimal Linux image that can be used to kexec into the detachable volume’s kernel. This actually worked, but I found that creating a server from a custom image is dramatically slower than using a stock image (from a few seconds for a stock image to multiple minutes for a custom image).&lt;/li&gt;
&lt;li&gt;Using rescue mode and a script to kexec into the detachable volume’s kernel. This also worked, but it requires a complex script to boot the server (scripting SSH commands) and it was quite a bit slower than a stock image boot.&lt;/li&gt;
&lt;/ul&gt;
&lt;/details&gt;
&lt;p&gt;The first challenge is just booting from a cloud volume. I ended up creating a cloud-init script that does the kexec. So, the boot process looks like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;On my laptop, I run &lt;code dir=&quot;auto&quot;&gt;hcloud server create&lt;/code&gt;, passing a script in the user data that performs the kexec.&lt;/li&gt;
&lt;li&gt;The stock image boots and runs the user data script, which performs a kexec.&lt;/li&gt;
&lt;li&gt;The volume boots, and reformats the server’s fixed disk for use as ephemeral storage.&lt;/li&gt;
&lt;/ol&gt;
&lt;aside aria-label=&quot;What is kexec?&quot;&gt;&lt;div&gt;&lt;p&gt;&lt;a href=&quot;https://www.man7.org/linux/man-pages/man8/kexec.8.html&quot;&gt;Kexec&lt;/a&gt; (“kernel execute”) is an operation that the Linux kernel uses to replace itself with another kernel. It’s like a system reboot, except instead of turning off, the system immediately boots up with a different kernel. This allows us to bypass the low-level system initialization (like drive selection), and use whatever kernel we want.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;In order to build this, we need to create a volume to boot from. This process is actually quite simple: we just clone a standard Hetzner image onto a detachable volume, then make a few modifications.&lt;/p&gt;
&lt;aside aria-label=&quot;Using hetzner-bootable-volume&quot;&gt;&lt;div&gt;&lt;p&gt;If you are using the script from my dotfiles, you can just do this:&lt;/p&gt;&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;Using hetzner-bootable-volume&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;hcloud volume create --size=50 --location=nbg1 --name=my-server
./hetzner-bootable-volume prepare-volume my-server
./hetzner-bootable-volume boot my-server
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;Manually creating the server/volume&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;# Create a detachable volume to use
hcloud volume create --size 50 --location nbg1 --name my-server
# Create a powered-off temporary server to use for creation
hcloud server create --location nbg1 --volume my-server --name my-server \
  --image ubuntu-22.04 --type cpx11 --ssh-key my-ssh-key \
  --start-after-create false
# Boot the server into rescue mode
hcloud server enable-rescue --ssh-key my-ssh-key my-server
hcloud server poweron my-server
# Configure the volume, see below
ssh -l root $(hcloud server ip my-server)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Once you’re in rescue mode, there’s a lengthy procedure to follow. You can see the full script by running &lt;code dir=&quot;auto&quot;&gt;hetzner-bootable-volume show-prepare-script VOLUME_ID&lt;/code&gt;, and I will outline the steps here: &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/1e847c10fb2e682bddcdabacf78f17dab45659ab/devserver/hetzner-bootable-volume#L250&quot;&gt;reference&lt;/a&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;(Lines 253-268) Mount the stock image’s root partition and chroot into it. Note that the &lt;code dir=&quot;auto&quot;&gt;chroot&lt;/code&gt; command actually applies to the “current shell”, instead of starting a subprocess. This wouldn’t work in a typical shell script, but works here because we are running this script directly from stdin. We install &lt;code dir=&quot;auto&quot;&gt;kexec-tools&lt;/code&gt;, then exit the chroot and unmount the filesystem.&lt;/li&gt;
&lt;li&gt;(Lines 270-276) Set up the partitions on the detachable volume. The entire drive contains a single partition, which is the root. We use &lt;code dir=&quot;auto&quot;&gt;cp&lt;/code&gt; to clone the filesystem from the stock image to the detachable volume, then randomize its permanent ID and resize it to fill the new disk size.&lt;/li&gt;
&lt;li&gt;(Lines 292-301) Create a script &lt;code dir=&quot;auto&quot;&gt;/boot/hbv-kexec&lt;/code&gt; that does the actual kexec. We store this script on the bootable volume in case it needs to be customized in the future.&lt;/li&gt;
&lt;li&gt;(Lines 303-323) Create a script &lt;code dir=&quot;auto&quot;&gt;/usr/local/sbin/hbv-ephemeral-drive&lt;/code&gt; that reformats the fixed drive. We run this script on every boot. The fixed drive will contain a swap partition, and a usable “ephemeral” partition.&lt;/li&gt;
&lt;li&gt;(Lines 325-335) Create the &lt;code dir=&quot;auto&quot;&gt;hbv-ephemeral-drive&lt;/code&gt; systemd unit, which runs the script we just added.&lt;/li&gt;
&lt;li&gt;(Lines 337-343) Prepare the new filesystem for initial boot, by telling cloud-init that it has never run before, and enabling the systemd unit we created.&lt;/li&gt;
&lt;li&gt;(Lines 345-367) Perform the initial boot into the new filesystem.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;After the initial boot has completed, we perform one last task (lines 190-243): disabling most of cloud-init. Most of what cloud-init does (like running commands on “first” boot) doesn’t make sense when the volume is used on multiple servers.&lt;/p&gt;
&lt;p&gt;Once that whole process is completed, the script to create a server from the volume is pretty simple:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;Manually booting from a volume&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;hcloud server create --location nbg1 --volume my-server --name my-server \
  --image ubuntu-22.04 --type cpx51 --ssh-key my-ssh-key \
  --user-data-from-file user-data.yml
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The user data is necessary to do the kexec is simple:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;user-data.yml&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;yaml&quot;&gt;#cloud-config
bootcmd:
 - |
  set -uex
  grub-editenv /boot/grub/grubenv unset recordfail
  mount /dev/disk/by-id/scsi-0HC_Volume_${volume_id}-part1 /mnt -o ro
  for i in dev sys tmp run proc; do mount --rbind /\$i /mnt/\$i; done
  chroot /mnt /boot/hbv-kexec
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;grub-editenv&lt;/code&gt; line is necessary to fix an issue with rebooting the detachable volume. Without this GRUB thinks that the last boot failed, and so it will GRUB drop into an interactive menu for you to repair the system. The other lines simply set up a chroot, then execute the &lt;code dir=&quot;auto&quot;&gt;hbv-exec&lt;/code&gt; script we put on the detachable volume.&lt;/p&gt;
&lt;p&gt;Remember that we disabled user data on the detachable volume, so this doesn’t conflict or cause boot loops.&lt;/p&gt;
&lt;p&gt;When you are done using your server, you can use &lt;code dir=&quot;auto&quot;&gt;hcloud server delete&lt;/code&gt; to delete it.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;automatically-shutting-down-idle-servers&quot;&gt;Automatically shutting down idle servers&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The next goal is to build a daemon that will detect when the system is not in use and shut it down. This is done in two parts:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A script that monitors the system and runs &lt;code dir=&quot;auto&quot;&gt;poweroff&lt;/code&gt; when it is idle for long enough.&lt;/li&gt;
&lt;li&gt;A script that calls &lt;code dir=&quot;auto&quot;&gt;hcloud server delete&lt;/code&gt; on itself when the system is shutting down.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Before we can do this, we need to define what “idle” means. There isn’t a mouse to jiggle or a screen saver like on a laptop, but instead we can list out a few signals and monitor them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Logged in users over SSH. This can be monitored by looking at the access time (&lt;code dir=&quot;auto&quot;&gt;atime&lt;/code&gt;) on all active PTS devices (&lt;code dir=&quot;auto&quot;&gt;/dev/pts/*&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Active GUI sessions (I wrote support for this, but never use graphical sessions). This is done by running &lt;code dir=&quot;auto&quot;&gt;xprintidle&lt;/code&gt; for each user that has an X server running.&lt;/li&gt;
&lt;li&gt;A special marker file to signal a the server should be kept on. This allows you to run &lt;code dir=&quot;auto&quot;&gt;hbv-auto-shutdown caffeinate command&lt;/code&gt; and leave for the weekend, the server will just down after &lt;code dir=&quot;auto&quot;&gt;command&lt;/code&gt; finishes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The result of this is &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/1e847c10fb2e682bddcdabacf78f17dab45659ab/devserver/scripts/hbv-auto-shutdown&quot;&gt;hbv-auto-shutdown&lt;/a&gt;. Install that script to &lt;code dir=&quot;auto&quot;&gt;/usr/local/bin/&lt;/code&gt;, then add a systemd unit like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;/etc/systemd/system/hbv-auto-shutdown.service&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;systemd&quot;&gt;[Unit]
Description=&quot;Automatic Shutdown&quot;
Documentation=https://gitlab.com/CGamesPlay/dotfiles
Requires=network-online.target
After=network-online.target


[Service]
ExecStart=/usr/local/bin/hbv-auto-shutdown daemon
KillMode=process
KillSignal=SIGTERM
Restart=on-failure


[Install]
WantedBy=multi-user.target
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Activating this daemon will automatically shut down the system when it goes idle, but this will leave the server in Hetzner and it will still be billed normally. To actually delete the server, we use another simple script:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;/usr/bin/hbv-self-destruct&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;#!/bin/sh
# Immediately destroy this server
set -e
if [ &quot;$(systemctl show --property=Job poweroff.target)&quot; = &quot;Job=&quot; ]; then
    echo &quot;Aborting self destruct because system is not powering off&quot; &amp;gt;&amp;amp;2
    exit 0
fi


# Just allow the system to cool down
sleep 5
sync
hcloud server delete &quot;$(cat /var/run/cloud-init/.instance-id)&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This script first checks that we are actually powering off the server (as a safety measure), and then simply calls &lt;code dir=&quot;auto&quot;&gt;hcloud server delete&lt;/code&gt;. The systemd unit that we use merits some explanation:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;/etc/systemd/system/hbv-self-destruct.service&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;systemd&quot;&gt;# When this service *stops*, it tells hcloud to delete this machine.
[Unit]
Description=self destruct on poweroff


# We want to stop this service pretty late in the shutdown process,
# but before the network goes down. By setting
# Before=network.target, our self destruct will only happen after
# everything which is After=network.target.
Before=network.target user.slice machine.slice
# But the self destruct requires the network to actually be active.
After=systemd-networkd.service nss-lookup.target


[Service]
EnvironmentFile=-/etc/hbv-self-destruct.env
ExecStop=/usr/local/sbin/hbv-self-destruct
Type=oneshot
RemainAfterExit=yes


[Install]
WantedBy=multi-user.target
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This is a bit backward. We actually bring this unit &lt;em&gt;up&lt;/em&gt; early in the boot, immediately after the network is available (1). Since there is no &lt;code dir=&quot;auto&quot;&gt;ExecStart&lt;/code&gt; but &lt;code dir=&quot;auto&quot;&gt;RemainAfterExit&lt;/code&gt; is set, the service is marked started without doing anything else. When the service comes &lt;em&gt;down&lt;/em&gt;, which is after network.target, user.slice, and machine.slice, it invokes &lt;code dir=&quot;auto&quot;&gt;hbv-self-destruct&lt;/code&gt; (2).&lt;/p&gt;
&lt;p&gt;The last thing to do is provide your server with an API key to use for &lt;code dir=&quot;auto&quot;&gt;hcloud&lt;/code&gt;:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;echo &apos;HCLOUD_TOKEN=YOUR_HCLOUD_TOKEN&apos; &amp;gt; /etc/hbv-self-destruct.env
chmod 600 /etc/hbv-self-destruct.env
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Activate these with &lt;code dir=&quot;auto&quot;&gt;systemctl enable --now hbv-auto-shutdown&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;systemctl enable --now hbv-auto-shutdown&lt;/code&gt;.&lt;/p&gt;
&lt;aside aria-label=&quot;API Key Safety&quot;&gt;&lt;div&gt;&lt;p&gt;Hetzner does not provide fine-grained API keys: an API key gives full access to all resources in the same project. For this reason, I recommend that each bootable volume be given its own project in Hetzner with its own API key. This means that if one of your servers is compromised, none of the other resources on your Hetzner account will be compromised.&lt;/p&gt;&lt;p&gt;There is no way to attach volumes to servers created in another project, but you can manually move volumes using &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/tree/1e847c10fb2e682bddcdabacf78f17dab45659ab/devserver#migrating-hetzner-cloud-volumes&quot;&gt;this process&lt;/a&gt;.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;div&gt;&lt;h2 id=&quot;improving-performance-with-raid1&quot;&gt;Improving performance with RAID1&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Benchmarks suggest that Hetzner volumes are able to sustain about 300 MiB/s of throughput, while local disks can achieve 700 MiB/s or more. By leveraging RAID1, we can use the server’s fixed drive as a RAID mirror, which improves the read throughput to the same level as a local disk (the write throughput will remain limited).&lt;/p&gt;
&lt;p&gt;This is actually very simple to do: every boot, we reformat the local drive, then configure a RAID array with the two drives, where the detachable volume is “write mostly”, leaving the other to be used as a fast cache. The key commands are:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;mdadm --build /dev/md0 --level=1 --force --raid-devices=1 \
  --write-mostly /dev/disk/by-label/root
mdadm --grow /dev/md0 --raid-devices=2 --add /dev/disk/by-partlabel/mirror
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The second command treats the added drive as a blank slate, so Linux will immediately begin mirroring the main drive onto it, and automatically using it for faster reads once that finishes. If you want, you can check the progress:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active raid1 sda3[1] sdb1[0](W)
      157285359 blocks super non-persistent [2/1] [U_]
      [===&amp;gt;.................]  recovery = 17.7% (27984768/157285359) finish=10.5min speed=203862K/sec


unused devices: &amp;lt;none&amp;gt;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Using this RAID1 setup on the root partition is a little bit more complicated; we need to modify the initramfs to run these key commands. You can use the &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/1e847c10fb2e682bddcdabacf78f17dab45659ab/devserver/scripts/enable-raid1.sh&quot;&gt;enable-raid1&lt;/a&gt; script to do the whole process.&lt;/p&gt;
&lt;aside aria-label=&quot;Do a practice run and make a backup&quot;&gt;&lt;div&gt;&lt;p&gt;You should always make a new test server to understand how these commands work before running them on your actual server. Also, make a backup of your server before you run them so that you can recover data in case it goes wrong.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;div&gt;&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I’ve been using this iteration of &lt;code dir=&quot;auto&quot;&gt;hetzner-bootable-volume&lt;/code&gt; for 2 months now, and earlier versions of this concept for over a year. It allows me to have a completely separate development environment for each of my clients, which is especially useful when they have complex VPN requirements. By doing my development on a server in a datacenter, my docker pulls and other bandwidth-heavy activity is always fast, even when I am working over a mobile hotspot.&lt;/p&gt;
&lt;section data-footnotes=&quot;&quot;&gt;&lt;div&gt;&lt;h2 id=&quot;footnote-label&quot;&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li id=&quot;user-content-fn-pricing&quot;&gt;
&lt;p&gt;6.60 (150 GB cloud volume) + 0.088/hr (CPX51) * 160 hr/mo. Current prices can be found at &lt;a href=&quot;https://www.hetzner.com/cloud/&quot;&gt;Hetzner Pricing&lt;/a&gt;. &lt;a href=&quot;#user-content-fnref-pricing&quot; data-footnote-backref=&quot;&quot; aria-label=&quot;Back to reference 1&quot;&gt;↩&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content:encoded><category>dotfiles</category></item><item><title>Stop using em in media queries</title><link>https://cgamesplay.com/post/2023/05/19/stop-using-em-in-media-queries/</link><guid isPermaLink="true">https://cgamesplay.com/post/2023/05/19/stop-using-em-in-media-queries/</guid><description>CSS media queries are used to create responsive layouts. Conventional wisdom tells us that we should use relative font sizes to specify layout dimensions, because that improves accessibility, however this wisdom is outdated in the current browser landscape.

</description><pubDate>Fri, 19 May 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;CSS media queries are used to create responsive layouts. Conventional wisdom tells us that we should use relative font sizes to specify layout dimensions, because that improves accessibility, however this wisdom is outdated in the current browser landscape.&lt;/p&gt;
&lt;p&gt;Here’s an example of a media query in vanilla CSS:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;css&quot;&gt;/* Hide the navigation sidebar on small screens. */
#navigation-sidebar {
  display: none;
}


/* Show it on large devices. */
@media (min-width: 1024px) {
  #navigation-siderbar {
    display: block;
  }
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;You are already using media queries to design responsive layouts, either like that example, or using &lt;a href=&quot;https://tailwindcss.com/docs/responsive-design&quot;&gt;breakpoints with Tailwind CSS&lt;/a&gt; or other CSS framework, or maybe even a &lt;a href=&quot;https://mui.com/material-ui/react-use-media-query/&quot;&gt;useMediaQuery&lt;/a&gt; React hook in JS. At the end of the day, responsive designs come down to setting up breakpoints using media queries.&lt;/p&gt;
&lt;p&gt;Media queries can be specified in &lt;code dir=&quot;auto&quot;&gt;px&lt;/code&gt;, of course, but also with &lt;code dir=&quot;auto&quot;&gt;rem&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;em&lt;/code&gt; units. Conventional wisdom tells us that we should always use &lt;code dir=&quot;auto&quot;&gt;em&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;rem&lt;/code&gt; units, so that our design adapts to the user’s preferred font size. Today we’re going to reevaluate this conventional wisdom.&lt;/p&gt;
&lt;p&gt;The spec says that in a media query, “the em unit is relative to the initial value of font-size, defined by the user agent or the user’s preferences, not any styling on the page.” (&lt;a href=&quot;https://drafts.csswg.org/mediaqueries/#units&quot;&gt;Source&lt;/a&gt;). All browsers these days use 16px as the default initial font-size, although users can customize this in browser settings and with user-agent stylesheets.&lt;/p&gt;
&lt;p&gt;Up until the mid-2010s, users could also change the font size using the browser’s “zoom in” feature. However, this generally wreaked havoc on the site layout: designers wanted the sidebar to be able to fit a certain number of characters, but changing the font size without making the sidebar bigger breaks the design. This led to two things happening. The first is that developers learned that in order to create proper responsive designs, it’s necessary to use &lt;code dir=&quot;auto&quot;&gt;em&lt;/code&gt; and (later) &lt;code dir=&quot;auto&quot;&gt;rem&lt;/code&gt; units.&lt;/p&gt;
&lt;p&gt;The second thing was that browsers stopped doing the thing that broke the site layouts. These days, the browser’s “zoom in” feature actually zooms in the pixels of the page, instead of just the font size. This makes things much easier on website designers, because a zoomed in page is just the same as a smaller browser window; and it’s generally what a user expects to happen when they “zoom in”. Notice how the entire box (not just the text) gets bigger as the page zoom changes:&lt;/p&gt;
&lt;video autoplay=&quot;&quot; loop=&quot;&quot; muted=&quot;&quot; playsinline=&quot;&quot; width=&quot;640&quot; height=&quot;452&quot; style=&quot;display: block; margin: 0 auto&quot;&gt;
   &lt;source src=&quot;https://cgamesplay.com/media/20230518-1113-page-zooming.webm&quot; type=&quot;video/webm&quot;&gt;
&lt;/video&gt;
&lt;p&gt;How does this apply to media queries? In &lt;a href=&quot;https://cloudfour.com/thinks/the-ems-have-it-proportional-media-queries-ftw/&quot;&gt;the old days&lt;/a&gt;, we would definitely want to use &lt;code dir=&quot;auto&quot;&gt;em&lt;/code&gt; units, because that would come closer to emulating the full-page zoom that we wanted, but browsers didn’t give us. However, since browsers now support full page zooming, this benefit doesn’t matter. But it gets worse: not all browsers agree on the interpretation of the spec!&lt;/p&gt;
&lt;p&gt;Recall that media queries are specified to use ems “relative to the initial value of font-size, defined by the user agent or the user’s preferences”. But what does that mean? Chrome and Firefox define this as 16px (again, customizable), but Safari works differently: it’s 16px times the page zoom level. This creates an awkward situation where your media queries are zoomed more than your text is! For example, let’s look at this media query (&lt;a href=&quot;https://codepen.io/cgamesplay/pen/abRQzoZ&quot;&gt;try on CodePen&lt;/a&gt;):&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;html&quot;&gt;&amp;lt;style&amp;gt;
  body { background: #fb7185; }
  /* 40em = 640px / 16px */
  @media (min-width: 40em) {
    body { background: #22d3ee; }
  }
&amp;lt;/style&amp;gt;
&amp;lt;script&amp;gt;
  const content = document.getElementById(&quot;content&quot;);
  function update() {
    const px = window.innerWidth;
    content.innerHTML = `&amp;lt;p&amp;gt;The window is ${px}px / ${(px / 16).toFixed(2)}em wide&amp;lt;/p&amp;gt;`;
  }
  update();
  window.addEventListener(&quot;resize&quot;, update);
&amp;lt;/script&amp;gt;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Now let’s see what happens when we zoom in and out in Safari:&lt;/p&gt;
&lt;video autoplay=&quot;&quot; loop=&quot;&quot; muted=&quot;&quot; playsinline=&quot;&quot; width=&quot;640&quot; height=&quot;441&quot; style=&quot;display: block; margin: 0 auto&quot;&gt;
   &lt;source src=&quot;https://cgamesplay.com/media/20230519-0743-safari-bug.webm&quot; type=&quot;video/webm&quot;&gt;
&lt;/video&gt;
&lt;p&gt;Look at that, everything looks normal as we zoom in, keeping our page above the 40em width even after we zoom in twice. But if we refresh, we see that Safari is actually calculating the media query based on the &lt;em&gt;initial&lt;/em&gt; font size, which comes out to 800px (40em * 16px * 125%), and when we zoom back out, the media query is not reevaluated, and so the media query only applies after our browser window is zoomed out to 800px wide.&lt;/p&gt;
&lt;p&gt;Is this a bug? Probably. Safari says that a media query of 1em is the same as &lt;code&gt;16px&amp;nbsp;*&amp;nbsp;page&amp;nbsp;zoom&amp;nbsp;level&lt;/code&gt;, say, 20px at 125%. But if you made a div and specified a width of 20px, it would too wide to match the media query, since all pixels are actually 1.25 pixels large at that zoom level. I think it’s also definitely a bug that Safari isn’t recalculating these values as the page is zoomed, since no reasonable user would want the page layout to shift after refreshing the page.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;recommendations&quot;&gt;Recommendations&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;So the situation in 2023 is that all major browsers support full page zooming, which allows users to zoom in pages while preserving the developer’s layout intent. We want to respect the user’s font preferences in general, but full-page using pixel values in media queries leads to better results, due to a bug in the second-most-common web browser, with &lt;a href=&quot;https://gs.statcounter.com&quot;&gt;20% market share&lt;/a&gt;. So, you should always write media queries in pixel values, using 16px = 1em as a guide.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Always write media queries in pixel values, using 16px = 1em as a guide.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is already the consensus amongst the largest players on the web. A quick survey of how media queries are used in various frameworks and popular sites turned up this information (as of May 2023):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Frameworks: &lt;a href=&quot;https://tailwindcss.com/docs/responsive-design&quot;&gt;Tailwind CSS&lt;/a&gt;, &lt;a href=&quot;https://getbootstrap.com/docs/3.4/css/#responsive-utilities&quot;&gt;Bootstrap&lt;/a&gt;, and &lt;a href=&quot;https://mui.com/material-ui/customization/breakpoints/#default-breakpoints&quot;&gt;MUI&lt;/a&gt; all use pixel values in their responsive design queries.&lt;/li&gt;
&lt;li&gt;Popular sites: Google Search, Youtube, and Facebook all use pixel values in their media queries.&lt;/li&gt;
&lt;li&gt;Sites by “CSS experts”: MDN, CSS-Tricks, and CodePen all use pixel values in their media queries.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Overall, the accessibility situation on the web is better than ever, but unfortunately we still live in a world with browser bugs. If you want your site to render the way you intended to users with low vision, you should keep this in mind and use &lt;code dir=&quot;auto&quot;&gt;em&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;rem&lt;/code&gt; units everywhere–except your media queries. Keep those in &lt;code dir=&quot;auto&quot;&gt;px&lt;/code&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Automating an SSH session with Python</title><link>https://cgamesplay.com/post/2023/01/18/automating-an-ssh-session-with-python/</link><guid isPermaLink="true">https://cgamesplay.com/post/2023/01/18/automating-an-ssh-session-with-python/</guid><description>Learn how to automate an SSH session for a MUD game using Python, iTerm2 triggers, and asyncio, enabling bot-like functionality for character commands and interactions.

</description><pubDate>Wed, 18 Jan 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A reader of my blog recently sent me a question, and I’m going to answer them today. They wanted to get some guidance on using iTerm 2 to automate a &lt;a href=&quot;https://en.wikipedia.org/wiki/MUD&quot;&gt;MUD&lt;/a&gt;, which is basically a text-based MMORPG.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Hi Ryan, I found you through your post about &lt;a href=&quot;https://cgamesplay.com/post/2020/11/25/iterm-plugins/&quot;&gt;iTerm2 python scripting&lt;/a&gt; and would like to get your input on a project I’ve been thinking through:&lt;/p&gt;
&lt;p&gt;The project is a helper-bot for an ancient 80’s text-based adventure game that’s run over an ssh session. The game supports multiple concurrent sessions with each session controlling a character in the game.&lt;/p&gt;
&lt;p&gt;The character commands are relatively basic: say, kill, heal, cure, get, drop, follow, etc..&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I’m looking for a script that runs as a daemon that can react to commands from one player character and execute them bot-style on a second character-session.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For example: a player (IronMan) would type something in session 1 that would appear in the “bot session” as:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;IronMan says “GameBot, Heal”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The bot reads this and types into its own session:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;heal IronMan&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I’m looking to support a few different kinds of interactions, with this “heal” example being the most basic, but getting somewhat more complex for other types of interactions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Execute a command once&lt;/li&gt;
&lt;li&gt;Execute a command until told to stop&lt;/li&gt;
&lt;li&gt;Execute a command until a condition is met&lt;/li&gt;
&lt;li&gt;Any of the above, but accepting arguments to alter the bot output&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I have a background in software development, although it’s been some time since I’ve been in the thick of it (and never with Python). I’m looking for a working skeleton that I can use to further develop for this game on my own.&lt;/p&gt;
&lt;p&gt;Let me know what you think, and I’m happy to answer any further questions.&lt;/p&gt;
&lt;p&gt;Thank you,
Billy&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Thanks for the question, Billy! I think that automating programs is a widely applicable skill, both for games as well as more serious tasks. Let’s take a look at what it would take to accomplish this. We don’t have an actual MUD to test with, but we can use &lt;a href=&quot;https://github.com/shazow/ssh-chat&quot;&gt;ssh-chat&lt;/a&gt; to create an SSH-based chat room that will allow us to simulate the core idea. I just downloaded this program, and connected to it from two separate terminals to do all my testing. Here’s what it will look like:&lt;/p&gt;

&lt;div&gt;&lt;h2 id=&quot;using-iterm-2-triggers&quot;&gt;Using iTerm 2 Triggers&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The absolute simplest thing you can do actually gets you pretty close without any coding at all. &lt;a href=&quot;https://iterm2.com/triggers.html&quot;&gt;iTerm Triggers&lt;/a&gt; can automatically send text to a terminal when they receive text. Let’s create a trigger so that when we see the text “Player said: Robot, heal”, the session will automatically respond with “do action heal”. We’ll use regular expressions to make “heal” be any command. The trigger will look like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Regular Expression: &lt;code dir=&quot;auto&quot;&gt;^player: robot, (\w+)$&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Action: &lt;code dir=&quot;auto&quot;&gt;Send Text...&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Parameters: &lt;code dir=&quot;auto&quot;&gt;do action \1\r&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The regular expression will match entire lines and the command can be any single word. The parameters include &lt;code dir=&quot;auto&quot;&gt;\1&lt;/code&gt;, which will be replaced with the single word command, and the &lt;code dir=&quot;auto&quot;&gt;\r&lt;/code&gt; is the escape sequence for the return key (if you omit this, the command will be typed but not sent).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20230116-1242-trigger.png&quot; alt=&quot;Screen shot showing iTerm2 trigger configuration&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; I recommend adding this trigger to a secondary profile, rather than your default one, so that you don’t accidentally run the trigger when you aren’t using the automation.&lt;/p&gt;
&lt;p&gt;To test it, I’ve got ssh-chat opened twice, side by side, with the “robot” profile on the left and my normal one on the right. When I type “robot, heal” on the right, the left terminal detects it and automatically responds.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20230116-1242-nc.png&quot; alt=&quot;Chat transcript between the player and robot sessions&quot;&gt;&lt;/p&gt;
&lt;p&gt;And we’re done! If you use your new bot profile and connect to the game, whenever it sees a string matching the regular expression, it will respond with the desired command.&lt;/p&gt;
&lt;p&gt;Unfortunately, this approach can’t be expanded upon. We can’t repeat the command, or add delays, and the arguments are limited to what we capture with the regular expression. To go further, we’ll switch to Python.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;writing-a-bot&quot;&gt;Writing a bot&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;To take this to the next level, let’s write a bot. It will be a Python script that receives the game’s output, and sends commands back to the game. Here’s an initial version:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;#!/usr/bin/env python3
import sys, re




def clean_line(line):
    &quot;&quot;&quot;
    Clean up escape codes and extra spaces in the line.
    &amp;gt;&amp;gt;&amp;gt; clean_line(&apos;\x1b[38;05;173mplayer\x1b[0m: robot, heal &apos;)
    &apos;player: robot, heal&apos;
    &quot;&quot;&quot;
    return re.sub(r&quot;\x1b\[[0-9;]*[a-zA-Z]|\x07&quot;, &quot;&quot;, line).strip()




def send_command(line):
    &quot;Send a command to the SSH session.&quot;
    # \r is the character code for a return. The default end is \n.
    print(line, end=&quot;\r&quot;)
    sys.stdout.flush()




def main():
    try:
        while True:
            line = clean_line(input())
            # For debugging, print every line exactly as it is received.
            print(repr(line), file=sys.stderr)
            m = re.match(r&quot;^\[robot\] player: robot, (\w+)$&quot;, line)
            if m is not None:
                send_command(f&quot;do action {m[1]}&quot;)
    except EOFError:
        pass




if __name__ == &quot;__main__&quot;:
    main()
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;We can test it by running it ourselves:&lt;/p&gt;

&lt;p&gt;When we type “player: robot, heal” (which is what the robot would see if we typed it into the game), the robot responds by writing “do action heal” on a new line. Note that because the robot ends commands with &lt;code dir=&quot;auto&quot;&gt;\r&lt;/code&gt;, the cursor will be on the same line as the robot’s output and you’ll type over it, but this is not an issue. How do we hook this up to SSH?&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;standard-unix-tools&quot;&gt;Standard UNIX tools&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;We actually don’t need to write an iTerm 2 plugin to finish this automation. In fact, we don’t need to use iTerm2 at all, although iTerm2 does provide a nice feature that we will use later on. For now, what we want to do is write a program that will &lt;strong&gt;read from the game&lt;/strong&gt; and &lt;strong&gt;send commands back&lt;/strong&gt; to it. We’ll need some way to tie the two programs together. There’s &lt;a href=&quot;https://unix.stackexchange.com/questions/53641/how-to-make-bidirectional-pipe-between-two-programs&quot;&gt;lots of ways&lt;/a&gt; to do this, but the easiest way is to use a named pipe, aka a FIFO (which stands for “first-in, first-out”). What’s a named pipe? We use &lt;em&gt;anonymous&lt;/em&gt; pipes all the time, for example &lt;code dir=&quot;auto&quot;&gt;echo | cat&lt;/code&gt; creates an anonymous pipe that takes the output of echo and sends it to cat. Our bot could work like that as well: if we ran &lt;code dir=&quot;auto&quot;&gt;ssh | bot.py&lt;/code&gt; then the bot would receive all of the game’s output. But to send the game input, we need the pipe to go both ways, and anonymous pipes can’t do that. A &lt;em&gt;named&lt;/em&gt; pipe is a special file that works just like a pipe: nothing can be written to it until another program is reading from it, and the written data will immediately be sent to the reading program.&lt;/p&gt;
&lt;p&gt;Let’s create a named pipe called &lt;code dir=&quot;auto&quot;&gt;bot-output&lt;/code&gt;, which will receive the bot’s output, and then send that named pipe to SSH. It looks something like this, where we send the bot’s output into SSH and SSH’s output into the bot. We have to use &lt;code dir=&quot;auto&quot;&gt;&amp;gt;&amp;gt;&lt;/code&gt; to avoid deleting the FIFO and replacing it with a regular file.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ mkfifo bot-output
$ cat bot-output | ssh ... | ./bot.py &amp;gt;&amp;gt; bot-output
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Here’s how it works:&lt;/p&gt;

&lt;p&gt;As you can see, the robot doesn’t see the same lines that we do, because of terminal escape codes. We have to filter them out, but sometimes lines come in jumbled and duplicated. Notably, the robot’s prompt (&lt;code dir=&quot;auto&quot;&gt;[robot]&lt;/code&gt;) is always at the start of every input line.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;more-advanced-automation&quot;&gt;More advanced automation&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Now that we have a custom Python program, we can take this however far we want. I’m going to show a simple example of repeating a line until told to stop. But there’s an important problem here: we need to do multiple things at once. Namely, we need to output lines on a schedule, but we also need to read lines to identify the stop command. There are two main ways we can approach this: threads, and asynchronous events. Threads are very useful, but come with many subtle caveats, and Python’s asynchronous framework is quite good, so we will use that.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;#!/usr/bin/env python3
import sys, re, asyncio


# Omitting clean_line and send_command for brevity, they have not changed.


# Adapted from https://stackoverflow.com/a/64317899/123899
async def connect_stdin():
    loop = asyncio.get_event_loop()
    reader = asyncio.StreamReader()
    protocol = asyncio.StreamReaderProtocol(reader)
    await loop.connect_read_pipe(lambda: protocol, sys.stdin)
    return reader




async def do_heal(person):
    while True:
        send_command(f&quot;heal {person}&quot;)
        await asyncio.sleep(2)




async def main():
    stdin = await connect_stdin()
    task = None
    try:
        while True:
            # Our stream returns bytes, so we will decode it to a str now.
            line = clean_line((await stdin.readline()).decode(&quot;utf-8&quot;))
            # For debugging, print every line exactly as it is received.
            print(repr(line), file=sys.stderr)
            if re.match(r&quot;^\[robot\] player: robot, heal me$&quot;, line) is not None:
                task = asyncio.create_task(do_heal(&quot;player&quot;))
            elif re.match(r&quot;^\[robot\] player: robot, stop$&quot;, line) is not None:
                if task is not None:
                    task.cancel()
                    task = None
    except EOFError:
        pass




if __name__ == &quot;__main__&quot;:
    asyncio.run(main())
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;By using &lt;code dir=&quot;auto&quot;&gt;asyncio.create_task&lt;/code&gt;, we can have the robot run a process while it’s waiting for more commands, like repeating a command. Here is a demo of our new bot in action:&lt;/p&gt;

&lt;p&gt;OK Billy, hopefully this is a good skeleton for you to take and run with! This technique is useful for a wide variety of automations, and there are a lot of tools and libraries that provide different approaches. Here are a few:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If you have a simple script that you need to send to a program, the &lt;a href=&quot;https://linux.die.net/man/1/expect&quot;&gt;expect&lt;/a&gt; program can handle it. It has a simple scripting language included, but it’s not as advanced as Python.&lt;/li&gt;
&lt;li&gt;If you’re automating SSH specifically, you can use &lt;a href=&quot;https://www.paramiko.org&quot;&gt;Paramiko&lt;/a&gt; to handle the SSH connection directly in Python instead of using a FIFO as we did here. This allows a deeper integration (for example, reconnecting automatically), but means you have to configure the entire SSH connection from Python, which may be more difficult to use.&lt;/li&gt;
&lt;li&gt;You can also use &lt;code dir=&quot;auto&quot;&gt;tmux pipe-pane&lt;/code&gt; to connect an existing tmux pane to a shell script, which might be easier than manually creating a FIFO.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Finally, since I promised more iTerm2 goodness, let’s look at how we can use the bot we wrote without manually creating FIFOs using another iTerm 2 feature.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;using-iterm2-coprocesses&quot;&gt;Using iTerm2 Coprocesses&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;iTerm2 supports &lt;a href=&quot;https://iterm2.com/documentation-coprocesses.html&quot;&gt;Coprocesses&lt;/a&gt;, which basically does exactly what we did with pipes, except built in to iTerm2. It’s a little bit harder to debug a coprocess than a simple shell script, so I recommend using this once you already have your script working.&lt;/p&gt;
&lt;p&gt;To actually use the coprocess, we’ll take the exact bot script we wrote above, and find its full path. Then we put that path into Session -&amp;gt; Run Coprocess. iTerm2 shows an icon in the affected terminal, but otherwise it’s invisible. Here’s what it looks like:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20230116-1242-coprocess.png&quot; alt=&quot;An iTerm2 session running a coprocess&quot;&gt;&lt;/p&gt;
&lt;p&gt;You can see the icon in the corner of the robot’s terminal that shows that iTerm2 is running the coprocess. The output is certainly easier to read when using a coprocess, since you see the screen normally, but there is no error output (unless the coprocess crashes), so I find it harder to debug. If you combined this with a log file and automatic re-running, it might be better than other methods.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Future automation idea:&lt;/strong&gt; It’s also possible to set up a trigger to automatically start a coprocess. You could use this to complete a lengthy login step, by having the trigger detect when you are attempting to log in to a service.&lt;/p&gt;
</content:encoded></item><item><title>Creating my personal cloud with HashiCorp</title><link>https://cgamesplay.com/post/2021/10/27/creating-my-personal-cloud-with-hashicorp/</link><guid isPermaLink="true">https://cgamesplay.com/post/2021/10/27/creating-my-personal-cloud-with-hashicorp/</guid><description>I maintain a VPS which I use to self-host a variety of services that I use: Joplin Server, Seafile, as well as for hosting websites that I develop. For the past few years, that VPS has been managed with Docker Compose, but recently I decided to build something a bit bigger.

</description><pubDate>Wed, 27 Oct 2021 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I maintain a VPS which I use to self-host a variety of services that I use: &lt;a href=&quot;https://joplinapp.org&quot;&gt;Joplin&lt;/a&gt; Server, &lt;a href=&quot;https://www.seafile.com&quot;&gt;Seafile&lt;/a&gt;, as well as for hosting websites that I develop. For the past few years, that VPS has been managed with Docker Compose, but recently I decided to build something a bit bigger. My goals with the project:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I want to be able to deploy closed-source projects in a completely self-hosted manner. This means self-hosting a Docker registry.&lt;/li&gt;
&lt;li&gt;I want to run 1 node, but with the option to scale to multiple without changing my infrastructure. This means I’m going to be using a cluster manager scaled to one node.&lt;/li&gt;
&lt;li&gt;I want a highly-secure way to store secrets on the server (for example, TOTP secrets with an audit trail). I decided early on that &lt;a href=&quot;http://vaultproject.io&quot;&gt;Vault&lt;/a&gt; was the right way to handle this.&lt;/li&gt;
&lt;li&gt;I want the setup process to be fully automatic. Basically, I want Infrastructure-as-Code, so if I have to recreate the server for any reason, I can do so consistently.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I decided to use &lt;a href=&quot;http://nomadproject.io&quot;&gt;Nomad&lt;/a&gt; to implement these features, and the fruits of my labor are open sourced here: &lt;a href=&quot;https://github.com/CGamesPlay/infra&quot;&gt;CGamesPlay/infra&lt;/a&gt;. If you are looking for a home-lab setup for this stack, I recommend checking it out. The software stack is certainly much more complicated, but the HashiCorp stack is much simpler than the Kubernetes stack and I’m very happy with how easy everything turned out to be, after spending the time to properly acquaint myself with the docs.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;how-does-it-work&quot;&gt;How does it work?&lt;/h2&gt;&lt;/div&gt;
&lt;!--
I decided that I won&apos;t want to deal with installing Chrome to prerender my
website. The SVG here doesn&apos;t actually render correctly. It would be good to
find a better solution in the future.

```mermaid
flowchart TD
  prepare(1. Configure services locally)
  tf(2. Create a new VM with Terraform)
  install(3. Generate and run the installation script)
  nomad(4. Upload jobs to Nomad)
  prepare -- &gt; install
  tf -- &gt; install -- &gt; nomad
```
---&gt;
&lt;p&gt;&lt;svg aria-roledescription=&quot;flowchart-v2&quot; role=&quot;graphics-document document&quot; viewBox=&quot;-8 -8 634 304&quot; style=&quot;max-width: 100%;&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;100%&quot; id=&quot;graph-div&quot; height=&quot;100%&quot;&gt;&lt;g&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;8&quot; markerWidth=&quot;8&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5&quot; refX=&quot;5&quot; viewBox=&quot;0 0 10 10&quot; id=&quot;graph-div_flowchart-v2-pointEnd&quot;&gt;&lt;path style=&quot;stroke-width: 1; stroke-dasharray: 1, 0;&quot; d=&quot;M 0 0 L 10 5 L 0 10 z&quot;&gt;&lt;/path&gt;&lt;/marker&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;8&quot; markerWidth=&quot;8&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5&quot; refX=&quot;4.5&quot; viewBox=&quot;0 0 10 10&quot; id=&quot;graph-div_flowchart-v2-pointStart&quot;&gt;&lt;path style=&quot;stroke-width: 1; stroke-dasharray: 1, 0;&quot; d=&quot;M 0 5 L 10 10 L 10 0 z&quot;&gt;&lt;/path&gt;&lt;/marker&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;11&quot; markerWidth=&quot;11&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5&quot; refX=&quot;11&quot; viewBox=&quot;0 0 10 10&quot; id=&quot;graph-div_flowchart-v2-circleEnd&quot;&gt;&lt;circle style=&quot;stroke-width: 1; stroke-dasharray: 1, 0;&quot; r=&quot;5&quot; cy=&quot;5&quot; cx=&quot;5&quot;&gt;&lt;/circle&gt;&lt;/marker&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;11&quot; markerWidth=&quot;11&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5&quot; refX=&quot;-1&quot; viewBox=&quot;0 0 10 10&quot; id=&quot;graph-div_flowchart-v2-circleStart&quot;&gt;&lt;circle style=&quot;stroke-width: 1; stroke-dasharray: 1, 0;&quot; r=&quot;5&quot; cy=&quot;5&quot; cx=&quot;5&quot;&gt;&lt;/circle&gt;&lt;/marker&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;11&quot; markerWidth=&quot;11&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5.2&quot; refX=&quot;12&quot; viewBox=&quot;0 0 11 11&quot; id=&quot;graph-div_flowchart-v2-crossEnd&quot;&gt;&lt;path style=&quot;stroke-width: 2; stroke-dasharray: 1, 0;&quot; d=&quot;M 1,1 l 9,9 M 10,1 l -9,9&quot;&gt;&lt;/path&gt;&lt;/marker&gt;&lt;marker orient=&quot;auto&quot; markerHeight=&quot;11&quot; markerWidth=&quot;11&quot; markerUnits=&quot;userSpaceOnUse&quot; refY=&quot;5.2&quot; refX=&quot;-1&quot; viewBox=&quot;0 0 11 11&quot; id=&quot;graph-div_flowchart-v2-crossStart&quot;&gt;&lt;path style=&quot;stroke-width: 2; stroke-dasharray: 1, 0;&quot; d=&quot;M 1,1 l 9,9 M 10,1 l -9,9&quot;&gt;&lt;/path&gt;&lt;/marker&gt;&lt;g&gt;&lt;g&gt;&lt;/g&gt;&lt;g&gt;&lt;path marker-end=&quot;url(#graph-div_flowchart-v2-pointEnd)&quot; style=&quot;&quot; id=&quot;L_prepare_install_0&quot; d=&quot;M148,68L148,72.167C148,76.333,148,84.667,159.868,92.789C171.735,100.912,195.47,108.823,207.338,112.779L219.205,116.735&quot;&gt;&lt;/path&gt;&lt;path marker-end=&quot;url(#graph-div_flowchart-v2-pointEnd)&quot; style=&quot;&quot; id=&quot;L_tf_install_1&quot; d=&quot;M478,68L478,72.167C478,76.333,478,84.667,466.132,92.789C454.265,100.912,430.53,108.823,418.662,112.779L406.795,116.735&quot;&gt;&lt;/path&gt;&lt;path marker-end=&quot;url(#graph-div_flowchart-v2-pointEnd)&quot; style=&quot;&quot; id=&quot;L_install_nomad_2&quot; d=&quot;M313,178L313,182.167C313,186.333,313,194.667,313,202.333C313,210,313,217,313,220.5L313,224&quot;&gt;&lt;/path&gt;&lt;/g&gt;&lt;g&gt;&lt;g&gt;&lt;g transform=&quot;translate(0, 0)&quot;&gt;&lt;foreignObject height=&quot;0&quot; width=&quot;0&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;g&gt;&lt;g transform=&quot;translate(0, 0)&quot;&gt;&lt;foreignObject height=&quot;0&quot; width=&quot;0&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;g&gt;&lt;g transform=&quot;translate(0, 0)&quot;&gt;&lt;foreignObject height=&quot;0&quot; width=&quot;0&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;g&gt;&lt;g transform=&quot;translate(148, 38)&quot; id=&quot;flowchart-prepare-63&quot;&gt;&lt;rect height=&quot;60&quot; width=&quot;280&quot; y=&quot;-30&quot; x=&quot;-140&quot; ry=&quot;5&quot; rx=&quot;5&quot; style=&quot;&quot;&gt;&lt;/rect&gt;&lt;g transform=&quot;translate(-125, -15)&quot; style=&quot;&quot;&gt;&lt;rect&gt;&lt;/rect&gt;&lt;foreignObject height=&quot;30&quot; width=&quot;250&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;p&gt;1. Configure services locally&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;g transform=&quot;translate(478, 38)&quot; id=&quot;flowchart-tf-64&quot;&gt;&lt;rect height=&quot;60&quot; width=&quot;280&quot; y=&quot;-30&quot; x=&quot;-140&quot; ry=&quot;5&quot; rx=&quot;5&quot; style=&quot;&quot;&gt;&lt;/rect&gt;&lt;g transform=&quot;translate(-125, -15)&quot; style=&quot;&quot;&gt;&lt;rect&gt;&lt;/rect&gt;&lt;foreignObject height=&quot;30&quot; width=&quot;250&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;p&gt;2. Create a new VM with Terraform&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;g transform=&quot;translate(313, 148)&quot; id=&quot;flowchart-install-65&quot;&gt;&lt;rect height=&quot;60&quot; width=&quot;280&quot; y=&quot;-30&quot; x=&quot;-140&quot; ry=&quot;5&quot; rx=&quot;5&quot; style=&quot;&quot;&gt;&lt;/rect&gt;&lt;g transform=&quot;translate(-125, -15)&quot; style=&quot;&quot;&gt;&lt;rect&gt;&lt;/rect&gt;&lt;foreignObject height=&quot;30&quot; width=&quot;250&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;p&gt;3. Generate and run the installation script&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;g transform=&quot;translate(313, 258)&quot; id=&quot;flowchart-nomad-66&quot;&gt;&lt;rect height=&quot;60&quot; width=&quot;252.05078125&quot; y=&quot;-30&quot; x=&quot;-126.025390625&quot; ry=&quot;5&quot; rx=&quot;5&quot; style=&quot;&quot;&gt;&lt;/rect&gt;&lt;g transform=&quot;translate(-111.025390625, -15)&quot; style=&quot;&quot;&gt;&lt;rect&gt;&lt;/rect&gt;&lt;foreignObject height=&quot;30&quot; width=&quot;222.05078125&quot;&gt;&lt;div style=&quot;display: table-cell; white-space: nowrap; line-height: 1.5; max-width: 200px; text-align: center;&quot; xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;span&gt;&lt;p&gt;4. Upload jobs to Nomad&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;/foreignObject&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;/svg&gt;&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;1-configure-services-locally&quot;&gt;1. Configure services locally&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;I started by configuring the services locally, so that I can easily make adjustments and learn how everything works. Specifically, I run Vault, Consul, and Nomad on my workstation and configure them as I like. Making changes locally is many times faster than making the changes to remote cloud infrastructure, and this allowed me to learn about the HashiCorp stack quickly. Once I had the services working locally the way I wanted, I wrote a script that could configure them that way from scratch again. Again, by developing this locally, it was many times faster than ddeveloping an equivalent script on remote infrastructure. The final product of this is in &lt;a href=&quot;https://github.com/CGamesPlay/infra/blob/8649f4d8856dedfab201f3c6f5135c99467d24bd/bootstrap/prepare.sh&quot;&gt;&lt;code dir=&quot;auto&quot;&gt;bootstrap/prepare.sh&lt;/code&gt;&lt;/a&gt;. This script will set up these 3 services (and also do some preparation for WireGuard), and store all of the configuration in a local directory, ready to be transferred to a VM.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;2-create-a-new-vm-with-terraform&quot;&gt;2. Create a new VM with Terraform&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;To actually create the infrastructure, we use  &lt;a href=&quot;http://terraform.io&quot;&gt;Terraform&lt;/a&gt;. I went with Terraform because I needed cross-cloud capability (AWS and &lt;a href=&quot;https://www.hetzner.com/cloud&quot;&gt;Hetzner Cloud&lt;/a&gt; in my case). I’m also a big fan of &lt;a href=&quot;https://www.pulumi.com&quot;&gt;Pulumi&lt;/a&gt;, but the infrastructure requirements I have are so simple that Terraform made more sense. This step generates a blank VM with software dependencies installed but not configured.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;3-generate-and-run-the-installation-script&quot;&gt;3. Generate and run the installation script&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;In previous cloud provisioning projects I have written scripts that would perform remote installations of software. In this project, I opted for a different approach for this project which made things much easier: generating an installation script and allowing the user to run it themselves. Basically, I have a bash script that outputs a second bash script that configures the software. This massively sped up development for me because I could inspect the generated script without running it, and then manually copy and paste commands into an SSH session, fixing any errors incrementally. Of course, once I was sure everything was working, I simply piped the generation script into an ssh session, and the process became completely automatic. The generator script is in &lt;a href=&quot;https://github.com/CGamesPlay/infra/blob/8649f4d8856dedfab201f3c6f5135c99467d24bd/bootstrap/generate_installer.sh&quot;&gt;&lt;code dir=&quot;auto&quot;&gt;bootstrap/generate_installer.sh&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;4-upload-jobs-to-nomad&quot;&gt;4. Upload jobs to Nomad&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;After those steps are completed, the server is online and ready to accept jobs. At this point I use plain Nomad jobs to set up &lt;a href=&quot;https://github.com/CGamesPlay/infra/tree/8649f4d8856dedfab201f3c6f5135c99467d24bd/nomad/traefik&quot;&gt;Traefik&lt;/a&gt;, the &lt;a href=&quot;https://github.com/CGamesPlay/infra/tree/8649f4d8856dedfab201f3c6f5135c99467d24bd/nomad/registry&quot;&gt;private Docker registry&lt;/a&gt;, and whatever else I want to run. I have a script (&lt;a href=&quot;https://github.com/CGamesPlay/infra/blob/8649f4d8856dedfab201f3c6f5135c99467d24bd/scripts/levant.sh&quot;&gt;&lt;code dir=&quot;auto&quot;&gt;scripts/levant.sh&lt;/code&gt;&lt;/a&gt;) that uses &lt;a href=&quot;https://github.com/hashicorp/levant&quot;&gt;Levant&lt;/a&gt; and iterates over all of my configured jobs, applying any changes automatically.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;how-does-it-feel-6-months-in&quot;&gt;How does it feel, 6 months in?&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;To me, the best test of my personal projects are if they still feel usable after 6 months of use. By this time, most of the context that I learned to develop the project has faded away and I have to rely on the documentation that I left myself. In this case, I think this project has been a great success. It’s easy for me to set up new services using the existing Nomad jobspecs as guidance, and I feel much more confident doing so than I did with docker-compose files. One of my favorite features of the new system is &lt;code dir=&quot;auto&quot;&gt;nomad job plan&lt;/code&gt;. This allows me to see what the system will do wtih my jobspec without actually doing it, and this gives me a lot of confidence that the change I am making right now doesn’t accidentally undo any manual changes I made before but forgot to properly add to the jobspec. Also, I feel much more confident editing HCL files than YAML files. In YAML, I am constantly worrying that a string will be interpreted as a different data type, or that an array-of-objects will interpreted as an array-of-arrays, etc.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;what-are-my-next-steps&quot;&gt;What are my next steps?&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I have a few ideas for features I’d like to add to this project:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Scaling to multiple machines is the obvious one. I’d like to be able to automatically scale up different machine configurations based on the jobspecs I’m running. For example, I want to be able to deploy a batch job that requires a GPU instance, and have the instance created and destroyed automatically.&lt;/li&gt;
&lt;li&gt;Scaling services to zero is another project I’d like to try. Basically, I want to automatically shut down certain jobs that aren’t receiving web traffic, and automatically start them up when they get a request, similar to how Heroku works. I haven’t seen any self hosted implementations of this, but I have some ideas around how it can be accomplished.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;But for now I’m happy using the system that I’ve built. I hope the code being open sourced is useful to others. If you find yourself working on up something like what I’ve done here, feel free to &lt;a href=&quot;https://cgamesplay.com/contact&quot;&gt;reach out to me&lt;/a&gt; and let me know!&lt;/p&gt;
</content:encoded><category>infra</category></item><item><title>Useful notifications in iTerm2</title><link>https://cgamesplay.com/post/2020/12/09/iterm-notifications/</link><guid isPermaLink="true">https://cgamesplay.com/post/2020/12/09/iterm-notifications/</guid><description>For some reason, I&apos;ve found that in my career a lot of the work I do ends up involving slow REPL loops: I make a change, run a command, wait for it to finish, and repeat. While I&apos;m sitting there waiting, it&apos;s easy to be distracted by things, and I want my task to bring itself back to my attention when it&apos;s ready. This desire has led me on a multi-year quest to tailor my notifications perfectly, and in this post I&apos;m going to share what I&apos;ve come up with.

</description><pubDate>Wed, 09 Dec 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;For some reason, I’ve found that in my career a lot of the work I do ends up involving slow REPL loops: I make a change, run a command, wait for it to finish, and repeat. While I’m sitting there waiting, it’s easy to be distracted by things, and I want my task to bring itself back to my attention when it’s ready. This desire has led me on a multi-year quest to tailor my notifications perfectly, and in this post I’m going to share what I’ve come up with.&lt;/p&gt;
&lt;aside aria-label=&quot;Skip the cutscene&quot;&gt;&lt;div&gt;&lt;p&gt;If you just want scripts you can copy/paste, you should go here: &lt;a href=&quot;https://cgamesplay.com/recipes/iterm2/#notifications&quot;&gt;iTerm2 Tips &amp;amp; Tricks: Notifications&lt;/a&gt;!&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;Here are the features I want my notifications to have:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I should be able to activate them from anywhere in the terminal: in bash, from the ruby console, over SSH, or anywhere else I find myself (in the terminal).&lt;/li&gt;
&lt;li&gt;They should be subtle so they don’t get too annoying, but noticeable enough that I don’t miss them.&lt;/li&gt;
&lt;li&gt;The should only fire when I want them: too many notifications will cause me to ignore all of them.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;h2 id=&quot;the-early-days&quot;&gt;The early days&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Back in 2015 or so, my company was writing scrapers to extract detailed, structured information from hundreds of websites. Each website was different and since we needed the information to be structured, we had to write a different scraper for each one. A single site could be scraped in about 5 minutes, and the data only changed a few times each year. Still, the sites would change often enough that I frequently found myself sitting in the office until late at night, mostly waiting for these scrapers to break so I could make one small fix, and repeat. Five minutes for each change really adds up when you have to repeat the entire scraper to test a single-line change.&lt;/p&gt;
&lt;p&gt;Fortunately, writing scrapers is pretty easy technically, so I didn’t need to be 100% focused as I was working on them. That meant that while I was waiting on the latest change I’d made to a scraper, I was able to focus on other high-value activities like shooting for a high score in Peggle Nights.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201201-1309-peggle-small.jpg&quot; alt=&quot;Screenshot of Peggle Nights&quot;&gt;&lt;/p&gt;
&lt;p&gt;But sometimes, when I was planning a tough shot on a high-scoring round, I could forget that I was still at the office waiting for my scraper to crash so I could fix it. That’s why I wanted a simple way to get notified when it was waiting for me. My first-ever attempt at building a notifications system used a feature built-in to Mac OS: the &lt;code dir=&quot;auto&quot;&gt;say&lt;/code&gt; command.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;long_running_command; say &quot;done&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This command uses the system’s text-to-speech to play through your computer speakers. The scrapers I was writing were mostly in Ruby, so if I were in IRB I could still get the notification:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;ruby&quot;&gt;my_scraper.run_main rescue ex = $!; `say done`
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This will play the notification even if the scraper fails, and preserve the raised exception in the &lt;code dir=&quot;auto&quot;&gt;ex&lt;/code&gt; variable. Neat!&lt;/p&gt;
&lt;p&gt;I used this solution for a few months, but I always felt that the text-to-speech was a little unpleasant. I decided to switch out the &lt;code dir=&quot;auto&quot;&gt;say&lt;/code&gt; command for the built-in audio file player, &lt;code dir=&quot;auto&quot;&gt;afplay&lt;/code&gt;, and I used one of the default sounds that comes with Mac OS.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;function ding {
  afplay /System/Library/Sounds/Glass.aiff
}
long_running_command; ding
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;That makes this sound, which is a little more subtle than a robotic voice shouting at me.&lt;/p&gt;
&lt;p&gt;&lt;audio controls=&quot;&quot; src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-sounds-glass.aiff&quot;&gt;&lt;a href=&quot;https://cgamesplay.com/media/20201125-1600-iterm-sounds-glass.aiff&quot;&gt;Click to download&lt;/a&gt;&lt;/audio&gt;&lt;/p&gt;
&lt;p&gt;These two tricks got me along just fine for years. I felt like I had solved the problem and didn’t need to think about it any more. Well, except when I started a command that I thought would be fast but it instead took an hour to run. But I developed a trick for that: if you press &lt;code dir=&quot;auto&quot;&gt;^Z&lt;/code&gt; (Ctrl-Z) to pause the job, then you can use &lt;code dir=&quot;auto&quot;&gt;fg; ding&lt;/code&gt; to resume it  and ding when it finishes. There. Now it’s perfect.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;improving-on-perfection&quot;&gt;Improving on perfection&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;One day I learned about &lt;a href=&quot;https://iterm2.com/documentation-shell-integration.html&quot;&gt;iTerm2 shell integration&lt;/a&gt;. This provides a bunch of neat features, and one of them is about notifications! It’s not very well documented, but if you use Edit › Marks and Annotations › Alerts › Alert on Next Mark, or the much-easier-to-remember Option-Command-A, you’ll get a native notification when the currently running command finishes. I installed the shell integration and to this day I use this feature more than anything else that it provides.&lt;/p&gt;
&lt;p&gt;Fast forward to 2020 and I’ve changed roles again. This time, I find myself automating cloud server provisioners, and waiting for the machines to come up isn’t fast. Sadly, the iTerm shell integration has to be installed on each server, and my perfect notification scripts don’t work over SSH. Realizing that perfection is a journey and not a destination, I set out to improve my notifications once again. Except this time, I was going to go industrial-strength.&lt;/p&gt;
&lt;p&gt;When I was learning about the iTerm2 shell integration, I also found out about &lt;a href=&quot;https://cgamesplay.com/post/2020/11/25/iterm-plugins/&quot;&gt;a bunch of other features that iTerm2 supports&lt;/a&gt;. If you want to follow along with me, read over that post and install &lt;code dir=&quot;auto&quot;&gt;PlaySound.py&lt;/code&gt;, &lt;code dir=&quot;auto&quot;&gt;iterm_notify&lt;/code&gt;, &lt;code dir=&quot;auto&quot;&gt;iterm_badge&lt;/code&gt;, and &lt;code dir=&quot;auto&quot;&gt;iterm_bounce&lt;/code&gt; on your computer. These new features had already made my notifications more powerful and SSH-compatible, but I had set my sights beyond a simple “ding!” sound. I wanted a smart notification system that would “ding” when the command completed, but “bonk” when it failed. But first I needed to find the right sounds to use.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201201-1344-oot-navi.jpg&quot; alt=&quot;The Legend of Zelda: Ocarina of Time&quot;&gt;&lt;/p&gt;
&lt;p&gt;The first sound that came to mind was the iconic “Hey! Listen!” from Ocarina of Time. If you played this game, then you probably know exactly how that sounds. I found a gallery of &lt;a href=&quot;http://noproblo.dayjo.org/ZeldaSounds/&quot;&gt;sounds from the Zelda games&lt;/a&gt; and searched for some appropriate ones. Eventually I settled on these two, for my “good” and “bad” sounds:&lt;/p&gt;
&lt;p&gt;&lt;audio controls=&quot;&quot; src=&quot;https://cgamesplay.com/media/20201201-1347-ootpressstart.wav&quot;&gt;&lt;a href=&quot;https://cgamesplay.com/media/20201201-1347-ootpressstart.wav&quot;&gt;Click to download&lt;/a&gt;&lt;/audio&gt;&lt;/p&gt;
&lt;p&gt;&lt;audio controls=&quot;&quot; src=&quot;https://cgamesplay.com/media/20201201-1349-mmtatlalarm.wav&quot;&gt;&lt;a href=&quot;https://cgamesplay.com/media/20201201-1349-mmtatlalarm.wav&quot;&gt;Click to download&lt;/a&gt;&lt;/audio&gt;&lt;/p&gt;
&lt;p&gt;The first thing to do is wrap them up in scripts to make them easy to use. I put them in my sound library (which is listing in &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/bee7d071a7b85f7becc696edc0b328677eb16c40/macos/Library/Application%20Support/iTerm2/Scripts/AutoLaunch/PlaySound.py&quot;&gt;PlaySound.py&lt;/a&gt;) and wrote these:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;function ding {
    iterm_sound OOT_PressStart
}


function bonk {
    iterm_sound MM_Tatl_Alarm.wav
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Now I can run my provisioning script like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;./provision.sh &amp;amp;&amp;amp; ding || bonk
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If the script succeeds, the &lt;code dir=&quot;auto&quot;&gt;&amp;amp;&amp;amp; ding&lt;/code&gt; will run, resulting in a pleasant chime. Otherwise the &lt;code dir=&quot;auto&quot;&gt;|| bonk&lt;/code&gt; sound will run and I’ll hear a nervous fairy. But I can do better! This is too much to type, and I want to leverage all of my notification channels, not just sound. So I wrote this function:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;function sound_status {
    local last_status=$?
    test $last_status -eq 0 &amp;amp;&amp;amp; ding || bonk
    iterm_bounce
    if test -z &quot;$@&quot;; then
        iterm_notify &quot;Command finished with status $last_status&quot;
    else
        iterm_notify &quot;$@ finished with status $last_status&quot;
    fi
    return $last_status
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This function has 3 important qualities:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It automatically chooses the sound to play.&lt;/li&gt;
&lt;li&gt;It also shows a system notification, with an optional custom message.&lt;/li&gt;
&lt;li&gt;It passes on the exit code, so you can run it in a pipeline.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For example, I can use it like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;./provision.sh; sound_status &quot;provision.sh&quot; &amp;amp;&amp;amp; ssh myhost
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Because it passes on the exit status, the &lt;code dir=&quot;auto&quot;&gt;&amp;amp;&amp;amp; ssh&lt;/code&gt; will only happen when the command succeeds, just like if the &lt;code dir=&quot;auto&quot;&gt;; sound_status&lt;/code&gt; hadn’t been there at all.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;the-little-things-in-life&quot;&gt;The little things in life&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;This notification script feels great: simple, only when requested, and with just a bit of “fun” flavor. But there is another area where I think that a subtle audio cue would help streamline my workflow. Sometimes I need to type 3 or 4 quick commands back-to-back. Has this ever happened to you?&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ git commit -m &quot;respond to feedback&quot;
no changes added to commit (use &quot;git add&quot; and/or &quot;git commit -a&quot;)
$ git push
Everything up-to-date
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;I run these commands, see that it succeeded, shut my laptop, and head out to lunch. Later that day I wonder why nobody has reviewed my code, only to find that the second command had failed because I never staged those files, so I never pushed any changes at all. If I had been more careful, this wouldn’t have happened. As a substitute for being more careful, I can have the computer tell me when my commands fail!&lt;/p&gt;
&lt;p&gt;When I want is a subtle ping to tell me that something bad happened, every time a command fails. A lot of times this notification will be unnecessary. For example, if  &lt;code dir=&quot;auto&quot;&gt;make&lt;/code&gt; fails with a compile error, I don’t really need a sound to tell me about that. So I wanted a “negative” sound that wasn’t too distracting. I eventually settled on this one.&lt;/p&gt;
&lt;p&gt;&lt;audio controls=&quot;&quot; src=&quot;https://cgamesplay.com/media/20201201-1409-alert-destroyed.wav&quot;&gt;&lt;a href=&quot;https://cgamesplay.com/media/20201201-1409-alert-destroyed.wav&quot;&gt;Click to download&lt;/a&gt;&lt;/audio&gt;&lt;/p&gt;
&lt;p&gt;Can you recognize it? It’s a sound you’ll have heard pretty often if you’ve ever played Factorio: the notification that a building you own has been destroyed. In the game, you’ll often hear this sound altering you of an attack while you’re working on some other task. Generally, it indicates a problem, but not necessarily an urgent one. I thought it would be perfect. Since I’m a user of &lt;a href=&quot;https://fishshell.com&quot;&gt;Fish shell&lt;/a&gt;, I rigged up the notification like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;# Saved to ~/.config/fish/conf.d/90-beep.fish
if test -z $beep_command
  set beep_command &quot;printf \a&quot;
end
set beep_primed &quot;&quot;
function beep_preexec --on-event fish_preexec
  set -g beep_primed 1
end
function beep_postexec --on-event fish_postexec
  set -l last_status $status
  if test ! -z $beep_primed -a ! -z $argv[1] -a $last_status -ne 0
    eval $beep_command
  end
  set -g beep_primed &quot;&quot;
end
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;There’s a few things worth mentioning here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To set the beep command, I used &lt;code dir=&quot;auto&quot;&gt;set -U beep_command &quot;iterm_sound Factorio/alert-destroyed.wav&quot;&lt;/code&gt;. This sets a “&lt;a href=&quot;https://fishshell.com/docs/current/#variable-scope&quot;&gt;universal variable&lt;/a&gt;” in fish, so it’s permanent and system-wide. This lets me change the sound easily whenever I want.&lt;/li&gt;
&lt;li&gt;The &lt;code dir=&quot;auto&quot;&gt;fish_postexec&lt;/code&gt; command runs even if you didn’t run a command (pressed enter at an empty prompt), so we use the &lt;code dir=&quot;auto&quot;&gt;-z $argv[1]&lt;/code&gt; to filter that out.&lt;/li&gt;
&lt;li&gt;The &lt;code dir=&quot;auto&quot;&gt;beep_primed&lt;/code&gt; variable is needed to ensure that the sound only happens once when the command fails. This is necessary to avoid some awkward situations that come up when you press Ctrl-C to cancel a command.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So that’s where I am today. I am very happy with how my notifications work and I’m glad I was able to add a unique bit of flavor to them by sampling from some nostalgic video games. Thanks for reading! If you want to set up something like this and are having problems, feel free to &lt;a href=&quot;https://cgamesplay.com/contact&quot;&gt;reach out to me&lt;/a&gt;.&lt;/p&gt;
</content:encoded><category>iterm</category></item><item><title>Writing iTerm2 Python scripts</title><link>https://cgamesplay.com/post/2020/11/25/iterm-plugins/</link><guid isPermaLink="true">https://cgamesplay.com/post/2020/11/25/iterm-plugins/</guid><description>iTerm2 is a very powerful piece of software and includes a plugin system that allows you to write Python scripts that terminal programs can take advantage of. In this post, we&apos;re going to write two Python scripts for iTerm2: one to automatically switch to/from Dark Mode, and the second to play a sound on your local speakers when an escape sequence is printed, even over SSH. I&apos;ll also share a few bonus snippets that take advantage of some of iTerm2&apos;s lesser known features.

</description><pubDate>Wed, 25 Nov 2020 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://www.iterm2.com&quot;&gt;iTerm2&lt;/a&gt; is a very powerful piece of software and includes a plugin system that allows you to write Python scripts that terminal programs can take advantage of. In this post, we’re going to write two Python scripts for iTerm2: one to automatically switch to/from Dark Mode, and the second to play a sound on your local speakers when an escape sequence is printed, even over SSH. I’ll also share a few bonus snippets that take advantage of some of iTerm2’s lesser known features.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;getting-started&quot;&gt;Getting Started&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Let’s build a simple “Hello, World” iTerm2 script to get started. First, enable the Python API in “Preferences ▸ General ▸ Magic ▸ Enable Python API”.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-python-api.png&quot; alt=&quot;iTerm2 Python API preferences screen&quot;&gt;&lt;/p&gt;
&lt;p&gt;Once enabled, go to “Scripts › Manage › New Python Script”. If you’ve never done this before, iTerm2 will automatically ask to download the Python runtime. Once that’s downloaded, answer “Basic” and “Simple” to the two questions, then save the file to the default directory (&lt;code dir=&quot;auto&quot;&gt;~/Library/Application Support/iTerm2/Scripts&lt;/code&gt;). Take the template that iTerm2 created for you and add a &lt;code dir=&quot;auto&quot;&gt;print&lt;/code&gt; statement to it after the &lt;code dir=&quot;auto&quot;&gt;async_create_tab&lt;/code&gt; call.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;#!/usr/bin/env python3


import iterm2
# This script was created with the &quot;basic&quot; environment which does not support adding dependencies
# with pip.


async def main(connection):
    # Your code goes here. Here&apos;s a bit of example code that adds a tab to the current window:
    app = await iterm2.async_get_app(connection)
    window = app.current_terminal_window
    if window is not None:
        await window.async_create_tab()
        print(&quot;Created a tab!&quot;)
    else:
        # You can view this message in the script console.
        print(&quot;No current window&quot;)


iterm2.run_until_complete(main)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Now in iTerm, select your script from the Scripts menu. If everything is working, your active window should open up a new tab.&lt;/p&gt;
&lt;p&gt;Debugging these scripts is possible with the iTerm2 console. To open it, use “Scripts › Manage › Console”. You’ll see all of your scripts, including those which have crashed or finished. Clicking on the latest one, we should see the output from the script, including the “Created a tab!” message that we added. We can also use the “Terminate” and “Restart” buttons to control the script. Note that you’ll need to manually restart the script any time you make a change to it.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-console.png&quot; alt=&quot;iTerm console&quot;&gt;&lt;/p&gt;
&lt;p&gt;Once everything is ready, we could move our script to the &lt;code dir=&quot;auto&quot;&gt;Scripts/AutoLaunch&lt;/code&gt; directory to have it be started automatically by iTerm2 when iTerm2 launches. That isn’t useful for the one-off script from this example, but you will probably want to do this for long-running scripts like the next two.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;automatic-dark-mode&quot;&gt;Automatic Dark Mode&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-auto-dark-mode.png&quot; alt=&quot;iTerm2 auto Dark Mode&quot;&gt;&lt;/p&gt;
&lt;aside aria-label=&quot;Note&quot;&gt;&lt;div&gt;&lt;p&gt;iTerm2 can now automatically switch themes between light and dark mode, but the Python concepts shown here are still relevant.&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
&lt;p&gt;To have iTerm2 automatically switch between a light and a dark theme following your system setting, follow these steps:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Go to Preferences › Profiles › Colors › Color Presets… and set up your preferred light and dark presets.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-color-presets.png&quot; alt=&quot;iTerm2 Color Presets&quot;&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Download &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/b8eb393f5149fe663fb7ea1c02e56988495a899d/macos/Library/Application%20Support/iTerm2/Scripts/AutoLaunch/DarkMode.py&quot;&gt;DarkMode.py&lt;/a&gt; into your AutoLaunch directory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Update the &lt;code dir=&quot;auto&quot;&gt;async_handle_theme&lt;/code&gt; function to use the correct Color Presets from step 1.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Manually launch the script for the first time using “Scripts › AutoLaunch › DarkMode.py” (or restart iTerm).&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I’ll walk you through the important parts of the code. Starting in the &lt;code dir=&quot;auto&quot;&gt;main&lt;/code&gt; function, you can see we set up a &lt;a href=&quot;https://iterm2.com/python-api/variables.html&quot;&gt;VariableMonitor&lt;/a&gt; on the &lt;a href=&quot;https://iterm2.com/documentation-variables.html&quot;&gt;effectiveTheme&lt;/a&gt; variable. This will allow us to detect when the system toggles Dark Mode. Note that the &lt;code dir=&quot;auto&quot;&gt;main&lt;/code&gt; function also checks the theme once on startup, so if Dark Mode was toggled while iTerm was not running, the change will be picked up immediately.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;async def main(connection):
    app = await iterm2.async_get_app(connection)
    theme = await app.async_get_theme()
    await async_handle_theme(connection, theme)


    async with iterm2.VariableMonitor(connection, iterm2.VariableScopes.APP, &quot;effectiveTheme&quot;, None) as mon:
        while True:
            # Block until theme changes
            joined_theme = await mon.async_get()
            theme = joined_theme.split(&quot; &quot;)
            await async_handle_theme(connection, theme)


iterm2.run_forever(main)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code dir=&quot;auto&quot;&gt;async_handle_theme&lt;/code&gt; function simply looks at the theme, which will be something like “dark”, “light highContrast”, “dark minimal”, etc., and decides which color scheme to use before passing it to &lt;code dir=&quot;auto&quot;&gt;async_set_color_preset&lt;/code&gt;.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;async def async_handle_theme(connection, theme):
    if &quot;dark&quot; in theme:
        preset = await iterm2.ColorPreset.async_get(connection, &quot;Solarized Dark&quot;)
    else:
        preset = await iterm2.ColorPreset.async_get(connection, &quot;Solarized Light&quot;)


    await async_set_color_preset(connection, preset)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;The main workhorse is the &lt;code dir=&quot;auto&quot;&gt;async_set_color_preset&lt;/code&gt; function. The first part loops over all of the saved profiles in iTerm2, which are called &lt;a href=&quot;https://iterm2.com/python-api/profile.html#iterm2.PartialProfile&quot;&gt;PartialProfiles&lt;/a&gt;. You can see in my screenshot above that I have just one named “Default”. By setting the color scheme for each profile, when a new session is opened it will have the correct color scheme applied.&lt;/p&gt;
&lt;p&gt;The second part loops over all tabs of all windows and sets their color scheme. This is causes all of the current session to switch to the correct color scheme when the system switches to/from Dark Mode. It does this by creating a &lt;a href=&quot;https://iterm2.com/python-api/profile.html#iterm2.LocalWriteOnlyProfile&quot;&gt;LocalWriteOnlyProfile&lt;/a&gt; which will just contain the necessary changes to the colors, and then applying those changes with &lt;a href=&quot;https://iterm2.com/python-api/session.html#iterm2.Session.async_set_profile_properties&quot;&gt;&lt;code dir=&quot;auto&quot;&gt;async_set_profile_properties&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;async def async_set_color_preset(connection, preset):
    &quot;&quot;&quot;
    This updates the color scheme of all profiles and of all active sessions.
    &quot;&quot;&quot;
    # Update the list of all profiles and iterate over them.
    profiles = await iterm2.PartialProfile.async_query(connection)
    for partial in profiles:
        # Fetch the full profile and then set the color preset in it.
        profile = await partial.async_get_full_profile()
        await profile.async_set_color_preset(preset)


    # Update all currently running sessions with the new preference.
    app = await iterm2.async_get_app(connection)
    for window in app.terminal_windows:
        for tab in window.tabs:
            for session in tab.sessions:
                profile = await session.async_get_profile()
                change = iterm2.LocalWriteOnlyProfile()
                set_color_preset(change, preset)
                await session.async_set_profile_properties(change)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Once you’ve set up the color schemes and installed this script, it’ll work silently. If anything isn’t working, check the iTerm2 script console first to find out why.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;playing-sounds-with-iterm&quot;&gt;Playing sounds with iTerm&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;This script allows you to write a short shell script to play an audio file on your local computer (or anything else, even &lt;a href=&quot;https://github.com/tenderlove/analog-terminal-bell&quot;&gt;to hit a physical bell&lt;/a&gt;), even over an SSH session. It works by using iTerm2’s custom escape sequences to run a Python function. To install this script:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Download &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/bee7d071a7b85f7becc696edc0b328677eb16c40/macos/Library/Application%20Support/iTerm2/Scripts/AutoLaunch/PlaySound.py&quot;&gt;PlaySound.py&lt;/a&gt; into your AutoLaunch directory.&lt;/li&gt;
&lt;li&gt;Replace the &lt;code dir=&quot;auto&quot;&gt;LIBRARIES&lt;/code&gt; constant with a list of directories that contain audio files you’d like to play.&lt;/li&gt;
&lt;li&gt;Manually launch the script for the first time using “Scripts › AutoLaunch › PlaySound.py” (or restart iTerm).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Our new custom escape sequence can be triggered using this bash snippet:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;printf &quot;\033]1337;Custom=id=%s:%s\a&quot; &quot;play-sound&quot; &quot;Glass&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;You can replace the “Glass” with the name of any sound file in one of the &lt;code dir=&quot;auto&quot;&gt;LIBRARIES&lt;/code&gt; directories. If you have a MacOS machine, the above snippet should make this sound:&lt;/p&gt;
&lt;p&gt;&lt;audio controls=&quot;&quot; src=&quot;https://cgamesplay.com/media/20201125-1600-iterm-sounds-glass.aiff&quot;&gt;&lt;a href=&quot;https://cgamesplay.com/media/20201125-1600-iterm-sounds-glass.aiff&quot;&gt;Click to download&lt;/a&gt;&lt;/audio&gt;&lt;/p&gt;
&lt;p&gt;The source code to this is really simple. Let’s first look at the &lt;code dir=&quot;auto&quot;&gt;main&lt;/code&gt; function: it uses a &lt;a href=&quot;https://iterm2.com/python-api/customcontrol.html&quot;&gt;CustomControlSequenceMonitor&lt;/a&gt; to listen for our sequence, and then it calls our &lt;code dir=&quot;auto&quot;&gt;locate_sound&lt;/code&gt; function to resolve the value (e.g. &lt;code dir=&quot;auto&quot;&gt;Glass&lt;/code&gt;) to a filename (&lt;code dir=&quot;auto&quot;&gt;/System/Library/Sounds/Glass.aiff&lt;/code&gt;), and finally calls a program to play the sound.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;async def main(connection):
    async with iterm2.CustomControlSequenceMonitor(connection, COMMAND, r&apos;^.*$&apos;) as mon:
        while True:
            match = await mon.async_get()
            try:
                filename = locate_sound(match.group(0))
                subprocess.run([&quot;afplay&quot;, filename])
            except:
                traceback.print_tb(sys.exc_info()[2])


iterm2.run_forever(main)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Our &lt;code dir=&quot;auto&quot;&gt;locate_sound&lt;/code&gt; function simply searches for files with a matching filename in one of the configured directories.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;python&quot;&gt;def locate_sound(name):
    for d in LIBRARIES:
        for m in glob.iglob(&quot;%s/%s.*&quot; % (d, glob.escape(name))):
            return m
        for m in glob.iglob(&quot;%s/%s&quot; % (d, glob.escape(name))):
            return m
    raise ValueError(&quot;no matching sound found&quot;)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;A quick note about security here. The iTerm docs recommend that the ID (&lt;code dir=&quot;auto&quot;&gt;COMMAND&lt;/code&gt; in this script) should be a password rather than a well-known string. This is because knowing the ID is the only access control that the file has. For example, if you run &lt;code dir=&quot;auto&quot;&gt;curl malicious.site/textfile&lt;/code&gt; and that file contains the escape sequence, it would trigger your script. For something silly like playing sounds, this isn’t a big concern, but it’s certainly worth keeping in mind when expanding on this idea.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;wrapping-up&quot;&gt;Wrapping up&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;With these scripts you can make iTerm2 more useful for you. Next time, we’re going to look at some ways to &lt;a href=&quot;https://cgamesplay.com/post/2020/12/09/iterm-notifications/&quot;&gt;get the most use out of these scripts&lt;/a&gt;.&lt;/p&gt;
&lt;aside aria-label=&quot;Bonus: Little-known iTerm2 features&quot;&gt;&lt;div&gt;&lt;p&gt;I have an entire page dedicated to &lt;a href=&quot;https://cgamesplay.com/recipes/iterm2/&quot;&gt;iTerm2 Tips &amp;amp; Tricks&lt;/a&gt;!&lt;/p&gt;&lt;/div&gt;&lt;/aside&gt;
</content:encoded><category>iterm</category></item><item><title>Configuring Prettier and ESLint</title><link>https://cgamesplay.com/post/2019/12/20/prettier/</link><guid isPermaLink="true">https://cgamesplay.com/post/2019/12/20/prettier/</guid><description>After configuring Prettier and ESLint for my JavaScript projects, I documented the streamlined process for others to easily achieve consistent code formatting and linting in their repositories.

</description><pubDate>Fri, 20 Dec 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;At my latest job, I’ve found myself setting up Prettier and ESLint on several different JavaScript projects. I’ve done it enough times that the process has become somewhat mechanical, so I wanted to document it so that others might be able to use the same process.&lt;/p&gt;
&lt;p&gt;In this post I am going to be using &lt;a href=&quot;https://github.com/BigDataBoutique/ElastiQuill&quot;&gt;ElasticQuill&lt;/a&gt; as an example project. You can see the end result in &lt;a href=&quot;https://github.com/BigDataBoutique/ElastiQuill/commit/cf3596e0feb3d65e8341c8fbc678f759c78dac96&quot;&gt;this commit&lt;/a&gt;. This process should work for any JavaScript repository with minimal modification, however.&lt;/p&gt;
&lt;p&gt;The ElastiQuill project is set up as a monorepo with two components, &lt;code dir=&quot;auto&quot;&gt;admin-frontend&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;backend&lt;/code&gt;. At the start the directory structure looks like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;elastiquill
├── admin-frontend
│  ├── node_modules
│  ├── package-lock.json
│  ├── package.json
│  ├── src
│  │  └── (javascript files)
│  └── webpack.config.js
└── backend
   ├── node_modules
   ├── package-lock.json
   ├── package.json
   ├── src
   │  └── (javascript files)
   └── webpack.config.js
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This guide is written against &lt;code dir=&quot;auto&quot;&gt;prettier@1.19.1&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;eslint@6.7.2&lt;/code&gt;.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;step-1-just-use-prettier&quot;&gt;Step 1: Just Use Prettier™&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;This step comes first because it’s the simplest and most mechanical. We simply install prettier and run it on all of the files we want to keep formatted. For the example project, these are everything under &lt;code dir=&quot;auto&quot;&gt;src&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;webpack.config.js&lt;/code&gt;, and we run these commands in each of the two project directories (&lt;code dir=&quot;auto&quot;&gt;admin-frontend&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;backend&lt;/code&gt;).&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;echo &apos;trailingComma = &quot;es5&quot;&apos; &amp;gt; .prettierrc.toml
cd admin-frontend
npm install --save-dev prettier
prettier --write &apos;src/**&apos; webpack.config.js
cd ../backend
npm install --save-dev prettier
prettier --write &apos;src/**&apos; webpack.config.js
cd ..
git add .
git commit -a -m &quot;Just Use Prettier™&quot;
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Notice that the &lt;code dir=&quot;auto&quot;&gt;.prettierrc.toml&lt;/code&gt; file is in the repository root, so it will be shared between both of the projects. You could install prettier into the repository root if you wanted, but having nested packages in this way can result in some confusing edge cases, so I don’t recommend it.&lt;/p&gt;
&lt;p&gt;As far as what to put in &lt;code dir=&quot;auto&quot;&gt;.prettierrc.toml&lt;/code&gt;, I recommend only one non-default setting:  &lt;code dir=&quot;auto&quot;&gt;trailingComma = &quot;es5&quot;&lt;/code&gt; This is because trailing commas lead to cleaner &lt;code dir=&quot;auto&quot;&gt;git diff&lt;/code&gt; output, and &lt;code dir=&quot;auto&quot;&gt;&quot;es5&quot;&lt;/code&gt; is supported in all browsers. If you want to go a step further, &lt;code dir=&quot;auto&quot;&gt;&quot;all&quot;&lt;/code&gt; can also be used, but should only be used if the project is transpiled with babel or something similar. &lt;a href=&quot;https://prettier.io/docs/en/options.html&quot;&gt;Read more about Prettier options&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;step-2-configure-eslint&quot;&gt;Step 2: Configure ESLint&lt;/h2&gt;&lt;/div&gt;
&lt;div&gt;&lt;h3 id=&quot;step-2a-deciding-on-an-eslint-configuration&quot;&gt;Step 2a: Deciding on an ESLint configuration&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;Unfortunately, ESLint requires much more configuration than Prettier. Since we are using prettier, we can use &lt;code dir=&quot;auto&quot;&gt;eslint-prettier&lt;/code&gt; to disable all code formatting warnings and have ESLint focus on more important things. I will include the settings that ElastiQuill ended up using and discuss them. ElastiQuill makes use of React, Babel, and Jest.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;module.exports = {
   env: { browser: true, node: true, &quot;jest/globals&quot;: true, es6: true },
   extends: [
     &quot;eslint:recommended&quot;,
     &quot;plugin:react/recommended&quot;,
     &quot;plugin:prettier/recommended&quot;,
   ],
   plugins: [&quot;jest&quot;],
   rules: {
     &quot;react/prop-types&quot;: &quot;off&quot;,
     &quot;react/jsx-no-target-blank&quot;: &quot;off&quot;,
     &quot;require-atomic-updates&quot;: &quot;off&quot;,
     &quot;no-unused-vars&quot;: [&quot;error&quot;, { ignoreRestSiblings: true }],
     &quot;no-console&quot;: &quot;off&quot;,
   },
   parserOptions: {
     ecmaFeatures: {
       jsx: true,
       modules: true,
       legacyDecorators: true,
     },
   },
   parser: &quot;babel-eslint&quot;,
 };
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Let me explain each setting and the motivations for including it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;env.browser&lt;/code&gt; The &lt;code dir=&quot;auto&quot;&gt;admin-frontend&lt;/code&gt; project runs in the browser. This setting defines browser globals like &lt;code dir=&quot;auto&quot;&gt;window&lt;/code&gt;  and &lt;code dir=&quot;auto&quot;&gt;document&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;env.node&lt;/code&gt; The &lt;code dir=&quot;auto&quot;&gt;backend&lt;/code&gt; project runs in node. This setting defines node globals like &lt;code dir=&quot;auto&quot;&gt;process&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;env[&quot;jest/globals&quot;]&lt;/code&gt; The tests run in Jest. This setting defines Jest globals like &lt;code dir=&quot;auto&quot;&gt;describe&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;it&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;env.es6&lt;/code&gt; The project is written in ES6. This setting defines ES6 globals like &lt;code dir=&quot;auto&quot;&gt;Promise&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;extends &quot;eslint:recommended&quot;&lt;/code&gt; This will be the basic defaults we use for ESLint. It provides mostly sane defaults, many of which ESLint can automatically fix.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;extends &quot;plugin:react/recommended&quot;&lt;/code&gt; This plugin adds several useful React-specific style and quality rules.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;extends &quot;plugin:prettier/recommended&quot;&lt;/code&gt; This plugin configures ESLint to defer all style decisions to Prettier.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;rules[&quot;no-unused-vars&quot;]&lt;/code&gt; This rule is good, however a common practice in React is to “pull out” props so they don’t get passed on to nested components. By setting &lt;code dir=&quot;auto&quot;&gt;ignoreRestSiblings&lt;/code&gt;, the following unused variable is allowed: &lt;code dir=&quot;auto&quot;&gt;const { onSubmit, ...rest}; return &amp;lt;button {...rest} /&amp;gt;&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;parserOptions&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;parser&lt;/code&gt; Everything here is just what is necessary to get ESLint to parse the source code. If ESLint reports syntax errors in valid code, you likely need to check the &lt;code dir=&quot;auto&quot;&gt;parserOptions&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The config file for ElastiQuill disables a few of the recommended rules. Here’s why:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;react/prop-types&lt;/code&gt; Unfortunately, this project does not use &lt;code dir=&quot;auto&quot;&gt;propTypes&lt;/code&gt;. It would be nice if it did, but adding them to all components is beyond the scope of simply configuring ESLint.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;react/jsx-no-target-blank&lt;/code&gt; This rule highlights a valid (though minor) security concern that is worth addressing. Rather than spamming &lt;code dir=&quot;auto&quot;&gt;rel=&quot;noopener&quot;&lt;/code&gt; into every &lt;code dir=&quot;auto&quot;&gt;target=&quot;_blank&quot;&lt;/code&gt; link in the project, however, a better solution is to create a custom component for off-site links that open in a new tab. Of course, this is beyond the scope of simply configuring ESLint.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;require-atomic-updates&lt;/code&gt; This rule is fundamentally incompatible with express, so it produces false positives on almost every express middleware you write. This rule also detects only the simplest of race conditions, so I don’t bother enabling it at all.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;no-console&lt;/code&gt; Unfortunately, this project has lots of &lt;code dir=&quot;auto&quot;&gt;console.error&lt;/code&gt; statements in error handlers. It would be nice if it had a better way of handling errors, but fixing all instances of this is beyond the scope of simply configuring ESLint.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I recommend starting with the defaults for all rules and choosing to disable specific rules later on in step 2b.&lt;/p&gt;
&lt;p&gt;We save this base configuration as &lt;code dir=&quot;auto&quot;&gt;.eslintrc.base.js&lt;/code&gt; in the repository root. Then, in each of the project directories we reference it:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;const baseConfig = require(&quot;../.eslintrc.base&quot;);
module.exports = { ...baseConfig, ignorePatterns: [&quot;src/lib/**/*&quot;] };
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;const baseConfig = require(&quot;../.eslintrc.base&quot;);
module.exports = { ...baseConfig, ignorePatterns: [&quot;src/views/**/*&quot;] };
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;We have to ignore some paths in each of the projects. For &lt;code dir=&quot;auto&quot;&gt;admin-frontend&lt;/code&gt;, there is a lot of vendor code that we don’t need to bother linting. For &lt;code dir=&quot;auto&quot;&gt;backend&lt;/code&gt;, there’s a lot of non-react, non-babel code which would require a different eslintrc. This is beyond the scope of this post.&lt;/p&gt;
&lt;div&gt;&lt;h3 id=&quot;step-2b-running-eslint&quot;&gt;Step 2b: Running ESLint&lt;/h3&gt;&lt;/div&gt;
&lt;p&gt;With our configuration decided, it’s time to run eslint and get an error list:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;cd admin-frontend
npm install --save-dev \
  eslint \
  eslint-config-prettier \
  eslint-config-react \
  eslint-plugin-prettier \
  eslint-plugin-jest \
  babel-eslint
eslint --cache --fix --ext js src
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This will give us a big error list. Start by going through and cleaning up anything trivial, like unused variable errors or missing &lt;code dir=&quot;auto&quot;&gt;key&lt;/code&gt; props. If fixing an error requires more than 15 seconds of reading the code, don’t fix it at this stage.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tip:&lt;/strong&gt; You can have vim load the eslint errors into your quickfix window with this command, and use &lt;code dir=&quot;auto&quot;&gt;:cnext&lt;/code&gt; or &lt;code dir=&quot;auto&quot;&gt;]q&lt;/code&gt; from &lt;a href=&quot;https://github.com/tpope/vim-unimpaired&quot;&gt;vim-unimpaired&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;:cexpr system(&apos;node_modules/.bin/eslint --cache --format unix --ext js src&apos;)
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;I find it’s useful to commit early and often at this stage, and make sure to test the application before every commit to make sure that everything is working still.&lt;/p&gt;
&lt;p&gt;After fixing all of the trivial errors, start working on the rest. For these, it’s useful to time box yourself to no more than a minute or so per lint error. If fixing a specific error would take longer than a minute, then use an ESLint comment directive to suppress the lint error for the specific location. Example:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;/* eslint-disable no-alert */
alert(&apos;foo&apos;);
/* eslint-enable no-alert */
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;If you end up leaving lots of lint violations (by using these disable directives), it may be useful to add &lt;a href=&quot;https://mysticatea.github.io/eslint-plugin-eslint-comments/&quot;&gt;eslint-plugin-eslint-comments&lt;/a&gt; to the configuration.&lt;/p&gt;
&lt;p&gt;We follow a similar process for the &lt;code dir=&quot;auto&quot;&gt;backend&lt;/code&gt; directory. At the end of this step, eslint should report no errors for either project.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;step-3-adding-to-ci&quot;&gt;Step 3: Adding to CI&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Now that the code base is formatted and lint-free, we want to keep it that way. This is simply a matter of writing some scripts to run prettier and eslint, and telling the CI to run them.&lt;/p&gt;
&lt;p&gt;The first script will be &lt;code dir=&quot;auto&quot;&gt;prettier-check&lt;/code&gt;, which verifies that prettier has been run on all files. Add some scripts to the &lt;code dir=&quot;auto&quot;&gt;script&lt;/code&gt; section of the &lt;code dir=&quot;auto&quot;&gt;package.json&lt;/code&gt; files in each project directory:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;json&quot;&gt;{
  &quot;scripts&quot;: {
    &quot;lint&quot;: &quot;eslint --cache --ext js src&quot;,
    &quot;prettier-check&quot;: &quot;prettier --check src/** webpack.config.js&quot;
  }
}
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Then add &lt;code dir=&quot;auto&quot;&gt;scripts/prettier-check.sh&lt;/code&gt; to the repository root:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;#!/bin/bash


 COMBINED_STATUS=0
 DIRS=&quot;admin-frontend backend&quot;
 for dir in $DIRS; do
   echo
   echo &quot;Checking $dir source&quot;
   (cd $dir &amp;amp;&amp;amp; npm run prettier-check)
   DIR_STATUS=$?
   [ $DIR_STATUS -ne 0 ] &amp;amp;&amp;amp; COMBINED_STATUS=$DIR_STATUS
 done


  [ $DIR_STATUS -ne 0 ] &amp;amp;&amp;amp; exit $DIR_STATUS
 exit 0
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This script should be straightforward, the only tricky thing is we want to run prettier on each project, but keep the build running and only fail at the end if there were errors. Add &lt;code dir=&quot;auto&quot;&gt;scripts/lint.sh&lt;/code&gt; as well, which is the same script but has &lt;code dir=&quot;auto&quot;&gt;npm run prettier-check&lt;/code&gt; replaced by &lt;code dir=&quot;auto&quot;&gt;npm run lint&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If the project is hosted on GitLab, then a &lt;code dir=&quot;auto&quot;&gt;.gitlab-ci.yml&lt;/code&gt; to run these scripts might look like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;yaml&quot;&gt;stages:
 - test


static-analysis:
  stage: test
  image: node
  cache:
    key: ${CI_JOB_NAME}
    paths:
      - admin-frontend/node_modules
      - backend/node_modules
  script:
    # These are in () to run in a subshell and not modify the real pwd
    - (cd admin-frontend &amp;amp;&amp;amp; npm install)
    - (cd backend &amp;amp;&amp;amp; npm install)
    - npm run prettier-check
    - npm run lint
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;And that’s it. Altogether, configuring and running eslint and prettier on ElastiQuill took me 2 hours.&lt;/p&gt;
&lt;p&gt;When I look back on this project, I can think of a few things that could be improved. Here’s are some of the ideas:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Since &lt;code dir=&quot;auto&quot;&gt;eslint-prettier&lt;/code&gt; is enforcing Prettier styles, the &lt;code dir=&quot;auto&quot;&gt;prettier-check&lt;/code&gt; script may actually be redundant, but I’m not sure that &lt;code dir=&quot;auto&quot;&gt;eslint-prettier&lt;/code&gt; performs the same checks as &lt;code dir=&quot;auto&quot;&gt;prettier --check&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It would be nice if the “longer-term” lint errors like &lt;code dir=&quot;auto&quot;&gt;react/prop-types&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;no-console&lt;/code&gt; were set to &lt;code dir=&quot;auto&quot;&gt;&quot;warn&quot;&lt;/code&gt; instead of &lt;code dir=&quot;auto&quot;&gt;&quot;error&quot;&lt;/code&gt; and accompanied by a tool to produce a report of these (like &lt;a href=&quot;https://goreportcard.com/report/github.com/sprkyco/g0sh1t&quot;&gt;Go Report Card&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Thoughts on dotfiles</title><link>https://cgamesplay.com/post/2019/12/01/thoughts-on-dotfiles/</link><guid isPermaLink="true">https://cgamesplay.com/post/2019/12/01/thoughts-on-dotfiles/</guid><description>I&apos;ve maintained a dotfiles repository since 2011 (at least that&apos;s when I initially put it into git), and haven&apos;t thought much about it since then. I wrote a basic &quot;dotfiles installation&quot; script back in 2013 and have been using and lightly modifying that ever since. My primary use case was just syncing dotfiles between my personal and corporate Macbooks, so it didn&apos;t need much flexibility. However, the Makefile wasn&apos;t trivial and doing simple things like adding new files required knowing the magic incantation (a combination of undocumented convention and GNU Make functions).

</description><pubDate>Sun, 01 Dec 2019 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I’ve maintained a dotfiles repository since 2011 (at least that’s when I initially put it into git), and haven’t thought much about it since then. I wrote a basic “dotfiles installation” script back in 2013 and have been using and lightly modifying that ever since. My primary use case was just syncing dotfiles between my personal and corporate Macbooks, so it didn’t need much flexibility. However, the Makefile wasn’t trivial and doing simple things like adding new files required knowing the magic incantation (a combination of undocumented convention and GNU Make functions).&lt;sup&gt;&lt;a href=&quot;#user-content-fn-makefile&quot; id=&quot;user-content-fnref-makefile&quot; data-footnote-ref=&quot;&quot; aria-describedby=&quot;footnote-label&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;I recently reevaluated my strategy since I was setting up a new workstation for the first time in a while, and it was a Linux box, which meant there would be configuration that wasn’t compatible with my Macbook. I decided that I needed to improve the situation, and came up with a list of personal priorities.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Minimize the required knowledge.&lt;/strong&gt; I only go near my dotfiles manager once in a while, and so it’s very easy to forget any customizations or processes I need to file. The ideal solution should be very easy to reason about and require few if any specialized commands or configuration files.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Minimize the likelihood of failure.&lt;/strong&gt; I might be configuring a MacOS or Linux machine of any distribution, and some software packages might not be available on the machine during installation. Installing my dotfiles should always work, regardless of the existing configuration of the target machine.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Minimize the friction of updating.&lt;/strong&gt; Sharing a modification from one machine to the rest should be as painless as possible. In general, I already have a working configuration file on one of my machines, and I just want that file, verbatim, on another machine.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Of course, everybody and their brother has their own preferred solution for managing their dotfiles, so naturally there’s a plethora of prior art to choose from. I looked through all of the ones on &lt;a href=&quot;https://dotfiles.github.io/&quot;&gt;Github Does Dotfiles&lt;/a&gt;, but (unsurprisingly) found that none were quite what I was looking for. When I was reviewing the list, I found a few factors that caused me to rule out most of the projects immediately:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Projects that bill themselves as “dotfile package managers”.&lt;/strong&gt; These all violate priority 1 for me by introducing a new set of commands/configuration to learn so I can manage my “dotfiles packages”. Beyond that, the functionality to “update” my dotfiles to a version that someone else wrote that I have never reviewed is a huge violation of all of my priorities. There’s no way I would introduce this level of complexity into my workflow.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Projects that depend on (node|python|ruby|gcc|apt).&lt;/strong&gt; These violate priority 2 for me. Not all of my systems have a these language runtimes installed, and I don’t want to install one to create some symlinks. Many scripting languages are also moving targets, requiring specific versions of the language runtimes in order to function properly, which might not be the same version installed by the OS package manager. The best projects are those that can be run directly from the git repository or have a single statically-linked binary distributed with the project.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Projects that interact with git.&lt;/strong&gt; I use git every day and have a git workflow that I use every day. Dotfile managers that attempt to manage my dotfiles git repository (or “wrap git”) end up putting me in situations outside of my “git happy path”, and inadvertently cause more confusion than simplicity.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Projects that don’t clean up unused configuration files.&lt;/strong&gt; This one is minor, but most dotfiles managers are good at getting files onto your system, but bad at getting them off, leaving dangling symlinks in their wake. When I remove the configuration from my git repository, I want it to be removed from my home directory as well.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;building-my-own-solution&quot;&gt;Building my own solution&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Like so many before me, I decided to write my own solution: &lt;a href=&quot;https://github.com/CGamesPlay/dfm&quot;&gt;dfm&lt;/a&gt;. The goals for dfm line up with the three priorities from before:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Simple.&lt;/strong&gt; Conceptually, dfm should be as simple as &lt;code dir=&quot;auto&quot;&gt;cp&lt;/code&gt;, with no new concepts. When using it, there should be a small number of commands and few, if any, options for those commands. Everything should be clearly documented, but reading the documentation should not be necessary for daily use.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reliable.&lt;/strong&gt; The program should be able to run on any freshly-configured Linux or MacOS system without any additional software installation. It should also work when running against an already-configured system, and not do anything silly like destroy the existing configuration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Easy.&lt;/strong&gt; The program should have one command (or fewer!) to set up a new machine; one command to update the machine; and one command to update the repository from the machine.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;I think dfm accomplished these goals well. In particular, I’m happy with the simplicity of the workflow:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;dfm add&lt;/code&gt; will copy a file from your home directory into your git repository, then replace it with a symlink to the git repository. No configuration files need to be edited.&lt;/li&gt;
&lt;li&gt;&lt;code dir=&quot;auto&quot;&gt;dfm link&lt;/code&gt; will sync your git repository to your home directory for both new files and removed files. It doesn’t overwrite existing files by default, but using the industry-standard &lt;code dir=&quot;auto&quot;&gt;-f&lt;/code&gt; flag will force it.&lt;/li&gt;
&lt;li&gt;There’s a command to stop using dfm. I don’t recall a single other dotfiles manager giving you a way out.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I did violate priority 1 a bit in dfm, by adding support for “multiple repositories”. I decided to do this because it grants you quite a bit of added flexibility (configurations for different OSes/machine roles, “dotfiles packages” through submodules, local-only configurations through &lt;code dir=&quot;auto&quot;&gt;.gitignore&lt;/code&gt;, etc.), at the cost of a required option during initial configuration.&lt;/p&gt;
&lt;p&gt;I stuck to my priorities as much as possible for the rest. Here are a few features that dfm does not have, because they would violate the priorities:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Templated files.&lt;/strong&gt; Instead, I can write a script that runs &lt;code dir=&quot;auto&quot;&gt;dfm link&lt;/code&gt; and then generates additional files.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Script running.&lt;/strong&gt; Instead, I can write a script that runs &lt;code dir=&quot;auto&quot;&gt;dfm link&lt;/code&gt; and then any other scripts I need.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Secret management.&lt;/strong&gt; Instead, I can use an external tool to store the secrets and combine it with a script that runs &lt;code dir=&quot;auto&quot;&gt;dfm link&lt;/code&gt; and then installs the secrets.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Syncing.&lt;/strong&gt; Instead, I can do this using git, like I do every day for all of my projects.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As I said before, everybody has their own custom solution for this, and I’m sure that for many of the solutions, the extra complexity they added is worthwhile to them. I wanted to build something that was deliberately simple and worked everywhere I am likely to find myself, and I think dfm does a good job of it.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;my-advice&quot;&gt;My advice&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Obviously, if your priorities are similar to mine, &lt;a href=&quot;https://github.com/CGamesPlay/dfm&quot;&gt;dfm&lt;/a&gt; is a project you should look into.&lt;/p&gt;
&lt;p&gt;But really, whatever you decide, document it for yourself! Your &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles&quot;&gt;repository README&lt;/a&gt; should at least cover setting up a new machine, adding a new config file, and syncing changes on an existing machine.&lt;/p&gt;
&lt;section data-footnotes=&quot;&quot;&gt;&lt;div&gt;&lt;h2 id=&quot;footnote-label&quot;&gt;Footnotes&lt;/h2&gt;&lt;/div&gt;
&lt;ol&gt;
&lt;li id=&quot;user-content-fn-makefile&quot;&gt;
&lt;p&gt;To get an idea for what I was dealing with, here is the &lt;a href=&quot;https://github.com/CGamesPlay/dotfiles/blob/e9f6272a30c5fc2e510d21b783fb591bb1bf264a/install&quot;&gt;last version of that script&lt;/a&gt; before I deleted it. &lt;a href=&quot;#user-content-fnref-makefile&quot; data-footnote-backref=&quot;&quot; aria-label=&quot;Back to reference 1&quot;&gt;↩&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content:encoded><category>dotfiles</category></item><item><title>Dev Diaries - July 21, 2018</title><link>https://cgamesplay.com/post/2018/07/21/dev-diaries-july-21-2018/</link><guid isPermaLink="true">https://cgamesplay.com/post/2018/07/21/dev-diaries-july-21-2018/</guid><description>A summary of my current hobby projects includes developing a board game engine with Glish, enhancing a Chess 2 AI, and reevaluating HTerminal&apos;s features for better productivity.

</description><pubDate>Sat, 21 Jul 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This is a short update about all of the hobby projects I have in flight. I’m mostly writing this as a way for me to keep track of what’s next on each of them, so I can decide what to work on next. 😀&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;glish&quot;&gt;Glish&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The core language is working well enough that I’m ready to start working on my first real Glish application to help design the other language features. The first application is a board game engine, where Glish is the repository of game rules and a web application is responsible for collecting the actions from the players and showing everything.&lt;/p&gt;
&lt;p&gt;Since I’m not totally sure what a “board game engine” looks like, I want to code a basic implementation in JavaScript, just to help me figure out what the primtives are. I am building a command-line Mancala program as an initial trial, and then plan to add some other simple game built on the JS version of the engine to “kick the tires” of the model I’ve designed. Then I’ll implement that model in Glish, and finally build a graphical frontend.&lt;/p&gt;
&lt;p&gt;The last step is a bit tricky for me. It turns out I’m really only good at building web applications of the traditional “application” kind, like with buttons and forms and stuff. I haven’t done any work with any modern tools to handle things like animations, physics, etc. So I had to take a pretty big detour here to learn about these. I compared a few and settled on &lt;a href=&quot;https://phaser.io&quot;&gt;Phaser&lt;/a&gt;, a JavaScript library designed to make 2D games. After doing a tutorial, I think I have a good enough grasp of Phaser to start building the front end. I wanted to do this before I got too far into building a particular implementation in case there were any unforeseen difficulties.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Next steps on this project:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Finish building the command-line version of the engine and make sure the designed model makes sense.&lt;/li&gt;
&lt;li&gt;Build a command-line version of the engine in Glish.&lt;/li&gt;
&lt;li&gt;Build the graphical frontend.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;&lt;h2 id=&quot;chess-2&quot;&gt;Chess 2&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I’ve been working on a &lt;a href=&quot;https://en.wikipedia.org/wiki/Chess_2:_The_Sequel&quot;&gt;Chess 2&lt;/a&gt; game for several years now. There’s an official Steam game, but it doesn’t offer mobile play and the AI that comes included with the game is woefully bad (it appears to be a stock Chess AI dropped in to the rules of Chess 2). My goal from the start has been to build a better Chess 2 AI and learn about machine learning in the process.&lt;/p&gt;
&lt;p&gt;I started this project by building a Python implementation of the Chess 2 engine. In doing this I discovered many difficult edge cases in the rules of Chess 2 and built an engine that could handle all of these. I chose Python because I was planning on developing the AI using TensorFlow, for which Python is the preferred language.&lt;/p&gt;
&lt;p&gt;After I did that I built &lt;a href=&quot;https://www.chess2online.com&quot;&gt;an online app to play games&lt;/a&gt;. It’s built with React, GraphQL, AWS Lambda, and AWS DynamoDB. The biggest thing I learned in doing this is that my entire API should have been a single Lambda function. I used a different Lambda function for each endpoint which means that deploys are more difficult and the app takes longer to “boot up”. The web app frontend isn’t very good, and I haven’t touched it in probably about a year.&lt;/p&gt;
&lt;p&gt;In order to train an AI, you typically need a huge data set. One doesn’t exist for Chess2 games, so I looked for “tabula rasa” training methods. The widely-known &lt;a href=&quot;https://deepmind.com/blog/alphago-zero-learning-scratch/&quot;&gt;AlphaGo Zero&lt;/a&gt; was one implementation, and &lt;a href=&quot;https://arxiv.org/abs/1509.01549&quot;&gt;Giraffe&lt;/a&gt; was another targetting Chess. I was very excited when the &lt;a href=&quot;https://arxiv.org/abs/1712.01815&quot;&gt;AlphaZero&lt;/a&gt; paper was published and was confident I’d be able to get decent results if I followed the same methodology.&lt;/p&gt;
&lt;p&gt;Unfortunately, the problem facing me now is purely technical. My Chess2 engine is &lt;em&gt;slow&lt;/em&gt;. On my computer, I’m only able to list valid moves at a rate of about 27 boards per second, and this doesn’t include doing any actual evaluation on those boards (i.e. no “AI”). I estimate that at this speed I would need around 100 days of 24x7 training to achieve similar results to the AlphaZero paper (300k self-play games). And if there was a bug then I’d have to start over.&lt;/p&gt;
&lt;p&gt;I think I need to make move generation at least 1,000x faster in order to have a real chance. Building the engine in Python seems to have been a pretty big failure here due to the speed issues. cPython might be faster, but isn’t supported by TensorFlow. Multithreading isn’t possible in Python, and multiprocess has too high of an overhead to enable the 1,000x speedup I’m looking for (the algorithm is very sensitive to latency).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Next steps on this project:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Think more about &lt;a href=&quot;https://eng.uber.com/accelerated-neuroevolution/&quot;&gt;neuroevolution&lt;/a&gt;, which may enable a multiprocess solution to work.&lt;/li&gt;
&lt;li&gt;Rewrite the engine in C++, then figure out how to build a paralellizable MCTS. This might require writing the neural network in C++ as well.&lt;/li&gt;
&lt;li&gt;Make the Chess 2 Online app better.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;&lt;h2 id=&quot;hterminal&quot;&gt;HTerminal&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I haven’t touched HTerminal in over 2 years, but I’ve started to think more about it recently. I stopped working on the project because I lost confidence that the approach I was taking was going to meaningfully enhance the terminal experience.&lt;/p&gt;
&lt;p&gt;The current status of HTerminal is “generally working”. It supports a few neat features and generally works as a standard console, although nowhere near as good as iTerm 2. The features that it adds aren’t game-changing, though. I can show icons in &lt;code dir=&quot;auto&quot;&gt;ls&lt;/code&gt;, or put a “commit” button in the output of &lt;code dir=&quot;auto&quot;&gt;git status&lt;/code&gt;, but none of these things really make me materially more productive.&lt;/p&gt;
&lt;p&gt;I have some ideas about how to improve HTerminal, which I’d like to write about soon. I think the core ideals of HTerminal are valid, like not replacing the shell and working over SSH; but I think the improvements that it brings to the table are lackluster presently. I’d like to incorporate some of the ideas from &lt;a href=&quot;https://github.com/railsware/upterm&quot;&gt;UpTerm&lt;/a&gt; into the project, but without compromising the ideals HTerminal has about backwards compatibility.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Next steps on this project:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Think more about specific features that would improve my own productivity.&lt;/li&gt;
&lt;li&gt;Build them into HTerminal.&lt;/li&gt;
&lt;/ol&gt;
</content:encoded></item><item><title>Dev Diaries - May 28, 2018</title><link>https://cgamesplay.com/post/2018/05/28/glish-dev-diaries/</link><guid isPermaLink="true">https://cgamesplay.com/post/2018/05/28/glish-dev-diaries/</guid><description>Work focused on defining how glish programs run, including their structure and exports, while planning future improvements like a visitor pattern and a board game app for testing.

</description><pubDate>Mon, 28 May 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;If you haven’t heard of glish before, check out the post &lt;a href=&quot;https://cgamesplay.com/post/2018/05/23/what-is-glish&quot;&gt;What is Glish?&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Most of my work this week went into thinking about how glish programs will be run. Writing &lt;a href=&quot;https://cgamesplay.com/post/2018/05/23/what-is-glish&quot;&gt;What is Glish?&lt;/a&gt; was part of that process and helped me crystalize what the main interfaces should be. There are basically 2 ways that glish programs will be run:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Embedded in a dedicated app.&lt;/strong&gt; This is the main case. Some host program keeps track of domain specific items, like items and carts and discounts, and glish is brought in to control the interactions between those items. Glish manuals will define some well-known rulebooks and/or phrases, and the host program will call them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;As a standalone program.&lt;/strong&gt; This is actually a special case of the dedicated app case. Here, the host program is very minimal, only looking for an initial rulebook export to call and then letting glish take over. In this mode, there is deliberately minimal sandboxing, so the glish manual can use code literals to do things like import other modules or interact with the system.&lt;/p&gt;
&lt;p&gt;This means that the overall structure of an application that uses glish (either glish-node standalone or embedding programs) will look like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Core application logic&lt;/strong&gt;, written in the native language, including code to load glish and call well-known rulebooks and phrases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Domain-specific glish runtime&lt;/strong&gt;, written in glish and bundled with the application. This should create the well-known rulebooks and create interfaces for any exposed native interfaces (for example, if your native code provides an &lt;code dir=&quot;auto&quot;&gt;applyDiscount&lt;/code&gt; method, this manual would set up the phrase, “To take (x - a number) from (c - a cart)”).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Manual with business logic&lt;/strong&gt;, also written in glish and loaded by the app at runtime. This will add rules to the rulebooks and defines the actual “business logic” that glish is responsible for.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Based on this, I’ve taken the approach that glish compiles to a CommonJS module, and there are some helpers to load the module with or without sandboxing. But what should the exports of these modules be?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Objects&lt;/strong&gt; are difficult to export because glish property names don’t make convenient JS identifiers, and because properties in glish are type checked at compile time, but the exposed properties should be type checked at run time. The generator will need to provide a wrapper with get/set methods for the properties.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Phrases&lt;/strong&gt; are very easy to export because method calls already have runtime type checking. However, if objects are received/returned, they will need to be unwrapped/wrapped.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Variables&lt;/strong&gt; could be exported similarly to object properties, but I’m not actually sure that exporting variables is a common enough use case to merit being built in to glish. It’s trivial to manually create a getter/setter phrase and export that.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Rulebooks&lt;/strong&gt; are the main use case for glish so exporting them should be built in. It’s easy to create a syntactic sugar for exporting a “follow rulebook” phrase automatically. I don’t think editing the rules of rulebooks will be a common use case, and again the user could manually create phrases to accomplish this quite easily.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Putting this together, here’s a sample hello world manual and script:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;To run the program (exported as `main`):
  say &quot;Hello, world!&quot;.
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;To say (x - a value): `console.log(x)`.
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;javascript&quot;&gt;const source = compile([ &quot;stdlib.glish&quot;, &quot;manual.glish&quot;);
const mod = loadModule(source, { console });
mod.main();
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;in-the-future&quot;&gt;In the future&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The progress this week was mostly conceptual rather than code, but was useful for helping me lay down the proper interfaces.&lt;/p&gt;
&lt;p&gt;I need to move the compiler to using a visitor pattern. This will make it much easier for me to do things like static overload resolution, dead code removal, function inlining, and type checking; plus it will be easier to test specific parts of the generator. This will require me making the &lt;code dir=&quot;auto&quot;&gt;Program&lt;/code&gt; internal representation a little more homogenous that currently, and I need to think about how indexes will be generated as well, which will be affected.&lt;/p&gt;
&lt;p&gt;My upcoming project list:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Create a board game app that can load glish manuals for the rules. I probably won’t be able to finish this, but it should be a good highlight of the missing glish features.&lt;/li&gt;
&lt;li&gt;Migrate the code generator to a visitor pattern; build a program index data structure.&lt;/li&gt;
&lt;li&gt;Have the generator create wrappers for object types returned from phrases.&lt;/li&gt;
&lt;li&gt;Continue working on the glish langauge (self-referential descriptions, etc).&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>What is Glish?</title><link>https://cgamesplay.com/post/2018/05/23/what-is-glish/</link><guid isPermaLink="true">https://cgamesplay.com/post/2018/05/23/what-is-glish/</guid><description>Glish is a programming language designed for writing prose-like manuals that define rules and behaviors for applications, making it easier for non-technical users to understand complex relationships.

</description><pubDate>Wed, 23 May 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Glish is a programming language used to write manuals that other programs can use to influence their behavior. In glish, you don’t write a program; you write write a manual, which is a set of rules that another program can reference.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;an-example&quot;&gt;An Example&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Imagine that you are making an ecommerce application and need to support some discounts for various situations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;First-time buyers get a 10% discount.&lt;/li&gt;
&lt;li&gt;Any accessory is 50% off with the purchase of a protection plan.&lt;/li&gt;
&lt;li&gt;All accessories are on a 15% sale right now.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A glish manual to support these discounts might look like this:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;Discount for an order from a first-time user:
  take 10% from the grand total.
Discount for an order containing a protection plan and an accessory:
  take 50% from the most expensive accessory in the order.
Discount:
  take 15% from each accessory in the order.
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Glish probably does not look like any other programming language you’ve seen. The syntax is very prose-like, but under the hood this syntax precisely compiles to a specific implementation. In that example, each of the three sentences describes a rule. Breaking down the first sentence, we have:&lt;/p&gt;
&lt;p&gt;In the first sentence, “Discount for an order from a first-time user” forms the preamble of the rule. The first part, “Discount for”, says that the rule will live among the discount rules; and the second part, “an order from a first-time user”, is a description of an order. This particular glish manual understands what orders and users are, as well as that orders are “from” a user, and that users can be “first-time” or not. The remainder of the first sentence forms the body of the rule, and this particular manual understands that it can “take” some amount “from the grand total”.&lt;/p&gt;
&lt;p&gt;The program that wants to reference the glish manual needs to provide definitions for concepts like “orders”, or what it means to “take from the grand total”, but once that has been done then any manual that uses these concepts can be referenced.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;why-glish&quot;&gt;Why Glish?&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;The main priorities for glish are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To provide rulebooks for other programs to use. Rulebooks can be used for things like validating inputs, or for applying effects in response to certain circumstances.&lt;/li&gt;
&lt;li&gt;To allow authors to describe complex rules easily. The condition under which a rule applies is built from simple pieces which can be composed together to express complex relationships.&lt;/li&gt;
&lt;li&gt;To allow non-technical users to read and understand the code. Glish source is very English-like, and glish provides tools to diagnose the exact behavior of programs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Glish is ideal in situations where the complexity is in the relationship between things, rather than in the things themselves. In the ecommerce example above, the core concepts in the application are orders, users, and items. Glish enters the picture to bring those concepts together.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;trivia&quot;&gt;Trivia&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Glish draws very heavily from &lt;a href=&quot;http://inform7.com&quot;&gt;Inform7&lt;/a&gt;, a programming language for writing interactive fiction. I first learned about Inform7 from &lt;a href=&quot;https://ericlippert.com/2015/05/11/wizards-and-warriors-part-five/&quot;&gt;a blog post by Eric Lippert&lt;/a&gt;, and was struck by the expressivity of the descriptions in the rule definitions. Once I started to dig in, I realized that the concepts used in Inform7 are useful in a variety of other contexts, which is why I set out to create a more general-purpose version of it. Along the way, I added additional flexibility to the language and removed some constructs that were specific to interactive fiction, but the language is similar in spirit as well as in syntax.&lt;/p&gt;
&lt;p&gt;The name “glish” comes from a joke my high school English teacher used to say when we made grammatical mistakes. “You’re not even writing full English, just ’glish!” Since glish looks like English, but is a smaller, quirkier subset, I thought the name was appropriate.&lt;/p&gt;
</content:encoded></item><item><title>Dev Diaries - May 21, 2018</title><link>https://cgamesplay.com/post/2018/05/21/glish-dev-diaries/</link><guid isPermaLink="true">https://cgamesplay.com/post/2018/05/21/glish-dev-diaries/</guid><description>Reflecting on the ongoing development of Glish, I&apos;ve encountered challenges with rulebooks, property assertions, types, and features like named outcomes and self-referential descriptions, guiding my next steps forward.

</description><pubDate>Mon, 21 May 2018 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;em&gt;If you haven’t heard of glish before, check out the post &lt;a href=&quot;https://cgamesplay.com/post/2018/05/23/what-is-glish&quot;&gt;What is Glish?&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;This is the first in a series I’ll be publishing on my experiences creating a new programming language. I’ve been working on Glish since late 2015. It’s gone through several complete rewrites as I’ve learned more about how the eventual programming language should look, but this epoch is trending in a direction that might be workable. I recently started writing notes about my progress to help coalesce my thoughts and direct my development efforts. I typically do this at the end of any day I make a commit to the repo, so this is just a dump of those notes. As time moves on, I might add more cohesion to these updates.&lt;/p&gt;
&lt;!-- excerpt --&gt;
&lt;div&gt;&lt;h2 id=&quot;2018-05-15&quot;&gt;2018-05-15&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;First implementation of rulebooks done today. There are lots of problems:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;no way to query the outcome of a rulebook&lt;/li&gt;
&lt;li&gt;no named outcomes&lt;/li&gt;
&lt;li&gt;rulebooks cannot have a basis&lt;/li&gt;
&lt;li&gt;rulebooks cannot produce a value&lt;/li&gt;
&lt;li&gt;the implementation is a massive pile of hand-written AST nodes and code literals&lt;/li&gt;
&lt;li&gt;there is very little testing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I like the implementation where it creates a separate program to merge in, but there has to be an easier way to create the program.&lt;/p&gt;
&lt;p&gt;Inform’s rulebooks which produce values are allowed to “succeed producing value”, “fail” and “make no decision”. Additionally, rulebooks that “don’t produce values” can set named outcomes and produce any of those outcomes as well as “make no decision”.&lt;/p&gt;
&lt;p&gt;Rulebooks need quite a bit of other work before I can really continue on them:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;enumerated types are going to form the basis for named outcomes&lt;/li&gt;
&lt;li&gt;loop constructs are going to be key to removing the code literals from the implementation&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;h2 id=&quot;2018-05-16&quot;&gt;2018-05-16&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Was able to get a basic kind of either-or property implemented today. There are obviously problems.&lt;/p&gt;
&lt;p&gt;The assertion &lt;code dir=&quot;auto&quot;&gt;now X is Y&lt;/code&gt; always makes a new instance, it doesn’t understand asserting something about an existing value. I need to modify &lt;code dir=&quot;auto&quot;&gt;analyzeAssertion&lt;/code&gt; to somehow detect whether or not to allocate a new variable versus modify the properties on an existing one, including asserting new facts about a global variable.&lt;/p&gt;
&lt;p&gt;Conditions can only check a single adjective because they are matching phrases rather than descriptions. I should modify the description matcher to take an “expected kind” to allow descriptions which don’t include a kind.&lt;/p&gt;
&lt;p&gt;All my properties are all checked with &lt;code dir=&quot;auto&quot;&gt;===&lt;/code&gt;, so I need to make sure that default values get set properly.&lt;/p&gt;
&lt;p&gt;I also noticed that the “variable initialized somewhere else” error doesn’t show its position correctly in the error messsage.&lt;/p&gt;
&lt;p&gt;I think the next course of action should be fixing up the first two problems here, then moving on to adjectives describing value properties.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;2018-05-19&quot;&gt;2018-05-19&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Types for phrases of one arg and rulebooks are implemented fairly well now. Here are my thoughts on my next steps:&lt;/p&gt;
&lt;p&gt;Enumerated properties are necessary for named rulebook outcomes, and named rulebook outcomes will require some thought as to the phrasing and structure they permit. Enumerated properties are also holding up my implementation of Bohnanza, because I use them for turn phases.&lt;/p&gt;
&lt;p&gt;My Nim example doesn’t work because &lt;code dir=&quot;auto&quot;&gt;process&lt;/code&gt; and &lt;code dir=&quot;auto&quot;&gt;require&lt;/code&gt; aren’t exposed to the running code. I looked into how &lt;code dir=&quot;auto&quot;&gt;babel-node&lt;/code&gt; exposes &lt;code dir=&quot;auto&quot;&gt;require&lt;/code&gt;, and it ends up doing it through a require hook using pirates. This would require a bit of a refactor in the compiler, but shouldn’t be too hard. I think I should probably focus on the entry points into glish programs before going on too much further.&lt;/p&gt;
&lt;p&gt;The only other problem I can see right now is around descriptions. I want to be able to say “taking the actor” and have it match taking actions where the actor is the object.&lt;/p&gt;
&lt;p&gt;I think my list of priorities should look like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Implement this “taking the actor” self-referential description type.&lt;/li&gt;
&lt;li&gt;Think about how glish programs will be run.&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Setting up RetroPie</title><link>https://cgamesplay.com/post/2016/01/03/setting-up-retro-pie/</link><guid isPermaLink="true">https://cgamesplay.com/post/2016/01/03/setting-up-retro-pie/</guid><description>Set up RetroPie on a Raspberry Pi B+ to play classic games, connect to a Time Capsule for ROM storage, and enhance the experience with faster tools and potential improvements.

</description><pubDate>Sun, 03 Jan 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I wanted to play some old video games, and I had a Raspberry Pi B+ lying around, so I thought I would check out &lt;a href=&quot;http://blog.petrockblock.com/retropie/&quot;&gt;RetroPie&lt;/a&gt; and get that working.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;flashing-an-image-to-an-sd-card-using-os-x&quot;&gt;Flashing an image to an SD card using OS X&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I downloaded the image (I used retropie-v3.3.1-rpi1), flashed it to a 4GB SD card, and set up the Pi.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;span&gt;&lt;/span&gt;&lt;span&gt;Terminal window&lt;/span&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;bash&quot;&gt;$ mount
# Looking for my SD card
/dev/disk2s1 on /Volumes/NO NAME (msdos, local, nodev, nosuid, noowners)


$ diskutil unmountDisk /dev/rdisk2
Unmount of all volumes on disk2 was successful


$ sudo dd bs=1m if=Downloads/torrent/retropie-v3.3.1-rpi1.img of=/dev/rdisk2
# ^T will show you the progress here


$ diskutil unmountDisk /dev/rdisk2
Unmount of all volumes on disk2 was successful
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;finding-your-hard-wired-pi-without-keyboard-access&quot;&gt;Finding your hard-wired Pi without keyboard access&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I use a MacBook as my primary computer and don’t have any other keyboard, so typing on the Pi was my first difficulty. The Pi may output its IP address during the bootup process, but I didn’t catch it. Fortunately, this is pretty easy to work around for a hard-wired Pi: I can just use the default hostname. This wouldn’t work if my Pi had been using wifi, because I would have needed to configure the SSID and password, but I’m fine since I am using a wire.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;$ ping retropie.local
ping: cannot resolve retropie.local: Unknown host
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;In this case, the hostname didn’t work. Maybe my router was misconfigured, or maybe this distribution doesn’t support this feature. Still, we can use nmap to find the IP address, then ssh in using the default login (&lt;code dir=&quot;auto&quot;&gt;pi&lt;/code&gt; / &lt;code dir=&quot;auto&quot;&gt;raspberry&lt;/code&gt;):&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;$ nmap 10.0.1.\*


Starting Nmap 6.46 ( http://nmap.org ) at 2016-01-01 18:24 PST
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;I’m going to be looking for something with ssh running. My Pi ended up being this one:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;Nmap scan report for 10.0.1.17
Host is up (0.018s latency).
Not shown: 997 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds


Nmap done: 256 IP addresses (5 hosts up) scanned in 55.26 seconds


$ ssh 10.0.1.17 -l pi
pi@10.0.1.17&apos;s password:
Linux retropie 4.1.13+ #826 PREEMPT Fri Nov 13 20:13:22 GMT 2015 armv6l


The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.


Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sun Jul 20 17:08:12 2014


  .~~.   .~~.    Saturday,  2 January 2016,  2:26:08 am UTC
 &apos;. \ &apos; &apos; / .&apos;   Linux 4.1.13+ armv6l GNU/Linux
  .~ .~~~..~.
 : .~.&apos;~&apos;.~. :   Filesystem      Size  Used Avail Use% Mounted on
~ (   ) (   ) ~  /dev/root       2.3G  2.0G  168M  93% /
( : &apos;~&apos;.~.&apos;~&apos; : ) Uptime.............: 0 days, 00h05m18s
~ .~       ~. ~  Memory.............: 132632kB (Free) / 250352kB (Total)
 (   |   |   )   Running Processes..: 71
 &apos;~         ~&apos;   IP Address.........: 10.0.1.17
   *--~-~--*     Temperature........: CPU: 41°C/105°F GPU: 41°C/105°F
                 The RetroPie Project, http://www.petrockblock.com




pi@retropie ~ $
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;setting-up-afp-to-connect-to-a-time-capsule&quot;&gt;Setting up AFP to connect to a Time Capsule&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;Now that I had the keyboard set up I proceeded to use the on-TV instructions to set up an XBox 360 wired controller. Then it was time to set up some games. My games are stored on a Time Capsule file server, so I will need to set up that service. I basically followed &lt;a href=&quot;http://elinux.org/Mounting_AFP_Shares_To_a_Mac_Over_Local_Network&quot;&gt;this guide&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;pi@retropie ~ $ sudo service samba stop
pi@retropie ~ $ sudo update-rc.d samba disable
# These two disable the samba sharing service. This isn&apos;t necessary, but I
# am not going to use it.
pi@retropie ~ $ sudo apt-get install fuse afpfs-ng
pi@retropie ~ $ sudo usermod -aG fuse pi
# Log out and back in
pi@retropie ~ $ sudo chown root:fuse /dev/fuse
pi@retropie ~ $ sudo chmod 660 /dev/fuse
pi@retropie ~ $ sudo mkdir -p /mnt/TimeCapsule/Data
pi@retropie ~ $ sudo chown -R pi:pi /mnt/TimeCapsule/
pi@retropie ~ $ mount_afp afp://&quot;Ryan Patterson&quot;:&quot;REDACTED&quot;@10.0.1.1/Data /mnt/TimeCapsule/Data
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;Note for anyone following along here, I was getting an obnoxious error that was quite difficult to track down. The error was:&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;Mounting 10.0.1.1 from Data on /mnt/TimeCapsule/Data
Unmounting volume Data from /mnt/TimeCapsule/Data
Unknown error 1, 1.
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;This error is very uninformative, but I was able to use strace to find out that the problem was related to not having the &lt;code dir=&quot;auto&quot;&gt;fusermount&lt;/code&gt; program installed. This is provided by the &lt;code dir=&quot;auto&quot;&gt;fuse&lt;/code&gt; package, so make sure to install that.&lt;/p&gt;
&lt;div&gt;&lt;h2 id=&quot;trying-again-with-cifs&quot;&gt;Trying again with CIFS&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I spent a lot of time trying to set up the connection to the service using AFP, but the daemon was crashing and I decided to switch to using CIFS, which was much easier to set up as well.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;pi@retropie ~ $ sudo service samba stop
pi@retropie ~ $ sudo update-rc.d samba disable
# These two disable the samba sharing service. This isn&apos;t necessary, but I
# am not going to use it.
pi@retropie ~ $ sudo mount -v -t cifs //10.0.1.1/Data /mnt/TimeCapsule/Data -o user=&quot;Ryan Patterson&quot;,pass=&quot;REDACTED&quot;,file_mode=0644,dir_mode=0755,sec=ntlm,uid=1000,gid=1000,noserverino
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;p&gt;I also needed to add a line to my /etc/fstab so that the share would be mounted on reboot (&lt;code dir=&quot;auto&quot;&gt;\040&lt;/code&gt; is how you escape a space in fstab):&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;//10.0.1.1/Data /mnt/TimeCapsule/Data cifs user=Ryan\040Patterson,pass=REDACTED,file_mode=0644,dir_mode=0755,sec=ntlm,uid=1000,gid=1000,noserverino 0 0
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;using-the-scraper-with-cifs&quot;&gt;Using the scraper with CIFS&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;I had a collection of ROMs and wanted to get the titles / box art in EmulationStation. EmulationStation’s builtin scraper is ludicrously slow and only does 1 game at a time however, so I searched around and found a faster program that lives in the RetroPie “experimental” section, called &lt;a href=&quot;https://github.com/sselph/scraper&quot;&gt;Sselph’s Scraper&lt;/a&gt;. However, it has a problem where it doesn’t follow symlinks, which means that my symlinked ROMs folder isn’t scanned. The workaround is as simple as adding a trailing slash to the pathname and running the scraper manually.&lt;/p&gt;
&lt;div&gt;&lt;figure&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;pre data-language=&quot;plaintext&quot;&gt;/opt/retropie/supplementary/scraper/scraper -image_dir /home/pi/.emulationstation/downloaded_images/snes -image_path /home/pi/.emulationstation/downloaded_images/snes -output_file /home/pi/.emulationstation/gamelists/snes/gamelist.xml -rom_dir /home/pi/RetroPie/roms/snes/ -workers 4 -thumb_only -skip_check
&lt;/pre&gt;&lt;div&gt;&lt;div aria-live=&quot;polite&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;/figure&gt;&lt;/div&gt;
&lt;div&gt;&lt;h2 id=&quot;future-ideas&quot;&gt;Future ideas:&lt;/h2&gt;&lt;/div&gt;
&lt;p&gt;While I was working on this project, I kept a list of the things that could be better. Maybe this will give you an idea for how to improve RetroPie.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I’d like to fix the wired XBox 360 controller blinking LED. Looks like the kernel module (xpad) does not have LED support compiled in?&lt;/li&gt;
&lt;li&gt;I want a power switch for the Pi so I don’t have to unplug the device to turn it off. Ideally, I’d like to find out how to get something that allows wireless xbox 360 controllers to power on the device using the button.&lt;/li&gt;
&lt;li&gt;The libretro GUI (rgui) is rather primitive, and doesn’t seem to be able to save configuration changes in the latest release.&lt;/li&gt;
&lt;li&gt;I would like to automatically restore my save state when I power on an emulator.&lt;/li&gt;
&lt;li&gt;I’d like to upgrade to a Raspberry Pi 2 and get N64 emulation running.&lt;/li&gt;
&lt;li&gt;The bootup time is pretty high. What could be shaved out to speed it up?&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item></channel></rss>