|
| 1 | +import { execFile, execFileSync } from "node:child_process"; |
| 2 | +import { randomUUID } from "node:crypto"; |
| 3 | +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; |
| 4 | +import { tmpdir } from "node:os"; |
| 5 | +import { join } from "node:path"; |
| 6 | +import { setTimeout } from "node:timers/promises"; |
| 7 | +import { promisify } from "node:util"; |
| 8 | +import { displayNames, Language } from "./options.js"; |
| 9 | + |
| 10 | +const execFileAsync = promisify(execFile); |
| 11 | + |
| 12 | +type CommandOptions = { |
| 13 | + bin: string; |
| 14 | + printWidth?: number; |
| 15 | + sqlDialect?: string; |
| 16 | +}; |
| 17 | + |
| 18 | +export type ShortcutsOptions = CommandOptions & { |
| 19 | + languages: Language[]; |
| 20 | + outDir: string; |
| 21 | +}; |
| 22 | + |
| 23 | +function escapeXml(value: string): string { |
| 24 | + return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); |
| 25 | +} |
| 26 | + |
| 27 | +function shellCommand(language: Language, { bin, printWidth, sqlDialect }: CommandOptions): string { |
| 28 | + const parts = ["pbpaste", "|", bin, language]; |
| 29 | + |
| 30 | + if (printWidth !== undefined) parts.push(`--print-width=${printWidth}`); |
| 31 | + if (sqlDialect && language.startsWith("sql")) parts.push(`--sql-dialect=${sqlDialect}`); |
| 32 | + |
| 33 | + return parts.join(" "); |
| 34 | +} |
| 35 | + |
| 36 | +function shortcutPlist(name: string, command: string): string { |
| 37 | + const scriptUUID = randomUUID().toUpperCase(); |
| 38 | + const clipboardUUID = randomUUID().toUpperCase(); |
| 39 | + |
| 40 | + return `<?xml version="1.0" encoding="UTF-8"?> |
| 41 | +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 42 | +<plist version="1.0"> |
| 43 | +<dict> |
| 44 | + <key>WFWorkflowName</key> |
| 45 | + <string>${escapeXml(name)}</string> |
| 46 | + <key>WFWorkflowClientVersion</key> |
| 47 | + <string>2607.0.2</string> |
| 48 | + <key>WFWorkflowMinimumClientVersion</key> |
| 49 | + <integer>900</integer> |
| 50 | + <key>WFWorkflowMinimumClientVersionString</key> |
| 51 | + <string>900</string> |
| 52 | + <key>WFWorkflowIcon</key> |
| 53 | + <dict> |
| 54 | + <key>WFWorkflowIconStartColor</key> |
| 55 | + <integer>463140863</integer> |
| 56 | + <key>WFWorkflowIconGlyphNumber</key> |
| 57 | + <integer>59446</integer> |
| 58 | + </dict> |
| 59 | + <key>WFWorkflowTypes</key> |
| 60 | + <array> |
| 61 | + <string>WFWorkflowTypeShowInSearch</string> |
| 62 | + </array> |
| 63 | + <key>WFWorkflowInputContentItemClasses</key> |
| 64 | + <array/> |
| 65 | + <key>WFWorkflowImportQuestions</key> |
| 66 | + <array/> |
| 67 | + <key>WFWorkflowActions</key> |
| 68 | + <array> |
| 69 | + <dict> |
| 70 | + <key>WFWorkflowActionIdentifier</key> |
| 71 | + <string>is.workflow.actions.runshellscript</string> |
| 72 | + <key>WFWorkflowActionParameters</key> |
| 73 | + <dict> |
| 74 | + <key>Script</key> |
| 75 | + <string>${escapeXml(command)}</string> |
| 76 | + <key>Shell</key> |
| 77 | + <string>/bin/bash</string> |
| 78 | + <key>UUID</key> |
| 79 | + <string>${scriptUUID}</string> |
| 80 | + </dict> |
| 81 | + </dict> |
| 82 | + <dict> |
| 83 | + <key>WFWorkflowActionIdentifier</key> |
| 84 | + <string>is.workflow.actions.setclipboard</string> |
| 85 | + <key>WFWorkflowActionParameters</key> |
| 86 | + <dict> |
| 87 | + <key>UUID</key> |
| 88 | + <string>${clipboardUUID}</string> |
| 89 | + <key>WFInput</key> |
| 90 | + <dict> |
| 91 | + <key>Value</key> |
| 92 | + <dict> |
| 93 | + <key>OutputName</key> |
| 94 | + <string>Shell Script Result</string> |
| 95 | + <key>OutputUUID</key> |
| 96 | + <string>${scriptUUID}</string> |
| 97 | + <key>Type</key> |
| 98 | + <string>ActionOutput</string> |
| 99 | + </dict> |
| 100 | + <key>WFSerializationType</key> |
| 101 | + <string>WFTextTokenAttachment</string> |
| 102 | + </dict> |
| 103 | + </dict> |
| 104 | + </dict> |
| 105 | + </array> |
| 106 | +</dict> |
| 107 | +</plist> |
| 108 | +`; |
| 109 | +} |
| 110 | + |
| 111 | +// Shortcuts runs the script with a small PATH, so the shortcut needs the full path. |
| 112 | +export function findBin(): string | undefined { |
| 113 | + try { |
| 114 | + return execFileSync("which", ["format-code"], { encoding: "utf8" }).trim(); |
| 115 | + } catch { |
| 116 | + return undefined; |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +const signAttempts = 3; |
| 121 | +const retryDelayMs = 2000; |
| 122 | + |
| 123 | +// The "shortcuts sign" command sends the shortcut to Apple. Apple sometimes returns a server error. |
| 124 | +async function signShortcut(unsignedPath: string, signedPath: string): Promise<void> { |
| 125 | + const signArgs = ["sign", "--mode", "anyone", "--input", unsignedPath, "--output", signedPath]; |
| 126 | + |
| 127 | + for (let attempt = 1; ; attempt++) { |
| 128 | + try { |
| 129 | + await execFileAsync("shortcuts", signArgs); |
| 130 | + return; |
| 131 | + } catch (e) { |
| 132 | + const stderr = (e as { stderr?: string }).stderr?.trim(); |
| 133 | + |
| 134 | + if (attempt === signAttempts) { |
| 135 | + throw new Error(`Cannot sign ${signedPath}: ${stderr || e}`, { cause: e }); |
| 136 | + } |
| 137 | + |
| 138 | + console.error(`Cannot sign ${signedPath}: ${stderr || e}. Try again in ${retryDelayMs / 1000} s.`); |
| 139 | + await setTimeout(retryDelayMs); |
| 140 | + } |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +// Signing takes a few seconds for each shortcut, so give each path as soon as it is signed. |
| 145 | +export async function* generateShortcuts({ |
| 146 | + languages, |
| 147 | + outDir, |
| 148 | + ...commandOptions |
| 149 | +}: ShortcutsOptions): AsyncGenerator<string> { |
| 150 | + const workDir = mkdtempSync(join(tmpdir(), "format-code-shortcuts-")); |
| 151 | + |
| 152 | + mkdirSync(outDir, { recursive: true }); |
| 153 | + |
| 154 | + try { |
| 155 | + for (const language of languages) { |
| 156 | + const name = `Format ${displayNames[language]}`; |
| 157 | + // The "shortcuts sign" command accepts only an input file with the .shortcut extension. |
| 158 | + const unsignedPath = join(workDir, `${language}.shortcut`); |
| 159 | + const signedPath = join(outDir, `${name}.shortcut`); |
| 160 | + |
| 161 | + writeFileSync(unsignedPath, shortcutPlist(name, shellCommand(language, commandOptions))); |
| 162 | + await signShortcut(unsignedPath, signedPath); |
| 163 | + yield signedPath; |
| 164 | + } |
| 165 | + } finally { |
| 166 | + rmSync(workDir, { recursive: true, force: true }); |
| 167 | + } |
| 168 | +} |
0 commit comments