Sources/OrgstarCLI/Tool.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Sources/OrgstarCLI/Tool.swift

120 lines · 5716 bytes

  1import Foundation
  2
  3/// The `orgstar` command: reads the command line, runs a command, and returns the exit status.
  4@MainActor
  5enum Tool {
  6    static let help = """
  7    Usage: orgstar <command> [<arguments>]
  8
  9    Works on your org files directly, with orgstar's configuration folder and folders, whether or
 10    not the app is running.
 11
 12    Commands:
 13      agenda [<view>]                 print the agenda or a view of views.toml
 14      capture <key> [<text>]          file an entry with a capture template
 15      clock in <file>::<heading>      start the clock on a heading
 16      clock out                       stop the running clock
 17      clock status                    show the running clock
 18      export <file> --to <format>     export to html, md, pdf, latex, odt, txt or reveal
 19      tangle <file>                   write the file's code blocks to their files
 20      open <file>[::<heading>]        open a file in orgstar, at a heading
 21
 22    Options:
 23      -h, --help                      this help; orgstar <command> --help for a command's
 24      --version                       the version
 25
 26    Exit status:
 27      0  done
 28      1  failed: a file couldn't be read, written or exported, or changed meanwhile
 29      2  usage: an unknown command or option, or a missing argument
 30      3  not found: no such file, heading, view or template; no running clock
 31      4  refused: a capture question without an answer, or a file that can't be changed here
 32         (encrypted, not UTF-8, or a command that needs the app)
 33
 34    Environment:
 35      ORGSTAR_CONFIG_DIR  the configuration folder, else $XDG_CONFIG_HOME/orgstar or ~/.config/orgstar
 36      ORGSTAR_DATA_DIR    the data folder (the app's folder list, running clock and recovery
 37                          versions), else ~/Library/Application Support/Orgstar
 38      ORGSTAR_ROOT        a folder to read besides those added in the app
 39    """
 40
 41    static let openHelp = """
 42    Usage: orgstar open <file>[::<heading>]
 43           orgstar open <file>::id:<id> | id:<id>
 44
 45    Opens the file in orgstar, at the heading when one is named: its title (with or without a
 46    leading *), #custom-id or id:ID.
 47    """
 48
 49    static func run(_ arguments: [String], host: Host) -> Int32 {
 50        guard let command = arguments.first else {
 51            host.error(help + "\n")
 52            return ExitCode.usage.rawValue
 53        }
 54        let rest = Array(arguments.dropFirst())
 55        let helps = ["agenda": AgendaCommand.help, "capture": CaptureCommand.help, "clock": ClockCommand.help, "export": ExportCommand.help,
 56                     "tangle": ExportCommand.tangleHelp, "open": openHelp]
 57        switch command {
 58        case "-h", "--help", "help":
 59            if let topic = rest.first {
 60                guard let text = helps[topic] else { return fail(Failure(.usage, "help: no command \(topic)"), host) }
 61                host.print(text)
 62            } else {
 63                host.print(help)
 64            }
 65            return ExitCode.success.rawValue
 66        case "--version":
 67            host.print("orgstar \(version(host))")
 68            return ExitCode.success.rawValue
 69        default:
 70            break
 71        }
 72        guard let text = helps[command] else { return fail(Failure(.usage, "unknown command \(command); see orgstar --help"), host) }
 73        if rest.contains("--help") || rest.contains("-h") {
 74            host.print(text)
 75            return ExitCode.success.rawValue
 76        }
 77        let workspace = Workspace(host: host)
 78        do {
 79            switch command {
 80            case "agenda": try AgendaCommand.run(rest, workspace)
 81            case "capture": try CaptureCommand.run(rest, workspace)
 82            case "clock": try ClockCommand.run(rest, workspace)
 83            case "export": try ExportCommand.run(rest, workspace)
 84            case "tangle": try ExportCommand.tangle(rest, workspace)
 85            default: try open(rest, workspace)
 86            }
 87        } catch {
 88            return fail(error, host)
 89        }
 90        return ExitCode.success.rawValue
 91    }
 92
 93    static func fail(_ failure: Failure, _ host: Host) -> Int32 {
 94        if !failure.message.isEmpty { host.error("orgstar: \(failure.message)\n") }
 95        return failure.code.rawValue
 96    }
 97
 98    /// The app's version, from the Info.plist of the app around this executable.
 99    static func version(_ host: Host) -> String {
100        guard let app = host.app, let info = NSDictionary(contentsOf: app.appendingPathComponent("Contents/Info.plist")),
101              let version = info["CFBundleShortVersionString"] as? String else { return "(development build)" }
102        let build = info["CFBundleVersion"] as? String
103        return build.map { $0 == version ? version : "\(version) (\($0))" } ?? version
104    }
105
106    /// `open`: the app's own link to the entry, `orgstar://entry`, opened by the app this
107    /// executable is in, else by whichever app handles the link.
108    static func open(_ words: [String], _ workspace: Workspace) throws(Failure) {
109        let arguments = try Arguments(words, command: "open", flags: [])
110        try arguments.expect(1, 1, "open")
111        let target = try workspace.target(arguments.positional[0])
112        var link = URLComponents()
113        link.scheme = "orgstar"
114        link.host = "entry"
115        link.queryItems = [URLQueryItem(name: "path", value: target.path), URLQueryItem(name: "offset", value: String(target.offset ?? 0))]
116        guard let url = link.url?.absoluteString else { throw Failure(.failure, "Can't make a link to \(target.path)") }
117        let status = workspace.host.open((workspace.host.app.map { ["-a", $0.path] } ?? []) + [url])
118        guard status == 0 else { throw Failure(.failure, "open couldn't open \(url)") }
119    }
120}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form