### Cherri Package Usage Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Shows how to include and use functions from an external Cherri package. Ensure the package is installed using `cherri --install=` before including it. ```cherri #define name Using Packages #include '@electrikmilk/device-info' // device-info package provides deviceInfo() function const info = deviceInfo() const model = getValue(@info, "model") alert("Device model: {@model}") ``` -------------------------------- ### Package Manifest (cherri.lock) Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Example structure of the `cherri.lock` file, which is in plist format and lists all installed Cherri packages. ```xml Packages @author/device-info @author/network-utils ``` -------------------------------- ### Package Info.plist Structure Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Example structure for the `info.plist` file, which contains metadata for a Cherri package, including its Name, Version, Author, and Description. ```xml Name Device Info Version 1.0.0 Author Author Name Description Package description ``` -------------------------------- ### Cherri Package Installation Logic Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Go function implementing the Cherri package installation process. It handles cloning the repository using `git.PlainClone` and includes verification steps for package files. ```go func (pkg *cherriPackage) install() bool { var packagePath = pkg.path() var _, cloneErr = git.PlainClone(packagePath, false, &git.CloneOptions{ URL: pkg.url(), SingleBranch: true, Depth: 5, }) if cloneErr != nil { pkg.failed(cloneErr) return false } // Verify main.cherri and info.plist exist return true } ``` -------------------------------- ### Install Cherri via Homebrew Source: https://github.com/electrikmilk/cherri/blob/main/ReadMe.md Installs the Cherri command-line tool using Homebrew. Ensure you have run 'brew tap electrikmilk/cherri' first. ```bash brew install electrikmilk/cherri/cherri ``` -------------------------------- ### Example Shortcuts Action Plist Source: https://github.com/electrikmilk/cherri/blob/main/CLAUDE.md This is an example of how a Shortcuts action is represented in plist format, showing the workflow action identifier and parameters. ```xml WFWorkflowActionIdentifier is.workflow.actions.gettext WFWorkflowActionParameters WFTextActionText hello ``` -------------------------------- ### Plist XML Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Provides an example of a Property List (plist) XML structure, commonly used for configuration. This snippet shows a dictionary with a specific workflow action identifier. ```xml WFWorkflowActionIdentifier is.workflow.actions.alert ``` -------------------------------- ### Install package Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/1-overview.md Installs a package using the Cherri compiler's package manager. ```bash cherri --install @author/package ``` -------------------------------- ### Cherri Menu Usage Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/7-control-flow.md An example demonstrating how to define a menu in Cherri with options and associated results. This syntax is used to create interactive choices within a shortcut. ```cherri menu myMenu { item "Option A" { @result = "A" } item "Option B" { @result = "B" } } ``` -------------------------------- ### Cherri Array Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/6-value-generation.md Shows how a simple Cherri array of numbers is converted into a Go WFArrayValue. ```cherri @numbers = [1, 2, 3] ``` ```go WFArrayValue{ WFArray: []any{1, 2, 3}, } ``` -------------------------------- ### Basic Hello World in Cherri Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Demonstrates the most basic Cherri script to display a 'Hello, world!' message using the alert action. Requires no special setup. ```cherri #define name Hello World #define color blue #define glyph hello alert("Hello, world!") ``` -------------------------------- ### Go Code Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Demonstrates a basic Go function structure. This is a standard Go code block. ```go func example() { // Go source code } ``` -------------------------------- ### Load Toolkit Database in Go Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Example of opening a SQLite database connection in Go using the 'sqlite3' driver, intended for loading action metadata. ```go func loadToolKit() { var db, err = sql.Open("sqlite3", toolkitPath) // Query tables for action definitions, parameters, etc. } ``` -------------------------------- ### Manage Cherri Packages Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Initialize a new package, install, remove, or list packages. Use --tidy to clean up package dependencies. ```bash # Package management cherri --init=@author/name cherri --install=@author/name cherri --remove=@author/name cherri --packages cherri --tidy ``` -------------------------------- ### List installed packages Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/1-overview.md Lists all installed packages managed by the Cherri compiler. ```bash cherri --packages ``` -------------------------------- ### Install Cherri via Nix Source: https://github.com/electrikmilk/cherri/blob/main/ReadMe.md Installs Cherri using the Nix package manager. This command adds Cherri to your user profile. ```bash nix profile install github:electrikmilk/cherri ``` -------------------------------- ### Install a Cherri Package Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Command to install a Cherri package. This process involves parsing the signature, resolving the Git URL, cloning the repository, and verifying essential package files. ```bash cherri --install=@author/package_name ``` -------------------------------- ### Cherri Package Management Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Manages Cherri packages, including initialization, installation, removal, listing, and updating. Use `--init`, `--install`, `--remove`, `--packages`, and `--tidy`. ```bash cherri --init=@author/package # Create package ``` ```bash cherri --install=@author/package # Install ``` ```bash cherri --remove=@author/package # Remove ``` ```bash cherri --packages # List installed ``` ```bash cherri --tidy # Update all ``` -------------------------------- ### Function Call Structure Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/6-value-generation.md Illustrates the structure of a function call dictionary, showing how arguments, including serialized variables and literals, are represented. ```Go var callDict = map[string]any{ "cherri_functions": 1, "function": functionName, "arguments": []any{ "{varRef1}", // Variable serialized as string "literal", // Literal value // ... }, } ``` -------------------------------- ### Combined Metadata Directives Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Demonstrates the use of #define, #include, and #question directives at the top of a Cherri file for configuration and setup. ```cherri #define name My App #define color blue #include 'actions/device' #question apiKey "API Key" text #question verbose "Verbose output" bool = false // Main Shortcut code const key = @apiKey if @verbose { alert("Starting...") } ``` -------------------------------- ### List Installed Cherri Packages Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Commands to list installed Cherri packages. `--packages` shows all installed packages with their details, while `--package` shows information about the current package. ```bash # Show all installed packages cherri --packages # Show current package info cherri --package ``` -------------------------------- ### Get Cherri Version and Help Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Displays the current Cherri CLI version or shows the help message with all available commands and options. ```bash cherri --version # Version ``` ```bash cherri --help # Help ``` -------------------------------- ### Cherri Dictionary Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/6-value-generation.md Illustrates how a Cherri dictionary literal is represented as a Go WFDictionaryFieldValue structure. ```cherri @data = {"name": "John", "age": 30} ``` ```go WFDictionaryFieldValue{ WFDictionaryFieldValueItems: []WFDictionaryFieldValueItem{ { WFKey: "name", WFItemType: 0, // String WFValue: WFTextTokenString{Value: WFTextTokenStringValue{String: "John"}}, }, { WFKey: "age", WFItemType: 1, // Number WFValue: 30, }, }, } ``` -------------------------------- ### packages.go Structures and Functions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Defines structures and functions for managing Cherri packages, including installation and removal. ```APIDOC ## cherriPackage ### Description Represents the definition of a Cherri package. ### Structure ```go type cherriPackage struct { // Fields defining the package } ``` ``` ```APIDOC ## initPackage() ### Description Initializes a new Cherri package. ### Signature `initPackage(packageName string)` ### Parameters #### Path Parameters - **packageName** (string) - Required - The name of the package to initialize. ``` ```APIDOC ## install() ### Description Clones and installs a Cherri package from a remote repository. ### Signature `install(repositoryURL string)` ### Parameters #### Path Parameters - **repositoryURL** (string) - Required - The URL of the package repository. ``` ```APIDOC ## removeFiles() ### Description Deletes the files associated with an installed Cherri package. ### Signature `removeFiles(packageName string)` ### Parameters #### Path Parameters - **packageName** (string) - Required - The name of the package to remove. ``` -------------------------------- ### Nix Flake Configuration for Cherri Source: https://github.com/electrikmilk/cherri/blob/main/ReadMe.md Example Nix flake.nix configuration to include Cherri in a development environment. This allows Cherri to be available when using tools like nix-direnv. ```nix { inputs.cherri.url = "github:electrikmilk/cherri"; { # outputs.packages.${system}.default = pkgs.mkShell etc - omitted for brevity buildInputs = [ inputs.cherri.packages.${system}.cherri ] } } ``` -------------------------------- ### Cherri Control Flow Source: https://github.com/electrikmilk/cherri/blob/main/AGENTS.md Shows examples of if/else statements, repeat loops, for-each loops, and assigning control flow output to constants. ```ruby // If / else if @x > 0 { // ... } else { // ... } // Operators: == != > >= < <= contains !contains beginsWith endsWith <> (between) // Logical: && (all) || (any) // Has value: if @x { } / if !@x { } // Between: if @x <> 5 10 { } // Repeat N times (i is the index variable) repeat i for 6 { @items += "Item {@i}" } // For-each @items = ["a","b","c"] for item in @items { alert("@item") } // Control flow output (assign result to a constant) const result = if @x == "iPhone" { getCellularDetail("Carrier Name") } else { getWifiDetail("Network Name") } ``` -------------------------------- ### Cherri Source Code Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Illustrates a basic Cherri source code snippet using preprocessor directives and comments. This is specific to the Cherri language. ```cherri #define name Example // Cherri source code ``` -------------------------------- ### Text Processing with Text Actions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Demonstrates various text manipulation functions available in the `actions/text` module, including trimming whitespace, converting to uppercase, and replacing substrings. The example shows the final processed string. ```cherri #define name Text Processing #include 'actions/text' @input = " hello world " // Trim whitespace const trimmed = replaceText(@input, " ", "") // Convert to uppercase const upper = uppercase(@trimmed) // Replace text const replaced = replaceText(@upper, "WORLD", "CHERRI") alert("@replaced") // "HELLO CHERRI" ``` -------------------------------- ### Making Network Requests and Parsing JSON Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Illustrates how to make an HTTP GET request to a weather API, parse the JSON response into a dictionary, and extract specific data. It uses `#question` for dynamic input and string interpolation for the URL. ```cherri #define name Weather Lookup #include 'actions/network' #question city "Which city?" text = "New York" const url = "https://api.weather.com/weather?city={@city}" const response = getContentsOfURL(@url) const data = getDictionary(@response) const temp = getValue(@data, "temperature") alert("Temperature in {@city}: {@temp}°F") ``` -------------------------------- ### Array Operations with List Actions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Shows how to perform common operations on arrays using functions from the `actions/list` module. It includes getting the first, last, and a random item from an array. ```cherri #define name Array Operations #include 'actions/list' @colors = ["red", "green", "blue"] const firstColor = getFirstItem(@colors) const lastColor = getLastItem(@colors) const randomColor = getRandomItem(@colors) alert("First: {@firstColor}, Last: {@lastColor}, Random: {@randomColor}") ``` -------------------------------- ### Expense Tracker: Record Expenses to CSV Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md A real-world example that parses user input for an expense, converts it to a number, formats a timestamp, and appends the data as a CSV line to a specified file. It showcases input parsing, type coercion, file I/O, and string building. ```cherri #define name Expense Tracker #define inputs text #define outputs file #include 'actions/files' #include 'actions/text' #include 'actions/list' #question filePath "Where to save?" text = "/tmp/expenses.csv" // Parse input: "Coffee: 5.50" @input = ShortcutInput const parts = splitText(@input, ":") const description = getFirstItem(@parts) const amount = number(getLastItem(@parts)) // Format timestamp @timestamp = CurrentDate // Create CSV line @line = "{@description},{@amount},{@timestamp}\n" // Append to file const fileContents = getFileContents(@filePath) const newContents = "{@fileContents}{@line}" writeFile(@filePath, @newContents) output("Recorded: {@description} ${@amount}") ``` -------------------------------- ### File Handling in Main Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Sets up global file path variables and reads the entire file content into a string. Handles potential read errors. ```go func handleFile() { relativePath = strings.Replace(filePath, filename, "", 1) var nameParts = strings.Split(filename, ".") basename = nameParts[0] workflowName = basename var fileBytes, readErr = os.ReadFile(filePath) handle(readErr) contents = string(fileBytes) } ``` -------------------------------- ### Usage of Magic Variables in Cherri Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Demonstrates how to use built-in magic variables within Cherri workflows for common tasks like getting input, date, and device information. Shows usage within loops for repeat item and index. ```cherri @input = ShortcutInput // Get workflow input @now = CurrentDate // Current date/time @cb = Clipboard // Clipboard contents @device_name = Device // Device info @user_input = Ask // User ask response // In loops: repeat i for 10 { @item = RepeatItem // Current loop item @index = RepeatIndex // Loop counter (1-based) } ``` -------------------------------- ### Define and Use Functions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Demonstrates defining and calling functions with typed parameters and return values. The 'output()' action is used to return values from functions. ```cherri #define name Function Demo function multiply(number a, number b): number { @result = @a * @b output(@result) } function greet(text name): text { output("Hello, {@name}!") } const product = multiply(6, 7) const greeting = greet("Alice") alert("@greeting\nProduct: {@product}") ``` -------------------------------- ### Define Basic Shortcut Metadata Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Use #define directives to set fundamental properties like name, color, glyph, inputs, outputs, version, platform, and origin. ```cherri #define name My Workflow #define color blue #define glyph apple #define inputs image, text #define outputs file #define version 1.0.0 #define mac true #define from menubar, sharesheet #define noinput stopwith "No input" ``` -------------------------------- ### Shortcut Generation (`generateShortcut()` in shortcutgen.go) Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Initializes the shortcut structure and concurrently generates metadata like input/output content item classes and import questions. This function orchestrates the creation of the shortcut's core data. ```go func generateShortcut() { shortcut = Shortcut{ WFWorkflowIcon: ShortcutIcon{iconGlyph, iconColor}, WFWorkflowClientVersion: clientVersion, WFWorkflowHasShortcutInputVariables: hasShortcutInputVariables, // ... populate fields } // Parallel generation of metadata waitFor( func() { shortcut.WFWorkflowInputContentItemClasses = generateInputContentItems() }, func() { shortcut.WFWorkflowOutputContentItemClasses = generateOutputContentItems() }, func() { shortcut.WFWorkflowImportQuestions = generateImportQuestions() }, ) generateActions() // Walk tokens and emit plist actions } ``` -------------------------------- ### Type Mismatch Examples Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Illustrates type mismatch errors during parsing. The first example shows an incorrect type for an 'alert' function, and the second shows too many arguments for the 'text' function. ```cherri alert(42) // ERROR: expected text, got number text("hello", "extra") // ERROR: too many arguments ``` -------------------------------- ### Build Cherri Compiler Source: https://github.com/electrikmilk/cherri/blob/main/CLAUDE.md Builds the Cherri compiler binary. Ensure you are in the repository root. ```bash go build ./... ``` -------------------------------- ### DSL Definition with Static Parameter Source: https://github.com/electrikmilk/cherri/blob/main/CLAUDE.md Demonstrates how to define an action with a static parameter using Cherri's DSL, specifying a 'Copy to Clipboard' behavior. ```cherri action 'output' outputOrClipboard(text output: 'WFOutput') { "WFNoOutputSurfaceBehavior": "Copy to Clipboard" } ``` -------------------------------- ### Initialize package management Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/1-overview.md Initializes a new package for the Cherri compiler's package manager. ```bash cherri --init @author/package ``` -------------------------------- ### Check for Comment Ahead Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Checks if a comment (single-line or multi-line) or a pseudo-comment starting with "!" is ahead. ```Go func commentAhead() bool { return (isChar('/') && (isChar('/') || isChar('*'))) || (isChar('"') && isChar('!')) // Pseudo-comment: "! text } ``` -------------------------------- ### Collect Variable Function Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Collects variables, which start with '@'. It reads the identifier and optional type/value, handling assignment operators. ```go func collectVariable() { // Starts with @ // Reads identifier and optional type/value // Emits Variable token // Handles assignment operators (=, +=, -=, *=, /=) } ``` -------------------------------- ### Cherri Compilation Pipeline Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Outlines the sequential steps involved in compiling a .cherri source file into a .shortcut file, from initial file handling to final signing. ```text .cherri source ↓ handleFile() — Read file, split into lines/chars ↓ initParse() — Initialize global state ↓ preParse() — Sequential pre-processing: handleIncludes() — Inline #include files handleFunctions() — Collect functions, inject header handleActionDefinitions() — Collect user-defined actions ↓ parse() — Main tokenization, emit tokens[] ↓ generateShortcut() — Walk tokens[], build plist actions[] ↓ createShortcut() — Serialize to .shortcut file ↓ sign() — Sign (local/remote/custom) ``` -------------------------------- ### Define Cherri Package Structure Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/2-api-reference.md Represents a remote or installed package with its metadata and dependencies. Used in the package management system. ```go type cherriPackage struct { Name string User string Uri string Archived bool Packages []cherriPackage } ``` -------------------------------- ### Menu Selection and Actions in Cherri Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Shows how to create a menu with multiple options using the `menu` block. Each item executes a specific code block, and the result can be stored and displayed. ```cherri #define name Menu Example #define color green menu operation { item "Add" { @result = 5 + 3 } item "Subtract" { @result = 5 - 3 } item "Multiply" { @result = 5 * 3 } item "Divide" { @result = 5 / 3 } } alert("Result: {@result}") ``` -------------------------------- ### Add Homebrew Tap for Cherri Source: https://github.com/electrikmilk/cherri/blob/main/ReadMe.md Adds the official Cherri repository to your Homebrew sources. This is a prerequisite for installing Cherri via Homebrew. ```bash brew tap electrikmilk/cherri ``` -------------------------------- ### Shortcut Serialization (`createShortcut()` in output.go) Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Determines the output path and writes the shortcut data to a file, handling debug output and signing. This function is responsible for the final output of the compiled shortcut. ```go func createShortcut() { outputPath = getOutputPath(workflowName + ".shortcut") if args.Using("debug") { writeShortcut(relativeFile+".plist", workflowName+".plist") } writeShortcut(relativeFile+unsignedEnd, workflowName+unsignedEnd) // Sign if not skipped if !args.Using("skip-sign") { sign() // or useHubSign() or useSigningService() } } ``` -------------------------------- ### Writing Shortcut to Plist (`writeShortcut()` in output.go) Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Serializes the shortcut data into a binary plist format and writes it to the specified file. Includes error handling for marshaling and file writing operations. ```go func writeShortcut(filename string, name string) { var plistBytes, marshalErr = plist.Marshal(shortcut, plist.BinaryFormat) handle(marshalErr) var fileErr = os.WriteFile(filename, plistBytes, 0600) handle(fileErr) } ``` -------------------------------- ### Remove a Cherri Package Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Command to remove an installed Cherri package. This action deletes the package's directory and removes it from the `cherri.lock` file. ```bash cherri --remove=@author/package_name ``` -------------------------------- ### Configure Quick Actions / Sharing Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Define where a Shortcut appears as a quick action using the #define from directive, specifying locations like the menubar or sharesheet. ```cherri #define from menubar, sharesheet ``` -------------------------------- ### Display Cherri Help Information Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Prints usage information and all available arguments for the Cherri CLI. Use either the long or short flag. ```bash cherri --help cherri -h ``` -------------------------------- ### Parameter Definition with Enumeration Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Example of a parameter definition that references an enumeration named 'sortOrder'. This restricts the 'order' parameter to accept only 'asc' or 'desc'. ```go parameterDefinition{ name: "order", validType: String, enum: "sortOrder", key: "WFSortOrder", } ``` -------------------------------- ### Compile a Cherri file Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/1-overview.md Basic command to compile a .cherri file into a .shortcut file. ```bash cherri file.cherri ``` -------------------------------- ### Cherri Version and Help Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Display the Cherri version or access the help information. ```bash # Other cherri --version cherri --help ``` -------------------------------- ### Minimal Go Definition for Get Text Action Source: https://github.com/electrikmilk/cherri/blob/main/CLAUDE.md Provides a minimal Go definition for the 'getText' action, specifying its parameters and output type. ```go "getText": { parameters: []parameterDefinition{ {name: "text", validType: String, key: "WFTextActionText"}, }, outputType: String, }, ``` -------------------------------- ### Initialize a Cherri Package Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Command to initialize a new Cherri package. This creates the necessary local directory structure, boilerplate files, and initializes a Git repository. ```bash cherri --init=@author/package_name ``` -------------------------------- ### Cherri Package Manifest Structure Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Go struct representing the `cherri.lock` package manifest. This structure is used to parse and manage the list of installed packages. ```go type packageManifest struct { Packages []string } ``` -------------------------------- ### signing.go Functions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Functions for signing Cherri Shortcuts using different methods. ```APIDOC ## sign() ### Description Performs local signing of a Cherri Shortcut on macOS. ### Signature `sign(shortcutPath string)` ### Parameters #### Path Parameters - **shortcutPath** (string) - Required - The path to the Shortcut file to sign. ``` ```APIDOC ## useHubSign() ### Description Utilizes the RoutineHub service for remote signing of a Cherri Shortcut. ### Signature `useHubSign(shortcutPath string)` ### Parameters #### Path Parameters - **shortcutPath** (string) - Required - The path to the Shortcut file to sign. ``` ```APIDOC ## useSigningService() ### Description Uses a custom signing server for signing Cherri Shortcuts. ### Signature `useSigningService(shortcutPath string)` ### Parameters #### Path Parameters - **shortcutPath** (string) - Required - The path to the Shortcut file to sign. ``` -------------------------------- ### Go Action Definition Mapping Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/4-action-system.md Maps a Cherri action definition to its Go struct representation. This example shows how the 'gettext' action is defined in Go. ```go "getText": { identifier: "gettext", parameters: []parameterDefinition{ {name: "text", validType: String, key: "WFTextActionText"}, }, outputType: String, } ``` -------------------------------- ### Run Cherri Compiler Source: https://github.com/electrikmilk/cherri/blob/main/CLAUDE.md Compiles a .cherri file into a .shortcut file. The filename must be the first argument. Use --debug to output intermediate files. ```bash go run . file.cherri ``` ```bash go run . file.cherri --debug ``` -------------------------------- ### Cherri Include Directive Syntax Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Demonstrates the different ways to use include directives in Cherri, specifying standard library categories, relative paths, and remote URLs. ```cherri #include 'actions/device' // Standard library category #include 'path/to/file.cherri' // Relative path #include 'https://example.com/file' // Remote URL ``` -------------------------------- ### Collect Comment Function Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Parses and collects comments, which start with // or /* */. Emits a Comment token with an action string, often used for inline documentation. ```go func collectComment() { // Starts with // or /* */ // Emits Comment token with action string // Used for inline Shortcuts actions as documentation } ``` -------------------------------- ### Enumeration Value Examples Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Demonstrates valid and invalid assignments for a parameter restricted by an enumeration. The first assignment is valid because 'red' is in the 'fileLabel' enum, while the second is an error. ```cherri @color = "red" // OK: in fileLabel enum @color = "cyan" // ERROR: not in enum ``` -------------------------------- ### Define a Device Reference Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Use the #ref directive to encode device content pointers for runtime resolution by the Shortcuts app. ```cherri #ref "@john" 'contact-data-encoded-value' ``` ```cherri #ref "@photoLibrary" 'PHAssetCollection:///asset/library/all-photos' // Later in code: @photos = @photoLibrary ``` -------------------------------- ### Convert Binary Plist to XML on macOS Source: https://github.com/electrikmilk/cherri/blob/main/AGENTS.md Convert the downloaded binary `.shortcut` file to a readable XML format using `plutil` on macOS. This step is necessary to compare the structure with Cherri's generated output. ```bash # Convert binary plist to readable XML (macOS) plutil -convert xml1 reference.shortcut -o reference.plist ``` -------------------------------- ### Cherri Mixed Type Array Example Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/6-value-generation.md Demonstrates the representation of a Cherri array containing mixed data types (number, string, boolean) within a Go WFArrayValue. ```cherri @mixed = [1, "text", true] ``` ```go WFArrayValue{ WFArray: []any{ 1, WFTextTokenString{...}, WFBoolValue{true}, }, } ``` -------------------------------- ### output.go Functions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Functions for resolving output file paths, creating, and writing Cherri Shortcuts. ```APIDOC ## getOutputPath() ### Description Resolves the final output file path for the generated Shortcut. ### Signature `getOutputPath(filename string)` ### Parameters #### Path Parameters - **filename** (string) - Required - The base filename for the output. ### Returns - `string`: The resolved output path. ``` ```APIDOC ## createShortcut() ### Description Creates an unsigned Cherri Shortcut file and triggers the signing process. ### Signature `createShortcut(shortcutData interface{}) error` ### Parameters #### Path Parameters - **shortcutData** (interface{}) - Required - The data representing the Shortcut to create. ### Returns - `error`: An error if creation or signing fails, otherwise nil. ``` ```APIDOC ## writeShortcut() ### Description Serializes the Shortcut data into plist format and writes it to the output file. ### Signature `writeShortcut(shortcutData interface{}, outputPath string)` ### Parameters #### Path Parameters - **shortcutData** (interface{}) - Required - The Shortcut data to serialize. - **outputPath** (string) - Required - The path where the Shortcut should be written. ``` -------------------------------- ### Cherri Standard Library Includes Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Lists common standard library categories available for inclusion in Cherri projects, such as device info, text processing, and file system actions. ```cherri #include 'actions/device' // Device info actions #include 'actions/text' // Text processing actions #include 'actions/list' // List/array manipulation #include 'actions/dictionary' // Dict operations #include 'actions/files' // File system actions #include 'actions/network' // Network/HTTP actions // ... more categories ``` -------------------------------- ### Collect Conditional Function Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Parses conditional statements starting with 'if'. It reads the condition and body block, handling optional 'else' blocks, and emits a Conditional token. ```go func collectConditional() { // Starts with "if" // Reads condition and body block // Handles optional "else" block // Emits Conditional token } ``` -------------------------------- ### Action Generation from Tokens (`generateActions()` in shortcutgen.go) Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Iterates through the collected tokens and generates corresponding plist actions for the shortcut. Different token types are mapped to specific action generation functions. ```go func generateActions() { for _, t := range tokens { switch t.typeof { case Variable, AddTo, SubFrom, MultiplyBy, DivideBy: makeVariableAction(&t) case Comment: makeCommentAction(t.value.(string)) case Action: var tokenAction = t.value.(action) makeAction(tokenAction.args, &WFActionReference{}) case Repeat: makeRepeatAction(&t) case If: makeConditionalAction(&t) // ... more action types } } } ``` -------------------------------- ### Get User Input with Cherri Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Shows how to prompt the user for input using `getText` and `getNumber` actions, and then display a personalized message. Supports default values for questions. ```cherri #define name User Input Demo #define inputs text #define outputs text #question greeting "What is your greeting?" text = "Hello" const name = getText("What is your name?") const age = getNumber("How old are you?") alert("{@greeting}, {@name}! You are {@age} years old.") ``` -------------------------------- ### Package Info.plist Dependency Structure Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Example structure for declaring package dependencies within the `info.plist` file. It uses an array of dictionaries, where each dictionary specifies the Name and Author of a dependency. ```xml Dependencies Name network-utils Author author ``` -------------------------------- ### Cherri Package Initialization Function Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Go function stub for initializing a Cherri package. It outlines the steps involved in parsing the package signature, creating the directory structure, initializing Git, and generating boilerplate files. ```go func initPackage() { // Parse package signature // Create directory structure // Initialize git repository // Create boilerplate files } ``` -------------------------------- ### WFMeasurementUnit Cherri Syntax Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/6-value-generation.md Illustrates Cherri syntax for defining physical quantities with units. ```cherri const distance = 5 meters const duration = 30 seconds ``` -------------------------------- ### Cherri Operand Type Examples Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Illustrates various combinations of operands in Cherri expressions, showing how different types (numbers, floats, variables, action outputs) interact during arithmetic operations. ```cherri @x = 5 + 3 // number + number → number @y = 5.5 + 2.1 // float + float → float @z = 5 + 2.5 // number + float → float @a = @var + 10 // variable + number (type depends on var) @b = actionResult() + 5 // action output + number ``` -------------------------------- ### Collect Action Function Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/3-parser-compilation.md Collects actions, which start with an identifier followed by parentheses. It reads arguments until the closing parenthesis, validates against the action definition, and emits an Action token. Arguments are type-checked and coerced. ```go func collectAction() { // Starts with identifier( // Reads arguments until ) // Validates against action definition // Emits Action token // Arguments are type-checked and coerced } ``` -------------------------------- ### main.go Functions Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/INDEX.md Functions for handling command-line arguments, file parsing, user input, and error management. ```APIDOC ## fileArg() ### Description Extracts the filename from command-line arguments. ### Signature `fileArg()` ### Returns - `string`: The filename provided as a command-line argument. ``` ```APIDOC ## handleFile() ### Description Parses the file path and reads its contents. ### Signature `handleFile()` ### Returns - `error`: An error if parsing or reading fails, otherwise nil. ``` ```APIDOC ## checkFile() ### Description Validates if the file exists and has the '.cherri' extension. ### Signature `checkFile(filePath string)` ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the file to check. ### Returns - `bool`: True if the file is valid, false otherwise. ``` ```APIDOC ## yesNo() ### Description Prompts the user for a yes/no input. ### Signature `yesNo(prompt string)` ### Parameters #### Path Parameters - **prompt** (string) - Required - The message to display to the user. ### Returns - `bool`: True if the user answers yes, false if no. ``` ```APIDOC ## camelCase() ### Description Converts a given string to camelCase format. ### Signature `camelCase(input string)` ### Parameters #### Path Parameters - **input** (string) - Required - The string to convert. ### Returns - `string`: The camelCased string. ``` ```APIDOC ## handle() ### Description General error handling mechanism, with support for optional debug output. ### Signature `handle(err error, debug bool)` ### Parameters #### Path Parameters - **err** (error) - Required - The error to handle. - **debug** (bool) - Optional - If true, enables debug error output. ``` -------------------------------- ### Loop Variable Availability Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/8-type-system.md Loop variables are available within their loop's scope. This example shows that a loop variable `i` becomes available inside the loop, while an outer variable `@name` retains its value. ```cherri // Repeat loop items repeat i for 5 { @item = RepeatItem // 'i' becomes available // but @name is still "Jane" } ``` -------------------------------- ### Debug Output: Plist File Structure Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/10-error-handling.md An example of the XML-formatted plist file generated with the --debug flag. This file is useful for comparing against Shortcuts app output and debugging plist structure issues. ```xml WFWorkflowIcon WFWorkflowIconGlyphNumber 59414 WFWorkflowIconStartColor 4 WFWorkflowActions ``` -------------------------------- ### Generate Documentation Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Generates documentation for actions, optionally filtered by category or subcategory. Outputs documentation in markdown or HTML format. ```bash # Generate all action docs cherri --docs ``` ```bash # Generate docs for category cherri --docs=device ``` ```bash # Filter by subcategory cherri --docs=device --subcat=wifi ``` -------------------------------- ### Cherri Type Coercion Examples Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/11-examples.md Demonstrates implicit and explicit type coercion in Cherri, including interpolation and action-based conversions. Note that direct variable type passthrough may cause issues in comparisons. ```cherri #define name Type Coercion Examples @text = "42" @number = 3.14 @bool = true // Coerce in interpolation const s1 = "{@number}" // "3.14" (implicit) const s2 = "{@bool}" // "1" (bool → number → text) // Coerce via action const n1 = number(@text) // 42 const n2 = number(@bool) // 1 // Variable type: no coercion @passthrough: variable = 42 alert("{@passthrough}") // May fail in comparison ``` -------------------------------- ### Custom Decompilation Logic in Cherri Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/4-action-system.md This example shows how to define custom decompilation logic for a specific action like 'setVariable' within the Cherri DSL. The 'decomp' function field allows for tailored output generation. ```json "setVariable": { decomp: func(action *ShortcutAction) []string { // Custom decompilation logic // Return []string of Cherri source lines return []string{"@var = value"} }, } ``` -------------------------------- ### Debug Output: Processed Cherri Source Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/10-error-handling.md An example of the processed Cherri source file generated with the --debug flag. This file shows the source after includes have been processed and action definitions removed, useful for understanding parser behavior. ```cherri // Generated functions header (if functions used) if @input["cherri_functions"] == 1 { switch @input["function"] { case "myFunc": // function body... } } // Original source with: // - #include directives replaced with file contents // - #action definitions removed (parsed) // - metadata intact ``` -------------------------------- ### Define Questions for Shortcut Import Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/9-metadata-directives.md Use #question directives to specify prompts, types, and default values for user input during Shortcut import. Supported types include text, number, and boolean. ```cherri #question myValue "What is your name?" text #question maxCount "Maximum items (default 10)" number = 10 #question useSSL "Enable HTTPS?" bool = true ``` -------------------------------- ### Specify Toolkit Database Path Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/5-cli-features.md Use the --toolkit flag to point Cherri to a specific Shortcuts Toolkit SQLite database file for action lookups during decompilation. ```bash cherri --toolkit=/path/to/ToolKit.db ``` -------------------------------- ### Handle Signing Failures in Go Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/10-error-handling.md This Go code snippet demonstrates how to execute an external command and check for errors during the signing process. It's crucial for ensuring the integrity of the build. ```go func sign() { // macOS codesign command var cmd = exec.Command("codesign", ...) var err = cmd.Run() if err != nil { exit(fmt.Sprintf("Signing failed: %v", err)) } } ``` -------------------------------- ### Generate Documentation Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/README.md Generates documentation for Cherri actions. Use `--docs` for all actions or `--docs=category` for a specific category. ```bash cherri --docs # All actions ``` ```bash cherri --docs=device # Category ``` -------------------------------- ### Cherri If-Else Syntax Source: https://github.com/electrikmilk/cherri/blob/main/_autodocs/7-control-flow.md Demonstrates the basic if-else syntax in Cherri for conditional execution. This structure compiles directly into Shortcuts' conditional actions. ```cherri if @x == 5 { alert("x is five") } else { alert("x is not five") } ``` -------------------------------- ### Compile and Run Cherri File Source: https://github.com/electrikmilk/cherri/blob/main/ReadMe.md Compiles and runs a Cherri source file. This is the basic command to process a .cherri file. ```bash cherri file.cherri ```